Search code examples
vbafilterlistboxcriterialistobject

selected items from the ListBoxes are the filter .criteria1 in the table


In active workbook.Sheets(1) I have a ListBoxes("List Box 1"). First I select items form this ListBoxes, then I want filtered table("table 1") in second worksheet. I don’t know why it doesn’t work.

'''

Sub group()

Dim i, j As Long
Dim lastrow As Long
Dim wb As Workbook
Dim wbNew As Workbook
Dim ListaI As Object 'listbox
Dim Wynik As String

Set wb = ActiveWorkbook

lastrow = WorksheetFunction.CountA(wb.Sheets(3).Columns("A:A")) 'in this column is a list of items


Set ListaI = wb.Sheets(1).ListBoxes("List Box 1") ' this listbox include value from wb.Sheets(3).Columns("A:A")

For i = 2 To lastrow
If ListaI.Selected(i) Then
    j = j + 1
    If j > 1 Then Wynik = Wynik ' to omit empty
    Wynik = Wynik & Chr(34) & ListaI.List(i) & Chr(34) & ", "
    
    
 End If
 Next


Wynik = Left(Wynik, Len(Wynik) - 2) ' to delite last comma, for example: "pen", "window", "door"


Set wbNew = Workbooks.Open(Filename:="C:\Users\username\Desktop\nameofphile.xlsx", ReadOnly:=True)

With wbNew.Sheets("name")
    .ListObjects("table 1").Range.AutoFilter Field:=1, Criteria1:=Wynik, _
     Operator:=xlFilterValues ' assigning selected values to a filter in a table
    
End With




End Sub

'''


Solution

  • Some suggestions:

    • Name your variables to something meaningful (i is hard to understand, counter it's easier)
    • Indent your code properly (you can use Rubberduckvba.com) to help you with data
    • Try to break your code into pieces (e.g. first set references, then counter, then create the filter array, then apply it)
    • Comment your code

    Read code's comments and adjust it to fit your needs

    Code:

    Option Explicit
    
    Public Sub FilterTableBySelectedItem()
        
        ' Set a referece to the workbook holding the listbox
        Dim sourceWorkbook As Workbook
        Set sourceWorkbook = ActiveWorkbook
        
        ' Set a reference to the worksheet holding the listbox
        Dim sourceSheet As Worksheet
        Set sourceSheet = sourceWorkbook.Worksheets("Sheet1")
        
        ' Set a reference to the listbox
        Dim sourceListbox As ListBox
        Set sourceListbox = sourceSheet.ListBoxes("List Box 1")
        
        ' Get total selected items in listbox
        Dim counter As Long
        For counter = 1 To sourceListbox.ListCount
            If sourceListbox.Selected(counter) Then
                Dim totalSelected As Long
                totalSelected = totalSelected + 1
            End If
        Next counter
        
        ' Add the selected items to an array
        Dim selectedItems As Variant
        ReDim selectedItems(totalSelected - 1)
        For counter = 1 To sourceListbox.ListCount
            If sourceListbox.Selected(counter) Then
                Dim selectedCounter As Long
                selectedItems(selectedCounter) = sourceListbox.List(counter)
                selectedCounter = selectedCounter + 1
            End If
        Next counter
        
        ' Uncomment this next lines if you plan to use the filter in another way,
        'Dim selectedItemsFilter As String
        'selectedItemsFilter = Join(selectedItems, ",")
        
        ' Set a reference to the workbook holding the table
        Dim targetWorkbook As Workbook
        Set targetWorkbook = Workbooks.Open(Filename:="C:\Temp\test.xlsx", ReadOnly:=True)
        
        ' Set a reference to the worksheet holding the table
        Dim targetSheet As Worksheet
        Set targetSheet = targetWorkbook.Worksheets("Sheet1")
        
        ' Set a reference to the table
        Dim targetTable As ListObject
        Set targetTable = targetSheet.ListObjects("Table1")
        
        ' Filter the table using the array of selected items
        targetTable.Range.AutoFilter Field:=1, Criteria1:=selectedItems, Operator:=xlFilterValues
    
    End Sub
    

    Let me know if it works