2016-11-08 67 views
0

我真的不知道爲什麼VBA編譯器嘮叨我,因爲GoTo Jump,分別Jump:Excel VBA:在for循環中跳轉:「Next without For」 - 我做錯了什麼?

counter2 = 0 
    If (counter1 > 1) Then 
     For i = 0 To (MaxLastCell - 4) 
      If (IncompleteRows(i) = 1) Then 
       If ((counter2 > 1) And (counter2 < counter1)) Then 
        x = x + ", " + CLng(i) 
        counter2 = counter2 + 1 
        GoTo Jump 
       End If 
       If ((counter2 > 1) And (counter2 = counter1)) Then 
        x = x + " and " + CLng(i) 
        GoTo Outside 
       If (counter2 = 0) Then 
        x = CLng(i) 
        counter2 = 1 
       End If 
      End If 
Jump: 
     Next i 

每當我嘗試運行我的代碼時,此代碼段似乎是一個問題。編譯器在最下方標記Next,並告訴我有一個"Next without For"

但不應該這種編碼工作?我剛看到它here。然而,一個奇怪的事情是,編譯器似乎並沒有強制B H將其跳躍點NextIteration:移動到最左邊,但允許它停留在第二個縮進級別,因此之內for -loop,as它似乎。 (難道,即使有關係嗎?)

+2

將IF結構更改爲ElseIF,如下面的答案。然後,您可以刪除goto Jump行,並用'Exit For'替換外部的goto。 –

回答

1

試試這個(修訂標記註釋):

counter2 = 0 
    If (counter1 > 1) Then 
     For i = 0 To (MaxLastCell - 4) 
      If (IncompleteRows(i) = 1) Then 
       If ((counter2 > 1) And (counter2 < counter1)) Then 
        x = x + ", " + CLng(i) 
        counter2 = counter2 + 1 
        GoTo Jump 
       End If 
       If ((counter2 > 1) And (counter2 = counter1)) Then 
        x = x + " and " + CLng(i) 
        GoTo Outside 
       ElseIf (counter2 = 0) Then '<--*** changed from simple 'If' 
        x = CLng(i) 
        counter2 = 1 
       End If 
      End If 
Jump: 
     Next i 
    End If '<--*** added 

但是你應該避免goto方法

1

你已經有了一些不錯的意大利麪條代碼那裏。 GoTo只是適當控制流程的一個糟糕的選擇。

Neal Stephenson thinks it's cute to name his labels 'dengo'

一個GoTo 「跳過下一次迭代」 是一回事。另一個到GoTo Outside(無論那是哪裏)是別的。

VBA(語言規範)不關心線標籤在哪一列開始;對於我們所知的所有鏈接的答案都是在答案框中輸入的,而不是在VBE中。當VBE(IDE /編輯器)看到一個線標籤時,它會自動將它移動到第1列,就像它自動在操作符和操作數之間插入空格一樣,就像在鍵入時自動調整關鍵字和標識符的大小。所以不,根本就沒有關係。

VBA語法要求塊被關閉:就像Sub DoSomething()過程必須一端與End SubWith必須一端與End With,一個For必須一端與Next。正確的縮進和小程序機構通常有助於獲得正確的結果。

很多其他語言(C#,Java和C++等)有什麼使一個有效的代碼塊(不匹配{}括號中使用它們AFAIK每一種語言編譯器錯誤)類似的限制,所以這不是VBA挑剔或抱怨沒有理由。

這就是說很難判斷你的代碼是否存在錯誤,以及你的代碼在哪裏存在錯誤,因爲你沒有包含整個過程範圍,所以我們不得不假設你的代碼片段中沒有其他東西 - 並且你發佈的代碼片段丟失了一個End Ifas user3598756 has noted

If (counter1 > 1) Then 
    '...code... 
End If 

那麼,如何去重組呢?

  • 假設Outside線標籤位於之前End Sub(或者是End Function?),那麼你可以將其替換爲Exit Sub(或Exit Function)和收工。
    • 如果在循環之後但在過程作用域結束之前需要運行更多的代碼,Exit For將讓您脫離循環,同時讓您保留在過程中 - 下一行將成爲第一個可執行語句緊隨Next令牌。
  • 現在採取使循環跳過迭代並相應地更改循環體的條件;使用ElseIf避免評估你並不需要的條件,並刪除所有這些外來的混亂括號:

    If IncompleteRows(i) = 1 And counter2 > 1 And counter2 < counter1 Then 
        x = x + ", " + CLng(i) 
        counter2 = counter2 + 1 
    ElseIf counter2 > 1 And counter2 = counter1 Then 
        x = x + " and " + CLng(i) 
        Exit For ' assuming... 
    ElseIf counter2 = 0 Then 
        x = CLng(i) 
        counter2 = 1 
    End If 
    

    這將是循環的整個身體。當然,它仍然可以改進; counter2 > 1重複兩次,所以有進一步重組的空間。但是,已經所有GoTo都沒有了。