打开excel文件时出现运行时错误

dan*_*lle 1 excel vba excel-vba

我正在尝试在button_click事件中打开excel文件.我打开的前四个excel文件没有遇到任何错误,但是当我的宏打开第五个时,它会停止并显示此运行时错误:

Run-time error '-2147021892 (80070bbc)':

office has detected a problem with this file. 
To help protect your computer this file cannot be opened.
Run Code Online (Sandbox Code Playgroud)

这是我打开excel文件的代码:

    Set wb = Workbooks.Open(fileName:=fileName, UpdateLinks:=True)
Run Code Online (Sandbox Code Playgroud)

bla*_*bbb 5

我有同样的问题.文件已损坏,VBA打开时抛出该错误.作为一种可能的解决方案,我发现了这个(faname是一个带路径的字符串):

Workbooks.Open FileName:= fname, UpdateLinks:=False, ReadOnly:=True, _
   IgnoreReadOnlyRecommended:=True, Password:="", Editable:=FALSE, _
   CorruptLoad:= xlExtractData
Run Code Online (Sandbox Code Playgroud)

重要的部分是"CorruptLoad:= xlExtractData",这使得可以从损坏的文件加载数据而不会抛出此错误.其他的东西只是为了防止文件做某事......与...一起

Application.DisplayAlerts = False
Application.AskToUpdateLinks = False
Application.EnableEvents = False
Application.AutomationSecurity = msoAutomationSecurityForceDisable
Application.Calculation = xlCalculationManual
Run Code Online (Sandbox Code Playgroud)

正如打开文件之前的预防措施...如果你这样做,不要忘记在宏完成之前撤消它(这些是我的标准设置,使用你自己的!你可以在立即窗口中使用Debug.Print找到它们):

Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
Application.EnableEvents = True
Application.Calculation = xlNormal
Application.AutomationSecurity = msoAutomationSecurityLow
Run Code Online (Sandbox Code Playgroud)

请注意您的安全设置实际上是什么,不要盲目复制这些设置更改...最好还是捕获错误("On Error ...")并最终重置以前的设置.