优化msoFileDialogOpen

时间:2015-06-30 17:50:51

标签: vba excel-vba ms-word word-vba office-2010

我试图让这个msoFileDialogOpen允许用户选择多个文件。有没有更好的方法来做到这一点:

Public Sub Function3_FileExplorer()
    ' Start File Explorer to select file containing data (simple GUI, much
    ' easier than coding vFileName)
    vuserChoiceDataFileNumber = InputBox("Enter the number of files you want to select.")
    With Application.FileDialog(msoFileDialogOpen)
        Select Case IsNumeric(vuserChoiceDataFileNumber)
            Case True
                If VarType(vuserChoiceDataFileNumber) = 2 Or 3 Then
                    iuserChoiceDataFileNumber = CInt(vuserChoiceDataFileNumber)
                End If
            Case False
                MsgBox (vuserChoiceDataFileNumber & " is not an integer.")
                .AllowMultiSelect = False
        End Select
        .Show
    End With
    Exit Sub
    On Error GoTo ErrorHandler
    .AllowMultiSelect = True
    ErrorHandler:
    MsgBox "Error detected" & vbNewLine & "Error" & Err.Number & ": " & _
        Err.Description, vbCritical, "Error Handler: Error " & Err.Number
    MsgBox "If you want to force the program to run, go to the line below and " & _
        "insert a ' mark to comment the line out." & vbNewLine & _
        "On Error GoTo ErrorHandler", vbCritical, "Error Handler: Error " & Err.Number
End Sub

1 个答案:

答案 0 :(得分:2)

是的,你可以通过不询问用户他们想要打开多少文件来简化这一过程 - 只需让他们选择任意数量的文件。

Public Sub Function3_FileExplorer()
    '   Start File Explorer to select file containing data (simple GUI, much easier than coding vFileName)
    With Application.FileDialog(msoFileDialogOpen)
        .AllowMultiSelect = True
        .FilterIndex = 2
        If .Show Then
            Dim file As Variant
            For Each file In .SelectedItems
                ' do something with the file, for example, open it:
                Application.Workbooks.Open (file)
            Next file
        End If
    End With
End Sub