2017-04-26 51 views
1

請指引我,我怎麼能直接恢復到「S = S + 1」如果我在SPRD = Application.Find收到錯誤(「」,xword)。請指導。如何使用IFERROR轉到下一頁功能

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 
+0

您通過xx循環,但是在代碼中沒有使用xx? – Luuklag

+1

爲什麼不使用'Instr'而不是'Application.Find'?如果找不到搜索字符串,它將返回0,而不是錯誤值。 – Rory

回答

1

代替Application.Find使用InStr(和交換參數):

sprd = InStr(xword, ",") 

不產生錯誤,並且更高效。

如果找不到匹配,sprd將爲零,因此您的Do While循環將被跳過。

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 

希望這會有所幫助!

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如何在發生錯誤的情況下,之前做-->它應該去NextLineNewLine就像書籤,可以是任何你想要的名字。你只需要告訴VBA這個書籤在哪裏。這是您的代碼中的第二次更改:(2)在s = s + 1之前添加一行,告訴VBA這是「書籤」NewLine。第三個變化是告訴VBA只有在行Application.Find上發生錯誤時才使用這個「書籤」。在所有其他情況下,VBA應該只是將錯誤傳回給您(用戶)。所以,(3)直接在Application.Find之後error 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