循环遍历几个列表框vba

时间:2013-03-05 17:24:50

标签: excel-vba for-loop listbox vba excel

我有以下代码,当然它不起作用,但我希望它表明我的意图。

Dim lItem As Long
Dim input_sh As Worksheet
Dim lb As ListBox
Set input_sh = ActiveWorkbook.Sheets("Input")
    For i = 1 To 4
        lb = "ListBox" & i
        For lItem = 0 To lb.ListCount - 1
            If lb.Selected(lItem) = True Then
                input_sh.Cells(1, 14 + i) = lb.List(lItem)
                lb.Selected(lItem) = False
            End If
        Next lItem
    Next i

基本上我在userform中有4个列表框,并且会使用for循环来获取所选项目,而不是为每个列表框设置for循环。

1 个答案:

答案 0 :(得分:0)

这个问题在评论中得到了解答,但只是为了使它成为堆栈中一个不那么未回答的问题(并最终在关闭投票堆栈中):

Dim input_sh As Worksheet
Dim lb As ListBox

Set input_sh = ActiveWorkbook.Sheets("Input")
For i = 1 To 4

    Set lb = Controls("ListBox" & i)

    ' object "lb" now contains a reference to the appropriate ListBox control.
    ' (do something with lb)

Next i

这是VB6和VBA之间的差异之一:在VBA中不能有控制数组。在VB6中,您可以命名所有ListBox,比如说MyListBox,并为它们提供1到4之间的索引,使代码看起来像这样:

Dim lb As ListBox

For i = 1 To 4

    Set lb = MyListBox(i)

    ' object "lb" now contains a reference to the appropriate ListBox control.
    ' (do something with lb)

Next i