Excel VBA:ListBox-UserForm变量创建问题

时间:2013-09-20 17:39:11

标签: excel vba excel-vba

在其他网站上查看了其他类似问题,但无法找到解决方案。

我正在尝试从listbox-userform的内容生成变量。列表中的内容是工作簿的名称。第一段代码向您展示了如何生成列表的内容供您参考。第二段代码是有问题的代码。

Private Sub CommandButton1_Click()
    Dim wb As Workbook

    For Each wb In Workbooks
        With ListBox1
            .AddItem (wb.Name)
        End With
    Next wb
lbl_Exit:
End Sub

我在下面的For Each行中收到Object Required错误。这段代码位于Userform

Private Sub CommandButton3_Click()
    Dim MainBook As Workbook
    Dim ListBox1 As ListBox

    For Each Item In ListBox1
        If Item.Name Like "Aggregate" Then
            Item.Select
            Set MainBook = Selection
        End If
    Next
End Sub

注意:我读到Item是ListBox的一个属性,这是我从中得到的。

1 个答案:

答案 0 :(得分:0)

这是你在尝试的吗?

Private Sub CommandButton1_Click()
    Dim wb As Workbook

    For Each wb In Workbooks
        With ListBox1
           .AddItem (wb.Name)
        End With
    Next wb
End Sub

Private Sub CommandButton2_Click()
    Dim MainBook As Workbook, i as Long

    For i = 0 To (ListBox1.ListCount -1)
        If ListBox1.List(i) Like "Aggregate" Then
            Set MainBook = Workbooks(ListBox1.List(i))
            MainBook.Activate
            Exit For
        End If
    Next
End Sub