【问题标题】:VBA ErrorHandler, msoFileDialogOpen Loops ForeverVBA ErrorHandler,msoFileDialog永远打开循环
【发布时间】:2015-06-29 14:22:15
【问题描述】:

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

【问题讨论】:

  • 你为什么要从内部调用例程?
  • 您希望它始终访问 ErrorHandler 还是忘记了 Exit Sub?
  • 从您发布的内容来看,ErrorHandler 永远不会被调用,因为没有“goto ErrorHandler”语句。请张贴在代码中的位置。另外,我同意 Roland 的观点,即您始终在 MsgBox 之后包含 Exit Sub 或 Resume。

标签: vba excel ms-office excel-2010


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 2015-08-13
    相关资源
    最近更新 更多