Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

Filter ListBox with dependent comboboxes - Excel vba

0

SOS

Hi

I've benn struggling for while to filter ListBox1 based on dependent comboboxes.

Any suggestions?

I welcome all advice to improve this project.

Cheers

Carlo

Answer
Discuss

Answers

0
Selected Answer

Hi Carlo

Here's an approach you might try...

In the attached revised file, I've modified your FilterListBox1 code to the following:

'FILTER LISTBOX EQUALS
Sub FilterListboxEquals(Contr As String, LBCol As Long)
' Skip this when UF is started
If Init = False Then Exit Sub

    ' step backwards through list
    For i = ListBox1.ListCount - 1 To 0 Step -1
    'delete items not matching
        If ListBox1.List(i, LBCol - 1) <> Me.Controls(Contr).Text Then
            ListBox1.RemoveItem i
        End If
    Next i
End Sub

where 1) it does nothing when the chnage arise from UF initialization since I've declare a public varaible Init at the top of the UF code:

Public Init As Boolean

that becomes True after the UF appears:

'INITIALIZATION OF UF_Report_Global
Private Sub UserForm_Initialize()
    ' << your existing code not shown...>>

        lbl_Search.Visible = True 'Show the word "Search" in front of TextBox_Search.

    Application.ScreenUpdating = True
    Init = True

End Sub

and 2) it runs backwards through the list on screen removing any items not matching the value in the control which called it. For Team, Shift, Category and Status the code is similar but it passes different values (in bold below) to the filter code above:

'FILTER TEAM
Private Sub cbo_Team_Change()

    If Init = False Then Exit Sub
    ' call the = filter for visible column 2
    Call FilterListboxEquals("cbo_Team", 2)
   lbl_Filtered.Caption = ListBox1.ListCount  'Show number of filtered items
End Sub

'FILTER Shift
Private Sub cbo_Shift_Change()
   If Init = False Then Exit Sub
   ' call the = filter for visible column 6
   Call FilterListboxEquals("cbo_Shift", 6)
    lbl_Filtered.Caption = ListBox1.ListCount  'Show number of filtered items
End Sub

'FILTER CATEGORY
Private Sub cbo_Category_Change()
    ' call the = filter for visible column 12
   Call FilterListboxEquals("cbo_Category", 12)
    lbl_Filtered.Caption = ListBox1.ListCount  'Show number of filtered items
End Sub

'FILTER STATUS
Private Sub cbo_Status_Change()
    ' call the = filter for visible column 13
   Call FilterListboxEquals("cbo_Status", 13)
    lbl_Filtered.Caption = ListBox1.ListCount  'Show number of filtered items
End Sub

You can change one or all items but will need to use your Reset button to clear the filters and start again.

You will need to write a FilterListBoxGreater for the start date and similar for the end date but can call them in a similar way..

Revision 29 June 2023

Second file added which implements Start and End date filters (in a similar way) but disables controls as a filter is set- new purple refresh button added to UserForm (after Start Date to Shift filter entries).

Revision 02 July 2023

Replaced second file (correcting UF _Initialization line Init = False) and added following explanatory comments following user response...

Second file is similar to first but StartDate is filtered by this procedure:

'FILTER cboStartDate
Private Sub cboStartDate_Change()
    ' call the = filter for visible column 4
   Call FilterListboxMonthPlus("cboStartDate", 4)
    lbl_Filtered.Caption = ListBox1.ListCount  'Show number of filtered items

End Sub
which calls the new (but similar):
'FILTER LISTBOX MONTH OR LATER
Sub FilterListboxMonthPlus(Contr As String, LBCol As Long)
' Skip this when UF is started
If Init = False Then Exit Sub

    ' step backwards through list
    For i = ListBox1.ListCount - 1 To 0 Step -1
    'delete items not matching
        If ListBox1.List(i, LBCol - 1) < CDate(Me.Controls(Contr).Text) Then
            ListBox1.RemoveItem i
        End If
    Next i
    ' prevent changes (except Reset)
    Me.Controls(Contr).Enabled = False
End Sub

The code for the end date changes is similar but calls new sub FilterListboxMonthLess which just reverses the operator giving this line:

If ListBox1.List(i, LBCol - 1) > CDate(Me.Controls(Contr).Text) Then

FilterListboxEquals (used by the chnage codes for other filters) now includes the same new lines above): 

    ' prevent changes (except Reset)
    Me.Controls(Contr).Enabled = False
so that selection can't be remade (until reset).

Furthermore, since the reset code just calls the Sub UserForm_Initialize procedure, the sleected items (and all others) are re-enabled by the code in bold below):

'INITIALIZATION OF UF_Report_Global
Private Sub UserForm_Initialize()
    Sheets("REPORT").Activate

    Application.ScreenUpdating = False
    ' prevent triggering _Change procedures
    Init = False

        cbo_Team.Value = "All"
        cbo_Shift.Value = "All"
        cbo_Category.Value = "All"
        cbo_Status.Value = "All"

        cbo_Team.List = Array("All", "Team 1", "Team 2", "Team 3", "Team 4")
        cbo_Shift.List = Array("All", "First", "Second", "Third")
        cbo_Category.List = Array("All", "A", "B")
        cbo_Status.List = Array("All", "RE", "IR")
        ' (re)enable CB controls
        cboStartDate.Enabled = True
        cboEndDate.Enabled = True
        cbo_Team.Enabled = True
        cbo_Shift.Enabled = True
        cbo_Category.Enabled = True
        cbo_Status.Enabled = True

