2015-10-16 84 views
0

我在編碼時遇到了Next Without For編譯錯誤,因爲我有一個額外的Next語句。如果行1中的值不是1,23,我希望宏移動到下一列。下面是我的代碼的簡化版本:'Next Without'因爲額外'Next'

For i = 1 To lastcol 
    Select Case Sheets("Daily Report").Cells(1, i).Value 
     Case 1 
      sPriority = "High" 
     Case 2 
      sPriority = "Med" 
     Case 3 
      sPriority = "Low" 
     Case Else 
      Next i 
    End Select 
    Set wsTracker = Sheets(sPriority) 
    'Omitted code to update data on Priority worksheet with data from Daily Report sheet. 
Next i 

回答

1

我能有額外的IF-THEN語句,以獲得相同的結果:

For i = 1 To lastcol 
    Select Case Sheets("Daily Report").Cells(1, i).Value 
     Case 1 
      sPriority = "High" 
     Case 2 
      sPriority = "Med" 
     Case 3 
      sPriority = "Low" 
    End Select 
    If sPriority <> "" Then 
     Set wsTracker = Sheets(sPriority) 
     'Omitted code to update data on Priority worksheet with data from Daily Report sheet. 
    End If 
    sPriority = "" 
Next i 
+3

這種方式可以工作,但您需要在每個循環的開始處爲sPriority分配一個零長度的字符串(「」或vbNullString)。或者包括一個這樣做的案例。 –

+0

這可能是最清晰的方法 - 您可以通過簡單地說「退出」退出循環,但據我所知,沒有任何單一命令可以過早地繼續循環到頂部,而無需人工干預。 –

+0

讓我希望有一個像VB.NET一樣的「繼續」。 – Kyle

1

這應該是快一點:

v = Array("High", "Med", "Low") 
On Error Resume Next 
For i = 1 To lastcol 
    Err.Clear: sPriority = v(Sheets("Daily Report").Cells(1, i) - 1) 
    If Err = 0 Then 
     Set wsTracker = Sheets(sPriority) 
     'Omitted code to update data on Priority worksheet with data from Daily Report sheet. 
    End If 
Next 
+0

我不明白這段代碼是如何規定1 =高等的。 –

+0

你試過了嗎? –

+0

我不問*如果它工作。我在問*爲什麼*。 –

0

雖然有人討厭使用GoTo,但我認爲在這種情況下效果會很好:

For i = 1 To lastcol 
    Select Case Sheets("Daily Report").Cells(1, i).Value 
     Case 1 
      sPriority = "High" 
     Case 2 
      sPriority = "Med" 
     Case 3 
      sPriority = "Low" 
     Case Else 
      GoTo NextLoop 
    End Select 
    Set wsTracker = Sheets(sPriority) 
    'Omitted code to update data on Priority worksheet with data from Daily Report sheet. 
NextLoop: 
Next i