如何使用IfError GoTo Next函数

时间:2017-04-26 11:18:09

标签: excel vba excel-vba

如果我在 sprd = Application.Find(&#34)中收到错误,请指导我如何直接恢复" s = s + 1" ;,",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

3 个答案:

答案 0 :(得分:1)

以下代码按要求回答您的问题:

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.Finderror trapping is being turned off again之后。

然而,更好的解决方案是使用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

答案 1 :(得分:1)

而不是Application.Find使用InStr(并交换参数):

sprd = InStr(xword, ",")

这不会产生错误,效率更高。

如果未找到匹配项, sprd 将为零,因此将跳过Do While循环。

答案 2 :(得分:0)

类似于this

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

希望这有帮助!