Hope this helps.

Discuss

Discussion

Thank you John for your quick response.

The code needs improvement and Test.

Please note that the goal is to have dependancy between all comboboxes.

All filters rely on the first step, Period(cboStartDate to cboEndDate).
Unfortunatly, Period filter doesn't work.

Team filter works only once. Other attemps lead to blank ListBox
Shift  filter only works only once. Other attemps lead to blank ListBox
Category filter works only once. Other attemps lead to blank ListBox
Status filter works only once. Other attemps lead to blank ListBox

I will appreciate further proposition.

 
Carlo (rep: 6) Jun 27, '23 at 10:39 am
Carlo 

If you don't alter the dates, the existing filters apply successively (provided you chose a value from the filtered list).

I asked you to implement the date filter (following the same approach) but seems you haven't tried.

Note thst I did test my code and warned you that Reset would be needed to change selection values.

I'll see if I can find more spare time to to do more but I doubt it.
John_Ru (rep: 6142) Jun 27, '23 at 10:57 am
Thank you for being patient.
Carlo (rep: 6) Jun 27, '23 at 10:28 pm
In my approach the TextBox filtering worked only once (so successive changes to other boxes would filter what remaindex- and a wrong choice could lead to a blank result).

Do you want filtering (after the from and to dates) to apply from left to right? So picking Team then Shift etc. in order? 
John_Ru (rep: 6142) Jun 28, '23 at 3:04 am
Thank you for taking the time to help me. I'm slowing learning VBA.

In fact, I'd like to be able to filter data shown in the ListBox just like I would filter a spreadsheet data with filter arrow buttons next to the Table headers.

From the Userform Filter data from March 2023 to April 2023 should show data for this period only. Then whithin this selected period, I would be able to view related Teams. Among these Teams or one of them I would filter Shift, Category and Status. Any changes in any of the comboboxes would change the filtered data.

If I pick a month from one of the period comboboxes, it filters only data related to its value not the period(both comboboxes). That's my first concern. the other comboboxes would refer to that period.  That's pretty challenging for me.
Carlo (rep: 6) Jun 28, '23 at 8:59 am
Carlo. You said "If I pick a month from one of the period comboboxes... " but I didn't implement any changes for those controls. Currently the Team and other category textboxes affect data for all dates.
John_Ru (rep: 6142) Jun 28, '23 at 10:52 am
So sorry for expressing my self poorly which may impact your reputation and makes you feel bad. It was probably due to the fact English is not my native language.

I will welcome any other suggestions.
Carlo (rep: 6) Jun 28, '23 at 11:27 am
Your language is fine Carlo. I'll try to find time tomorrow to help you (but I expect to be busy). Please be patient.

One question- once you have a filtered list in the ListBox, what will you do with it? (Apart from look at it!) 
John_Ru (rep: 6142) Jun 28, '23 at 12:06 pm
In fact, this is just one part of the project. A Data entry Userform, a Dashboard(summary, Tables, filtering charts...) will be used as well. 

I plan to :
- Analyze data
- Import Data
- Export Data
- Extract data
- Send data to pdf form
- Print data 

Thank you so much for sharing your skills and knowledge.

I'll be waiting...
Carlo (rep: 6) Jun 28, '23 at 1:28 pm
Carlo. I'll try to revise my Answer (somewhat) tomorrow.

Your project is ambitious but please don't expect this (Q&A) Forum to create an entire project for you- that's not how it works! When you get stuck, ask a question here and hopefully someone will know the answer.

I'm not here to sell anything but you might consider Don's (paid) course " Professional Forms in Excel" - see the Course hypelink above
John_Ru (rep: 6142) Jun 28, '23 at 6:25 pm
Carlo please see Revision 29 June 2023 to my Answer and try the second file now attached. This filters for dates but disables controls as a (0ne-off) filter is set- new purple refresh button added to UF after text filters. 
John_Ru (rep: 6142) Jun 29, '23 at 5:23 pm
Very close to what I was looking for   :  ) I'm ok with it. Hope that one day I'll be able to help like you keep doing it.

Thank you so much John.    
Carlo (rep: 6) Jun 30, '23 at 5:04 pm
Thanks Carlo If you think it helps enough, kindly mark my Answer as Selected and I'll add explanatory notes for you/ other users.
John_Ru (rep: 6142) Jun 30, '23 at 5:32 pm
Thanks for selecting my Answer, Carlo. I'll try to add explanatory notes to my revision later today (UK time) 
John_Ru (rep: 6142) Jun 30, '23 at 7:10 pm
Carlo. Add notes and corrected an important typo (so please use revised second file). 
John_Ru (rep: 6142) Jul 2, '23 at 8:40 am
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login