请指导我如何直接恢复到" s = s 1" 如果我在 sprd = application中遇到错误",",xword(。请指导。
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
之后,错误陷阱再次关闭。
然而,更好的解决方案是这样使用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
希望这会有所帮助!