How to show just filtered rows in my userform listbox

前端 未结 3 1860
甜味超标
甜味超标 2021-01-24 08:53

I have one Excel sheet, one userform and a listbox is in userform. Now when i filter my sheet and update listbox by click on button that is on my user form i see all rows in lis

3条回答
  •  情歌与酒
    2021-01-24 09:07

    The code below reads only Visible cells after Filter was applied to Range("D7:D46") in "NEWPRJ" sheet, it saves them to MyArr array, and then shows them in ListBox1 listbox in your User_Form.

    Using .SpecialCells(xlCellTypeVisible) allows reading only visible cells.

    Option Explicit
    
    Private Sub CommandButton1_Click()
    
    Dim cell As Range
    Dim MyArr  As Variant, i As Long
    
    ' intialize array to high number of elements at start
    ReDim MyArr(0 To 10000)
    
    ' work on sheets "NEWPRJ" according to PO
    With Sheets("NEWPRJ")
        ' scan each cell in Range "D7:D46" only on visible cells (cells that are visible after the filter was applied)
        For Each cell In .Range("D7:D46").SpecialCells(xlCellTypeVisible)
            MyArr(i) = cell.Value ' read all visible cells to array
            i = i + 1
        Next cell
        ' reduce array size to populated elements only
        ReDim Preserve MyArr(0 To i - 1)
    
        ' populate listbox with array
        ListBox1.List = MyArr
    End With
    
    End Sub
    

提交回复
热议问题