用于填充列表框的过滤数据数组

Leo*_*n S 5 excel vba listbox

好的,我正在按标准过滤工作表(“数据”):

Sub Filter_Offene()
    Sheets("Data").Range("A:R").AutoFilter Field:=18, Criteria1:="WAHR"
End Sub

Run Code Online (Sandbox Code Playgroud)

然后,我想将过滤表填充到列表框我的问题是,行数可能会有所不同,所以我想我可以尝试通过执行以下 cells.find 例程来列出过滤表“结束”的位置:

Dim lRow As Long
Dim lCol As Long

    lRow = ThisWorkbook.Sheets("Data").Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

lRow = lRow + 1
Run Code Online (Sandbox Code Playgroud)

不幸的是,这也计算“隐藏”行,因此在我的示例中,它不计算 2,而是计算 7。我.Range.SpecialCells(xlCellTypeVisible)以前使用过,但它似乎不适用于上面的 cells.find。有人知道如何计算可见(=过滤)表,然后将其放入列表框中吗?

编辑:我像这样填充列表框(未过滤):

Dim lastrow As Long
With Sheets("Data")
    lastrow = .Cells(.Rows.Count, "R").End(xlUp).Row
End With

With Offene_PZ_Form.Offene_PZ
.ColumnCount = 18
.ColumnWidths = "0;80;0;100;100;0;50;50;80;50;0;0;0;0;0;150;150;0"
.List = Sheets("Data").Range("A2:R" & lastrow).Value
End With
Run Code Online (Sandbox Code Playgroud)

但这不适用于过滤后的数据。

Nar*_*esh 2

以下是用于填充筛选行的 VBA 代码UserForm1.ListBox1.List。感谢@FaneDuru 根据他的评论对代码进行了改进。

在 Userform1 代码中

Private Sub UserForm_Initialize()
PopulateListBoxWithVisibleCells
End Sub
Run Code Online (Sandbox Code Playgroud)

模块内

子 PopulateListBoxWithVisibleCells()

Dim wb As Workbook, ws As Worksheet
Dim filtRng As Range, rw As Range
Dim i As Long, j As Long, x As Long, y As Long, k As Long, filtRngArr
i = 0: j = 0: x = 0: y = 0

Set wb = ThisWorkbook: Set ws = wb.Sheets("Sheet1")

Set filtRng = ws.UsedRange.Cells.SpecialCells(xlCellTypeVisible)

For Each Area In filtRng.Areas
x = x + Area.Rows.Count
Next
y = filtRng.Columns.Count
ReDim filtRngArr(1 To x, 1 To y)

For k = 1 To filtRng.Areas.Count
For Each rw In filtRng.Areas(k).Rows
    i = i + 1
    arr = rw.Value
    For j = 1 To y
    filtRngArr(i, j) = Split(Join(Application.Index(arr, 1, 0), "|"), "|")(j - 1)
    
    Next
Next
Next

With UserForm1.ListBox1
.ColumnCount = y
.List = filtRngArr
End With

End Sub
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我们还可以添加更多字段,例如行号,Split(rw.Row & "|" & Join(Application.Index(arr, 1, 0), "|"), "|")(j - 1)但对于每个这样的预期列增量,我们需要增加 y 的值,例如y = filtRng.Columns.Count + 1

为了找到 x(行数),我们不需要第一个循环......简单地说,x = filtRng.Cells.Count / filtRng.Columns.Count就足够了