在给定路径中缺少文件时出现错误处理程序

时间:2014-07-28 05:27:16

标签: excel-vba vba excel

我写了一个vba代码来打开多个文件并复制该文件的内容并将其粘贴到主文件中。当指定位置缺少文件时,编译器抛出错误,我可以处理它并继续下一个文件。但是,如果第二次出现错误,程序就会停止。

代码

On Error GoTo ErrH:

ErrH:
MsgBox strFileName & "is missing."
Sheets(strListSheet).Select
ActiveCell.Offset(1, 0).Select

GoTo Continue

2 个答案:

答案 0 :(得分:1)

处理这样的错误有两种常见方法

  • 单独的错误处理程序
    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
  • 内联错误处理程序
    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

答案 1 :(得分:0)

或者您可以尝试此版本的内联错误处理:

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