vba 文件在给定路径中丢失时的错误处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24988882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error Handler while the file is missing in the given path
提问by user3883092
I wrote a vba code to open multiple files and copy the content of that files and paste it in the master file. when a file is missing in the specified location compiler is throwing error and I can able to handle that and continue with the next file. However, if the error occurs for the second time program is getting stopped.
我编写了一个 vba 代码来打开多个文件并复制这些文件的内容并将其粘贴到主文件中。当指定位置中缺少文件时,编译器会抛出错误,我可以处理该问题并继续处理下一个文件。但是,如果第二次发生错误,程序就会停止。
Code
代码
On Error GoTo ErrH:
ErrH:
MsgBox strFileName & "is missing."
Sheets(strListSheet).Select
ActiveCell.Offset(1, 0).Select
GoTo Continue
回答by chris neilsen
There are two common ways on handling errors like this
处理这样的错误有两种常见的方法
- Seperate Error handler
- 单独的错误处理程序
Dim wb As Workbook
On Error GoTo ErrH
For ' loop your File Names
Set wb = Nothing
Set wb = Workbooks.Open(strFileName)
If Not wb Is Nothing Then
' Do your stuff
End If
Next 'strFileName
Exit Sub
ErrH:
If Err.Number = 1004 Then
' File not found error
Resume Next
Else
' Handle other Errors
MsgBox Err.Description
End If
End Sub
- Inline error handler
- 内联错误处理程序
Dim wb As Workbook
On Error GoTo ErrH
For ' loop your File Names
Set wb = Nothing
On Error Resume Next
Set wb = Workbooks.Open(strFileName)
On Error GoTo ErrH
' if wb is nothing then strFileName wasn't found
If Not wb Is Nothing Then
' Do your stuff
End If
Next 'strFileName
Exit Sub
ErrH:
' Handle other Errors
MsgBox Err.Description
End Sub
回答by L42
Or you can try this version of inline error handling:
或者你可以尝试这个版本的内联错误处理:
For Each strfilename In strfilenames '~~> just for example
On Error Resume Next
Set wb = Workbooks.Open(strFileName)
On Error Goto 0 '~~> required to capture any other error which might occur.
If Not wb Is Nothing Then
'~~> Do something
End If
wb.Close False '~~> close file without saving
Set wb = Nothing '~~> set wb variable to nothing
Next