VBA 错误处理 GoTo Next Loop 而不是恢复

Jul*_*i44 3 error-handling excel vba

当导入选项卡中没有文件路径时,此代码会产生错误。因此,我包含On Error Resume Next为了运行下一个循环。但是,在On Error Resume Next代码继续运行复制操作之后,这弄乱了我要复制到的选项卡。

我发现解决方案是 On Error 代码应该进入下一个循环而不是继续操作。有没有人对如何更改错误处理有任何意见?

Sub ImportBS()

Dim filePath As String
Dim SourceWb As Workbook
Dim TargetWb As Workbook
Dim Cell As Range
Dim i As Integer
Dim k As Integer
Dim Lastrow As Long


'SourceWb - Workbook were data is copied from
'TargetWb - Workbook were data is copied to and links are stored

Application.ScreenUpdating = False

Set TargetWb = Application.Workbooks("APC Refi Tracker.xlsb")
Lastrow = TargetWb.Sheets("Import").Range("F100").End(xlUp).Row - 6


    For k = 1 To Lastrow
    

        filePath = TargetWb.Sheets("Import").Range("F" & 6 + k).Value
        Set SourceWb = Workbooks.Open(filePath)
    
    On Error Resume Next
        Range("A1").CurrentRegion.Copy
        TargetWb.Sheets("Balance Sheet Drop").Range("D" & 2 + (k - 1) * 149).PasteSpecial Paste:=xlPasteValues
        Range("A1").Copy
        Application.CutCopyMode = False
        SourceWb.Close

    Next

Application.ScreenUpdating = True

Worksheets("Import").Activate

    MsgBox "All done!"

End Sub
Run Code Online (Sandbox Code Playgroud)

Sid*_*out 5

我会以不同的方式做这件事。我会使用Dir 函数检查路径,然后决定要做什么。这是一个例子

For k = 1 To Lastrow
    filePath = TargetWb.Sheets("Import").Range("F" & 6 + k).Value
    
    '~~> Check if the path is valid
    If Not Dir(filePath, vbNormal) = vbNullString Then
        Set SourceWb = Workbooks.Open(filePath)
        
        '
        '~~> Rest of your code
        '
    End If
Next
Run Code Online (Sandbox Code Playgroud)