【问题标题】:Excel VBA - Skip sub or end sub IF StatementExcel VBA - 跳过子或结束子IF语句
【发布时间】:2014-11-20 16:05:17
【问题描述】:

我的代码循环遍历表格中的单元格值并查看是否存在同名文档。 如果确实存在,它将执行打开这些文件并导入数据的操作。

If bProcess Then
    FileCounter = 0
    For Each folderIDX In PrimaryMergeFiles
        'If folderIDX.Name = Worksheets("Table").Range("A1:A13") Then
        Dim vTest As Variant
        vTest = Application.WorksheetFunction.VLookup(folderIDX.Name, Worksheets("Table").Range("A1:B13"), 2, False)

        'Creating Merge File
        If Not IsError(vTest) Then
            FileCounter = FileCounter + 1

            strStatus = "Creating file " & FileCounter & " of " & PrimaryMergeFiles.Count & ": " & folderIDX.Name
            Application.StatusBar = strStatus
            CreateMergedFile wdApp, sPrimaryMergeDirectory, folderIDX.Name, sSourceFile, ClientCount, _
                sClientSubDirectory, bClearHighlightings(ClientCount), bHome
            'ElseIf IsError(vTest) Then
        Else
            End Sub
        End If  
    Next
End If

当 vTest 出错时,如何跳过文件或结束循环/子?

【问题讨论】:

    标签: excel vba loops if-statement vlookup


    【解决方案1】:

    你应该使用:

    Else
        Exit Sub '<-- Exit! :)
    End If
    

    代替:

    Else
        End Sub '<-- Instead of End :3
    End If
    

    希望这会有所帮助!

    编辑:回答您的评论

    Dim vTest As Variant
    
    On Error Resume Next '<-- Add these since you are catching the error immediately after
    vTest = Application.WorksheetFunction.VLookup(folderIDX.Name, Worksheets("Table").Range("A1:B13"), 2, False)
    On Error Goto 0      '<-- You will handle your error on the next line
    
    If Not IsError(vTest) Then '...
    
    'You may also want to use/use instead: If Err.Number <> 0 Then ...
    

    这里有更多关于 VBA 中错误处理的信息:http://www.cpearson.com/excel/errorhandling.htm

    【讨论】:

    • 不幸的是,当它到达不在 vlookup 中的文件时,我收到此错误消息:运行时错误 '1004' 应用程序定义或对象定义错误
    猜你喜欢
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 2012-04-27
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多