【问题标题】:How to populate userform listbox with a filtered range from a worksheet如何使用工作表中的过滤范围填充用户表单列表框
【发布时间】:2019-12-24 18:47:27
【问题描述】:

我有一个用户窗体列表框,我想在其中填充来自 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

【问题讨论】:

    标签: excel vba filter listbox populate


    【解决方案1】:

    限定整行...

    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) 一个数组,该数组的维度为高以将列表缩短到更合适的计数。

    【讨论】:

      猜你喜欢
      • 2013-02-26
      • 2016-02-29
      • 1970-01-01
      • 1970-01-01
      • 2019-01-24
      • 1970-01-01
      • 1970-01-01
      • 2014-02-15
      • 1970-01-01
      相关资源
      最近更新 更多