VBA ErrorHandler、msoFileDialogOpen Loops Forever

VBA ErrorHandler, msoFileDialogOpen Loops Forever

我的 ErrorHandler 和 msoFileDialogOpen 永远循环。这是我要修复的代码:

Public Sub FunctionFileExplorer()
'   Start File Explorer to select file containing data (simple GUI, much easier than coding in the file)

    With Application.FileDialog(msoFileDialogOpen)
        .AllowMultiSelect = True
        .Show

    vFileName = CVar(strFilename)
    '   Display paths of each file selected
        For Count = 1 To .SelectedItems.Count
        Next Count
        For Each vFileName In .SelectedItems
            MsgBox strFilename
            FunctionFileExplorer
        Next
    End With

    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

你的函数是一个递归函数,即它总是调用自己,所以它总是 运行 除非你给它一个退出点。在这里查看它调用自身的位置:

    For Each vFileName In .SelectedItems
        MsgBox strFilename
        FunctionFileExplorer
    Next

如果您希望用户能够 select 多个文件,然后您对这些文件进行处理,代码如下:

我删除了您不需要的代码并在错误处理程序前添加了 Exit Sub

Public Sub FunctionFileExplorer()
'   Start File Explorer to select file containing data (simple GUI, much easier than coding in the file)

Dim vFilename As Variant

    With Application.FileDialog(msoFileDialogOpen)
        .AllowMultiSelect = True
        .Show

    '   Display paths of each file selected
        For Each vFilename In .SelectedItems
            MsgBox vFilename
            'FunctionFileExplorer ' comment out this line
        Next
    End With

CleanUp:
    Exit Sub

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