启动时多列ListBox填充-运行时错误

时间:2019-07-05 15:47:40

标签: excel vba

我试图用唯一工作表上指定的用户信息填充列表框的三个不同列

我只能用一列来完成此操作,但是在尝试添加几列时遇到了麻烦。我想选择必要的数据,并将每一列分配给各自的数组,但是它总是告诉我我的下标超出范围。

如果我将一个范围分配给一个数组,则可以使用以下行填充列表框:

Sheet1.name_List.List() = FirstNameArray

否则,我尝试使用以下代码填充所有三列...

Private Sub Workbook_Open()

    i = 0

    Application.ScreenUpdating() = False

    Sheets("Sheet2").Activate

    N = Cells(1, 1).End(xlDown).Row

    FirstNameArray = Range("A2:A" & N)
    SecondNameArray = Range("B2:B" & N)
    nIDArray = Range("C2:C" & N)

    For i = 0 To N
        With Sheet1.name_List
            .AddItem
            .List(i, 0) = FirstNameArray(i)
            .List(i, 1) = SecondNameArray(i)
            .List(i, 2) = nIDArray(i)
        End With
    Next i

    Sheets("Sheet1").Activate
    Application.ScreenUpdating = True

End Sub

*******编辑******

查看评论后,我将代码修改为以下代码段:

For i = LBound(FirstNameArray) To UBound(FirstNameArray)
    With Sheet1.name_List
        .AddItem
        .List(i, 0) = FirstNameArray(i, 1)
        .List(i, 1) = SecondNameArray(i, 1)
        .List(i, 2) = nIDArray(i, 1)
    End With
Next i

似乎FirstNameArray将其第一个索引分配给列表框的第一列,但是当它尝试分配SecondNameArray时出现错误。它显示无效的属性值。

2 个答案:

答案 0 :(得分:1)

在将工作表的范围分配给Variant数组时,无论该范围是一列还是多列,都将分配一个二维数组。因此,要引用数组中的第一项,您需要包括第二维。另外,请注意,List属性的索引从0开始,而数组从1开始。因此,您的For / Next循环应如下所示...

With Sheet1.name_list
    For i = LBound(FirstNameArray) To UBound(FirstNameArray)
        .AddItem
        .List(i - 1, 0) = FirstNameArray(i, 1)
        .List(i - 1, 1) = SecondNameArray(i, 1)
        .List(i - 1, 2) = nIDArray(i, 1)
    Next i
End With

答案 1 :(得分:0)

发生这种情况是因为您“离开”了阵列。

您的数组中有N-1个值:
Range("A2:A" & N)的N = 5将为您提供一个包含4个条目(A2,A3,A4,A5)的数组。

但是For i = 0 To N将循环6次,(0,1,2,3,4,5)

使用UBoundLBound循环数组:

For i = LBound(FirstNameArray) To UBound(FirstNameArray)

此外,您的Range对象也不完全合格,将隐式引用Activesheet。有关更多信息,请点击此处:https://rubberduckvba.wordpress.com/2018/03/15/vba-trap-default-members/

例如,从一开始就这样做:
编辑:现在使用二维数组,如OT注释中建议的@Domenic

Option Explicit

Private Sub Workbook_Open()

    dim i as long
    dim lastRow as long
    dim sht1 as excel.worksheet
    dim sht2 as excel.worksheet
    dim completeArray as Variant


    set sht1 = thisWorkbook.Worksheeets("Sheet1")
    set sht2 = thisWorkbook.Worksheeets("Sheet2")

    Application.ScreenUpdating() = False

    lastRow  = sht2.Cells(1, 1).End(xlDown).Row

    completeArray = sht2.Range("A2:C" & lastRow)

    With sht1.name_List
        .ColumnCount = 3
        'https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/ubound-function
        For i = LBound(completeArray, 1) To UBound(completeArray, 1)
            .AddItem
            .List(i - 1, 0) = completeArray(i, 1)
            .List(i - 1, 1) = completeArray(i, 2)
            .List(i - 1, 2) = completeArray(i, 3)
        Next i
    End With

    sht1.Activate
    Application.ScreenUpdating = True

End Sub