如何使用工作表中的过滤范围填充用户窗体列表框

时间:2019-08-19 14:16:40

标签: excel vba filter listbox populate

我有一个UserForm列表框,我想在其中填充excel工作表中的过滤范围(仅可见单元格)。问题出在这句话:userForm.listBox.RowSource = dataRng.Address,其中dataRng是可见单元格的范围(Set dataRng = sht.Range(Cells(startRow, 1), Cells(lastRow, 4)).SpecialCells(xlCellTypeVisible))。

我也尝试使用动态数组(MyArray(i, j) = dataRng.Cells(i, j).Value)来获得可见范围,然后用它来填充列表框,但是没有成功(出现标题问题,但似乎是最有效,最快的解决方案)。

几年前我发现了this unanswered question,但我正在寻找更好的解决方案。

 Private Sub listBox_Change()
    Dim startRow,lastRow As Integer
    Dim sht As Worksheet
   'Dim MyArray As Variant 'variant, receives one based 2-dim data field array

        Set sht = Worksheets("SheetName")
        Call filterData(sht) 'filter data in SheetName
        startRow = sht.Cells(Rows.Count, 1).End(xlDown).Row 'get initial row of filtered range
        lastRow = sht.Cells(Rows.Count, 1).End(xlUp).Row 'get last row of filtered range
        Set dataRng = sht.Range(Cells(startRow, 1), Cells(lastRow, 4)).SpecialCells(xlCellTypeVisible) 'get range of visible cells in SheetName

        With userForm.listBox

            .ColumnCount = 4
            .ColumnWidths = "90;90;0;90"
            .RowSource = dataRng.Address

    '    For i = startRow To lastRow
    '        For j = 1 To 3
    '            MyArray(i, j) = dataRng.Cells(i, j).Value
    '        Next j
    '    Next i

        End With

    End Sub

运行时错误380:无法设置RowSource属性。属性值无效。

Error message

1 个答案:

答案 0 :(得分:0)

确认整行...

Set dataRng = sht.Range(Cells(startRow, 1), Cells(lastRow, 4)).SpecialCells(xlCellTypeVisible)

上述不符合Cells()范围...应该是:

Set dataRng = sht.Range(sht.Cells(startRow, 1), sht.Cells(lastRow, 4)).SpecialCells(xlCellTypeVisible)

startrowlastrow ... sht.Rows.Count

也一样

编辑1:

380相关,我倾向于避免使用.RowSource并附加一个实际列表(尤其是在使用非连续范围时),因此将遍历过滤范围,如果可见,追加到列表中。

给出概念的未经测试的代码:

redim arr(lastrow)
with sht
    for i = startrow to lastrow
        if not .rows(i).entirerow.hidden then 
            arr(n) = .cell(i,1).value 'this appends col 1 (A) cells to a 1-dimensional array
            n = n + 1
        end if
    next i
end with
userform.listbox.list = arr

请注意,您可以在循环过程中redim preserve arr(ubound(arr)+1)来查找值,也可以在循环后的大小数组中循环,然后redim preserve arr(not_is_empty)遍历高尺寸的数组以将列表缩短到更合适的数目。 / p>