VBA ErrorHandler,msoFileDialogOpen永远循环

时间:2015-06-29 14:22:16

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

我的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

1 个答案:

答案 0 :(得分:1)

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

    For Each vFileName In .SelectedItems
        MsgBox strFilename
        FunctionFileExplorer
    Next

如果您希望用户能够选择多个文件,然后您对这些文件执行某些操作,则代码为:

我删除了您不需要的代码,并在错误处理程序之前添加了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