如何在我的userform列表框中显示刚刚过滤的行

时间:2016-12-03 13:32:32

标签: excel vba excel-vba filter listbox

我有一个Excel工作表,一个用户表单和一个列表框在userform中。现在,当我通过单击我的用户表单上的按钮来过滤我的工作表并更新列表框时,我会看到列表框中的所有行。我的意思是listbox1显示所有单元格(过滤器+没有过滤器)。

我在VBA中有一点形成,但我需要代码,这对我来说非常重要。如果可能的话,请帮我详细说明和文件。

到目前为止,我的代码用于更新列表框:

Private Sub CommandButton1_Click()
  CommandButton10.Visible = True
  insertlist1.Visible = True
  ListBox1.Visible = True
  ListBox1.RowSource = "'NEWPRJ'!D7:D46"
End Sub

3 个答案:

答案 0 :(得分:1)

下面的代码只读取过滤器应用于“NEWPRJ”表格中的范围(“D7:D46”)后的可见单元格,它将它们保存到MyArr数组,然后在ListBox1中显示它们User_Form中的列表框。

使用.SpecialCells(xlCellTypeVisible)可以只读取可见的单元格。

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

答案 1 :(得分:1)

使用数组时,列表框标题消失了......
因此,您可以尝试使用两个想法解决问题:
1.对表格进行排序,使过滤后的值到达顶部(在表格的标题下);
2.过滤表格;

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

答案 2 :(得分:0)

更新Shai Rado代码,因为它将获得combox中填充的所有空白

implicit def hconsWH[H, TI <: HList, TO <: HList](
  implicit
  thatThingINeedToLiftAToWrapperA: Encoder[A], // whatever is needed to lift A => Wrapper[A]
  tailWH: WrapperHelper.Aux[TI, TO]
): WrapperHelper.Aux[H :: TI, Wrapper[H] :: TO]

这只是我添加的陈述,以消除组合框下拉列表中的任何空白。