如何使用IfError GoTo Next函数
如果我在sprd = Application.Find(“,”,xword)中出现错误,请指导我如何直接恢复到“s = s + 1” 。 请指导。
For xx = 2 To 15494 xword = Cells(s, m) If xword <> "" Then le = Len(xword) sprd = Application.Find(",", xword)'' If I am getting Error old_sprd = sprd 's = 1 Star = 1 Do While sprd <> 0 word = Mid(xword, Star, sprd - 1) xword = Mid(xword, sprd + 1, le) s = s + 1 Rows(s).Insert Cells(s, m) = word sprd = Application.Find(",", xword) If IsError(sprd) Then sprd = 0 If sprd = 0 Then s = s + 1 Rows(s).Insert Cells(s, m) = xword End If le = Len(xword) Loop End If s = s + 1 '' My Code supposed to directing divert in This line. Next
而不是Application.Find
使用InStr
(并交换参数):
sprd = InStr(xword, ",")
这不会产生错误,而且效率更高。
如果找不到匹配,则sprd将为零,因此您的Do While
循环将被跳过。
以下代码按照问题回答您的问题:
For xx = 2 To 15494 xword = Cells(s, m) If xword <> "" Then le = Len(xword) On Error GoTo NextLine sprd = Application.Find(",", xword) '' If I am getting Error On Error GoTo 0 old_sprd = sprd 's = 1 Star = 1 Do While sprd <> 0 word = Mid(xword, Star, sprd - 1) xword = Mid(xword, sprd + 1, le) s = s + 1 Rows(s).Insert Cells(s, m) = word sprd = Application.Find(",", xword) If IsError(sprd) Then sprd = 0 If sprd = 0 Then s = s + 1 Rows(s).Insert Cells(s, m) = xword End If le = Len(xword) Loop End If NextLine: s = s + 1 '' My Code supposed to directing divert in This line. Next
基本上,有三个变化:(1)在发出Application.Find
命令之前,有一行告诉VBA在发生错误时应该怎么做-->
它应该转到NextLine
。 NewLine
就像一个书签,可以是任何你想要的名字。 你只需要告诉VBA这个书签在哪里。 这是你的代码中的第二个改变:(2)在s = s + 1
之前添加一行,告诉VBA这是称为NewLine
的“书签”。 第三个变化是告诉VBA只有在Application.Find
行发生错误时才使用这个“书签”。 在所有其他情况下,VBA应该只是将错误传回给您(用户)。 所以,(3)直接在Application.Find
行之后。 找出错误陷阱再次被closures 。
然而,更好的解决scheme是像这样使用InStr()
:
For xx = 2 To 15494 xword = Cells(s, m) If xword <> "" Then le = Len(xword) If InStr(1, xword, ",", vbTextCompare) Then sprd = Application.Find(",", xword) old_sprd = sprd Star = 1 Do While sprd <> 0 word = Mid(xword, Star, sprd - 1) xword = Mid(xword, sprd + 1, le) s = s + 1 Rows(s).Insert Cells(s, m) = word sprd = Application.Find(",", xword) If IsError(sprd) Then sprd = 0 If sprd = 0 Then s = s + 1 Rows(s).Insert Cells(s, m) = xword End If le = Len(xword) Loop End If End If s = s + 1 '' My Code supposed to directing divert in This line. Next xx
像这样的东西?
On Error Goto JumpHere: i = 1 / 0 'throws error i = 2 'this line is never executed JumpHere: i = 1 'code resumes here after error in line 2
希望这可以帮助!