2015-10-16 160 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