【问题标题】:Excel User forms in vbavba中的Excel用户表单
【发布时间】:2014-02-06 13:36:44
【问题描述】:

我正在使用 Forms 开发 VBA 代码。我有一个特定的按钮选项可以让用户使用 FileDialog 选择工作簿。工作簿文件本身可能包含 4 或 5 张工作表。我有空的组合框。

我需要在不打开工作簿的情况下自动在组合框中列出用户选择的工作簿的工作表名称。

我尝试使用以下代码,但得到了已打开工作簿的名称。

Private Sub CommandButton2_Click()
Set myfile = Application.FileDialog(msoFileDialogOpen)
    With myfile
    .Title = "Choose File"
    .AllowMultiSelect = False
        If .Show <> -1 Then
         Exit Sub
        End If
Fileselected = .SelectedItems(1)
    End With
With Fileselected
    For i = 1 To Sheets.Count
            ComboBox2.AddItem Sheets(i).Name
    Next i
End With

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    目前Sheets 指的是当前工作簿,因为您对Fileselected 不执行任何操作。

    您必须打开所选文件,否则如何检查其内容?

    Set myfile = Application.FileDialog(msoFileDialogOpen)
    With myfile
        .Title = "Choose File"
        .AllowMultiSelect = False
        If .Show <> -1 Then
            Exit Sub
        End If
    
        Fileselected = .SelectedItems(1)
    End With
    
    Dim doc As Workbook
    Set doc = Application.Workbooks.Open(Fileselected)
    
    With doc
        For i = 1 To .Sheets.Count
            ComboBox2.AddItem .Sheets(i).Name
        Next i
    
        .Close
    End With
    

    【讨论】:

    • After.AllowMultiSelect 你可以添加.Filters.Add "Excel Documents", "*.xls; *.xlsx; *.xlsm", 1 来过滤excel文档
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    • 2021-05-16
    相关资源
    最近更新 更多