Excel VBA - 跳过子或结束子 IF 语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27044105/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:09:35  来源:igfitidea点击:

Excel VBA - Skip sub or end sub IF Statement

excelvbaloopsif-statementvlookup

提问by Hymanson5

My code loops through cell values in a table and sees if document with same name exists. If it does exist, it will perform an action to open those files and import data.

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

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

How can I skip the files or end the loop/sub when vTest is Error?

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

回答by user1274820

You should use:

你应该使用:

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

Instead of:

代替:

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

Hope this helps!

希望这可以帮助!

Edit: To answer your comment

编辑:回答你的评论

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 ...

Here is some more information on error handling in VBA: http://www.cpearson.com/excel/errorhandling.htm

以下是有关 VBA 中错误处理的更多信息:http: //www.cpearson.com/excel/errorhandling.htm