【问题标题】:VBA Error Handling when trying to open Workbook尝试打开工作簿时的 VBA 错误处理
【发布时间】:2019-04-30 21:30:24
【问题描述】:

我正在尝试遍历文件夹中的所有文件,打开它们并删除文档信息。我在处理无法打开的文件时遇到问题,或者在打开时弹出我们关于禁用宏的提示。我尝试使用 on error resume next 和 on error goto 0 来解决此问题。但随后出现运行时失败,因为当我尝试关闭已打开的文件时,我的工作簿对象 (wb) 尚未设置。

我已阅读有关“On Error Resume Next”和“On error goto 0”的文档,但我不相信我在这里正确使用它们。 非常感谢任何帮助,谢谢。

Option Explicit
Sub test_Scrubber_New()

Dim directory As String, fileName As String, i As Variant, wb As Workbook
Application.DisplayAlerts = False
Application.ScreenUpdating = False

'directory = "C:\Users\bayli\Desktop\Files for Testing\"
directory = "C:\Users\bayli\Desktop\excel files\"
fileName = Dir(directory & "*.xl??")

i = 0
Do While fileName <> ""
    On Error Resume Next
    Set wb = Workbooks.Open(directory & fileName)
    On Error GoTo 0
        'remove info
        ActiveWorkbook.RemoveDocumentInformation (xlRDIAll)
    wb.Close True
    i = i + 1
    fileName = Dir()
    Application.StatusBar = "Files Completed:  " & i
Loop

Application.StatusBar = False
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox "Complete"

End Sub

我更新了我的代码以包括: If Not wb Is Nothing 然后删除@PatricK 建议的信息,它正在工作,但是它不断停止并弹出关于更新链接的弹出窗口。如果我单击“不更新”,我的代码会根据需要继续工作,但有没有办法处理这个问题。我正在循环浏览超过 5k 个文件,因此您可以想象它需要一段时间。花费的时间不是问题,但目前我坐在这里不得不多次点击“不更新”。我认为 Application.DisplayAlerts = False 会阻止这些弹出窗口,但事实并非如此。

【问题讨论】:

  • 您尝试打开一个工作簿,如果失败则忽略错误,然后继续对该工作簿进行文字处理。那当然会失败,因为它无法打开!您需要捕获错误,然后执行其他操作。 If Err.Number &lt;&gt; 0 Then 'do something else
  • 请注意,如果您在打开文件时出现错误,ActiveWorkbook.RemoveDocumentInformation (xlRDIAll) 行将不管运行,并将在该 Activeworkbook 上。您可能希望将其切换为 wb.RemoveDocumentInformation(...)
  • @MichalRosa“你的代码是正确的”——我不敢苟同。 RemoveDocumentInformation 应该针对 wb,而不是 ActiveWorkbook。而On Error Resume Next 不是正确的错误处理。 “正确”代码不会愉快地在未知错误状态下运行,并在一切都着火时愉快地报告“完成”。硬编码的路径也是一个问题,iVariant 是非常值得怀疑的,xlRDIAll 是强制通过ByVal 无缘无故,Dir() 不需要多余的括号,程序名称可能更有意义,PascalCase 和明确的Public
  • @MichalRosa - 文件的存在并不意味着 Excel 可以打开它。此外,命中文件系统的 anything 应该会失败,因为正在运行的代码不是唯一的 IO 使用者。其他进程删除Dir调用和Workbooks.Open调用之间的文件是完全可行的。
  • 判断 Excel 是否无法打开文件的简单方法是在尝试打开文件后检查 wb Is Nothing

标签: excel vba error-handling


【解决方案1】:

好的,这里有几个问题。首先,关于错误处理。当您使用内联错误处理 (On Error Resume Next) 时,基本模式是关闭自动错误处理,运行您想要“捕获”错误的代码行,然后测试 @987654323 @ 为零:

On Error Resume Next
ProcedureThatCanError
If Err.Number <> 0 Then
    'handle it.
End If
On Error GoTo 0

其余问题涉及您在打开工作簿时可能遇到的对话框。其中大部分都记录在Workbook.OpenMSDN page 中,但您需要更改Application.AutomationSecurity 属性以根据需要处理宏提示。对于更新,您应该传递适当的UpdateLinks 参数。我还建议指定IgnoreReadOnlyRecommendedNotifyCorruptLoad。像这样的东西应该可以工作(未经测试),或者至少让你更接近:


Sub TestScrubberNew() 'Underscores should be avoided in method names.

    Dim directory As String, fileName As String, i As Variant, wb As Workbook
    Application.DisplayAlerts = False
    Application.ScreenUpdating = False

    Dim security As MsoAutomationSecurity
    security = Application.AutomationSecurity
    Application.AutomationSecurity = msoAutomationSecurityForceDisable

    directory = "C:\Users\bayli\Desktop\excel files\"
    fileName = Dir(directory & "*.xl??")

    i = 0
    Do While fileName <> vbNullString
        On Error Resume Next
        Set wb = Workbooks.Open(fileName:=directory & fileName, _
                                UpdateLinks:=0, _
                                IgnoreReadOnlyRecommended:=True, _
                                Notify:=False, _
                                CorruptLoad:=xlNormalLoad)
        If Err.Number = 0 And Not wb Is Nothing Then
            On Error GoTo 0
            wb.RemoveDocumentInformation xlRDIAll
            wb.Close True
            i = i + 1
            Application.StatusBar = "Files Completed:  " & i
            fileName = Dir()
        Else
            Err.Clear
            On Error GoTo 0
            'Handle (maybe log?) file that didn't open.
        End If
    Loop

    Application.AutomationSecurity = security
    Application.StatusBar = False
    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
    MsgBox "Complete"

End Sub

【讨论】:

  • 非常感谢。这很有帮助!测试您现在提供的代码,它看起来运行良好
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多