如何使用IfError goto下一个功能



请指导我如何直接恢复到" 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在发生错误-->时该怎么办,应该转到NextLineNewLine就像书签一样,可以是您想要的任何名称。您只需要告诉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

希望这会有所帮助!

最新更新