问题
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 list box. I mean listbox1 show all cells (filter+no filter).
I have a little in formation in VBA but i need the codes and it is so important for me. Please help me with detail and with file if possible.
My code so far for updating the list box:
Private Sub CommandButton1_Click()
CommandButton10.Visible = True
insertlist1.Visible = True
ListBox1.Visible = True
ListBox1.RowSource = "'NEWPRJ'!D7:D46"
End Sub
回答1:
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
回答2:
When using arrays, the listbox header goes away...
So you could try to solve the problem using two ideas:
1. Sort the table, to make the filtered values come to top (under the header of the table);
2. Filter the table;
Private Sub fillListBox()
'lstGrade as the listbox component
Dim oTab As ListObject
Dim oRng As Range
Set oTab = Sheets("Sheet1").ListObjects("MyTable")
'remove any filter and then sort the data using the "SomeValue" to stick it on top of the table
With oTab
.Range.AutoFilter
.Sort.SortFields.Clear
.Sort.SortFields.Add _
Key:=Range("MyTable[Column3]"), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
CustomOrder:="SomeValue", _
DataOption:=xlSortNormal
With .Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
'note that "SomeValue" is the same as in the sorted area above
oTab.Range.AutoFilter 2, "SomeValue"
'"save" the data into the new range object
Set oRng = oTab.DataBodyRange.SpecialCells(xlCellTypeVisible)
lstGrade.RowSource = oRng.Address
End Sub
来源:https://stackoverflow.com/questions/40948329/how-to-show-just-filtered-rows-in-my-userform-listbox