Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Excel VBA:ListBox用户表单变量创建问题_Vba_Excel - Fatal编程技术网

Excel VBA:ListBox用户表单变量创建问题

Excel VBA:ListBox用户表单变量创建问题,vba,excel,Vba,Excel,在其他网站上查看了其他类似问题,但找不到解决方案 我试图从listbox用户表单的内容生成变量。列表中的内容是工作簿的名称。第一段代码向您展示了如何生成列表内容供您参考。第二段代码就是有问题的代码 Private Sub CommandButton1_Click() Dim wb As Workbook For Each wb In Workbooks With ListBox1 .AddItem (wb.Name) En

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

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

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
对于下面的每一行,我在上得到一个
所需对象
错误。这段代码驻留在
用户表单中

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

注意:我读到
是列表框的一个属性,我从列表框中得到它

这就是你正在尝试的吗

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

是的,看起来不错,谢谢。但是有了新的变量MainBook,我可以在模块内的代码中自由引用它吗,或者我需要做什么特殊的事情才能将它从UserForm传输到模块?是的,你可以引用它,如果将
Dim MainBook As Workbook
移动到最顶端:),则只能在
CommandButton2\u单击
过程中使用它。