从数组中填充listbox.list

时间:2014-05-12 08:26:35

标签: arrays excel excel-vba optimization listbox vba

            x= range("A1:d100000").value
            For i = 1 To UBound(x, 1)

            Sk = x(i, 1) & "·" & x(i, 2) & "·" & x(i, 3) & "·" & x(i, 4)

            If InStr(x(i,4), "text") Then
              s = s & "~" & Sk
            Else
            End If
            Next i


            ListBox1.List = Split(Mid$(s, 2), "~")

此代码将匹配结果放入(ActiveX)listbox.list 1列

如何根据SK列数将匹配结果放到listbox.list中,所以

if x(i, 1) & "·" & x(i, 2) 
so put x(i,1) to listbox 1 column, x(i,2) to listbox 2 column

if x(i, 1) & "·" & x(i, 2) & "·" & x(i, 3)
so put x(i,1) to listbox 1 column, x(i,2) to listbox 2 column, x(i,3) to listbox 3 column

这段代码做得很好,但需要花费三倍

   q = Split(Mid$(s, 2), "~")

    With ListBox1
        .Clear
        For Li = LBound(q) To UBound(q)
            q1 = Split(q(Li), "·")
            .ColumnCount = UBound(q1) + 1
            .ColumnWidths = Replace(Space(UBound(q1)), " ", "200;") & 200
            .AddItem q1(0), Li
            For Li2 = 1 To UBound(q1)
                .List(Li, Li2) = q1(Li2)
            Next Li2
        Next Li
'        Stop
    End With

无论如何加速这段代码?

1 个答案:

答案 0 :(得分:0)

当您从Range读取.Value属性时,您将获得一个基于1的数组。 ActiveX列表框的List属性需要基于0的数组。 .AddItem属性总是很慢,当你只有几个项目时应该使用它。对于任何多个项目,将数据转换为基于0的数组并使用List属性。

Sub FillLb()

    Dim vaRange As Variant
    Dim aList() As Variant
    Dim i As Long, j As Long

    vaRange = Sheet1.Range("A1:D100000")
    ReDim aList(0 To UBound(vaRange, 1) - 1, 0 To UBound(vaRange, 2) - 1)
    Sheet1.ListBox1.ColumnCount = UBound(vaRange, 2)

    For i = LBound(vaRange, 1) To UBound(vaRange, 1)
        For j = LBound(vaRange, 2) To UBound(vaRange, 2)
            aList(i - 1, j - 1) = vaRange(i, j)
        Next j
    Next i

    Sheet1.ListBox1.List = aList

End Sub