简体   繁体   English

VBA Excel:仅在列表框中显示可见的单元格

[英]VBA Excel: Show visible cells in listbox only

I have the below mentioned code, I am trying to load filtered cells only into the listbox but I don't know why the below mentioned code is not functional. 我有下面提到的代码,我试图将过滤后的单元格仅加载到列表框中,但我不知道为什么下面提到的代码不起作用。

Legend: 传说:

  • PatternSearchButton is a button PatternSearchButton是一个按钮
  • PatternTextBox is a textbox by which the user enters a value Which the Sheet will filter. PatternTextBox是一个文本框,用户可通过该文本框输入一个值,供工作表过滤。
  • WsLookup is a function which selects the sheet (completely functional) WsLookup是选择工作表的功能(完全功能)

     Private Sub PatternSearchButton_Click() Dim PatternInput As String, PatternCounter As Double, WsSelector As Worksheet PatternInput = PatternTextBox.Value Set WsSelector = WsLookup(GSMListType.Value) WsSelector.Range("F:F").AutoFilter Field:=1, Criteria1:=PatternInput PatternCounter = Application.WorksheetFunction.Subtotal(4, WsSelector.Range("F:F")) With AvailableNumberList .Clear For k = 2 To PatternCounter + 1 .AddItem WsSelector.Range("A" & k).SpecialCells(xlCellTypeVisible).Value Next k End With End Sub 

You're are using PatternCounter as the upper limit in your For .. Next but this is being set using the MAX (eg 4 ) subfunction of SUBTOTAL . 您正在使用PatternCounter作为For .. Next上限For .. Next ,可以使用SUBTOTALMAX (例如4 )子功能进行设置。 This might work on sequential numbers in an unfiltered list but it is unlikely to be accurate in a filtered list. 这可能适用于未过滤列表中的序列号,但在过滤列表中不太可能准确。 Using the COUNT ( 2/102 ) or COUNTA ( 3/103 ) subfunction might be more appropriate. 使用COUNT2/102 )或COUNTA3/103 )子功能可能更合适。

You were using SUBTOTAL(4, ...) so I would assume that you are dealing with numbers. 您正在使用SUBTOTAL(4, ...)所以我认为您正在处理数字。 Use a straight count on numbers on visible cells in column F and modify the remainder of the code to resemble this. 对F列中可见单元格上的数字进行直接计数,然后修改代码的其余部分以使其与此相似。

    PatternCounter = Application.WorksheetFunction.Subtotal(2, WsSelector.Range("F:F"))
    With WsSelector.cells(1,1).currentregion.offset(1,0).SpecialCells(xlCellTypeVisible)
        AvailableNumberList.Clear
        For k = 1 To PatternCounter
            AvailableNumberList.AddItem .cells(k, 1).Value
        Next k
    End With

The problem might stem from the fact that you add to the list box the value of a special cell that might not exist if the cell is hidden. 该问题可能源于以下事实:将特殊单元格的值添加到列表框中,如果该单元格是隐藏的,则该单元格可能不存在。

Try for the body of the For loop: 尝试使用For循环的主体:

' ... previous code '
If Not WsSelector.Rows(k).EntireRow.Hidden Then
        .AddItem WsSelector.Cells(k, 1).Value
End If
' rest of the code ... '

Also, make sure that AvailableNumberList points to the correct object in your code. 另外,请确保AvailableNumberList指向代码中的正确对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM