擅长错误转到多个

我试图得到多个错误语句工作,不能弄明白。

如果在本地可以findpdf然后打开,如果没有,则打开networking位置。 如果没有PDF,则返回msgbox。

Sub Cutsheets() Application.ScreenUpdating = False Dim finalrow As Integer finalrow = Cells(Rows.Count, 1).End(xlUp).Row On Error GoTo net1 If Not Application.Intersect(ActiveCell, Range("A9:A" & finalrow)) Is Nothing Then 'Local Location ActiveWorkbook.FollowHyperlink "C:\Local" & ActiveCell & ".pdf" Application.SendKeys "{ENTER}", True End If Exit Sub net1: If Not Application.Intersect(ActiveCell, Range("A9:A" & finalrow)) Is Nothing Then 'Network Location On Error GoTo whoa ActiveWorkbook.FollowHyperlink "P:\Network" & ActiveCell & ".pdf" Application.SendKeys "{ENTER}", True End If Exit Sub whoa: MsgBox ("No cutsheet can be found for this item.") Application.ScreenUpdating = True End Sub 

另外我不记得为什么我会把sendkeys放在那里,但是如果没有它的话,它是不行的。

使用多个On Error Goto XYZ处理程序来控制stream程会使一些简单的validation检查过于复杂,然后仅仅使用error handling来处理实际的错误。

正如@Rory在评论中指出的,你可以使用Dir函数。 你可以结合使用DirIf...ElseIf...Else...End If结构来控制你的代码:

 Option Explicit Sub Cutsheets() On Error GoTo ErrHandler Dim strLocalCheck As String Dim strNetworkCheck As String 'check for files - Dir will return "" if file not found strLocalCheck = Dir("C:\Local" & ActiveCell.Value & ".pdf") strNetworkCheck = Dir("P:\Network" & ActiveCell.Value & ".pdf") 'control flow If strLocalCheck <> "" Then ActiveWorkbook.FollowHyperlink strLocalCheck Application.SendKeys "{ENTER}", True ElseIf strNetworkCheck <> "" Then ActiveWorkbook.FollowHyperlink strNetworkCheck Application.SendKeys "{ENTER}", True Else MsgBox "No cutsheet can be found for this item." End If Exit Sub ErrHandler: Debug.Print "A real error occurred: " & Err.Description End Sub 

我想获得多个错误语句工作

别。

想象一下你是VBA运行时。 你正在执行一个名为Cutsheets的过程,并且你遇到了这个指令:

 On Error GoTo net1 

从那时起,在用户的脸上炸开之前,如果遇到运行时错误,您将跳转到net1标签。 所以你继续运行指示。 最后你运行这一行:

 ActiveWorkbook.FollowHyperlink "C:\Local" & ActiveCell & ".pdf" 

FollowHyperlink方法以“uh nope,不能这样做”来响应并引发运行时错误时,执行上下文会改变。

您处于“error handling”模式。

所以你跳转到net1标签。 您处于“error handling”模式 。 在“正常执行模式”下你可以做某些事情,在“error handling模式”中不能(或不应该 )这样做。 提高和处理更多的错误是这些事情之一。

 On Error GoTo whoa 

已经在处理一个运行时错误了:当你在一个error handling子程序中遇到这个语句时你应该怎么做? 马上跳到whoa

当VBA运行时处于“error handling模式”时,作为程序员的工作就是处理运行时错误 ,并尽可能快地返回到“正常执行模式” – 这通常是通过一个Resume指令完成的,或者离开当前的范围。

从“正常执行path”复制一段代码并试图在“error handling模式”下运行(稍微改变)不会处理错误并尽快回到正常执行模式

error handling与否, 复制粘贴代码块反正写得不好。

取而代之的是一个过程:

 Private Sub OpenPortableDocumentFile(ByVal path As String) On Error GoTo ErrHandler ActiveWorkbook.FollowHyperlink path Application.SendKeys "{ENTER}", True Exit Sub ErrHandler: MsgBox "Could not open file '" & path & "'." End Sub 

现在这样做了,通过在OpenPortableDocumentFile过程传递无效path之前validation文件是否存在,清理控制stream。

最好的error handling策略是避免首先增加运行时错误。