简体   繁体   English

Excel 2007中的VBA不会执行嵌套循环

[英]VBA in Excel 2007 won't execute nested for loops

I've written nested For loops and even though the conditions are met it is not executing the code of the For loops. 我已经编写了嵌套的For循环,即使满足条件,它也不执行For循环的代码。 I tried commenting out the outermost For loop but the inner loop doesn't work either. 我尝试注释掉最外面的For循环,但内部循环也不起作用。 I'm working in Excel 2007 我在Excel 2007中工作

Sub CalcAll()

Dim a As Integer
a = 10
Dim b As Integer
b = 10

For a = 10 To a = (Range("B" & Rows.Count).End(xlUp).Row) Step 1

    For b = 10 To b = (Worksheets("DistanceLookupTable").Cells(2, Sheet1.Columns.Count).End(xlToLeft).Column) Step 1

        If IsEmpty(Cells(a, i).Value) Then
            Exit Sub
        Else
            'Lots of code reading values from the worksheet and printing
            'calculated values to the worksheet 
        End If
    Next b 
Next a 
End Sub 

Thanks for your help 谢谢你的帮助

Your For loops should be written as: 您的For循环应写为:

For a = 10 To XXX

Rather than: 而不是:

For a = 10 To a = XXX

Try this: 尝试这个:

Dim a As Integer
'a = 10 'Unnecessary to assign value here, as you assign the starting value in the For loop
Dim b As Integer
'b = 10 'Again, this line not necessary

For a = 10 To Range("B" & Rows.Count).End(xlUp).Row Step 1

   For b = 10 To Worksheets("DistanceLookupTable").Cells(2, Sheet1.Columns.Count).End(xlToLeft).Column Step 1

      If IsEmpty(Cells(a, i).Value) Then '<- do you mean 'b' instead of 'i'? I don't see 'i' assigned anywhere...
         Exit Sub
      Else
        'Lots of code reading values from the worksheet and printing
        'calculated values to the worksheet 
      End If
   Next b 
Next a 

And on an unrelated note, you might consider fully qualifying your range in the first for loop ( Worksheets("worksheetName").Range("B" & Rows.Count)... instead of just Range("B" & Rows.Count)... ) As it is now, it will use the range of the currently active sheet. 另外,您可以考虑在第一个for循环( Worksheets("worksheetName").Range("B" & Rows.Count)...而不是Range("B" & Rows.Count)... Worksheets("worksheetName").Range("B" & Rows.Count)...完全限定范围Range("B" & Rows.Count)... )现在,它将使用当前活动工作表的范围。 So unless that is your intention, it's better to be explicit. 因此,除非您有此意图,否则最好将其明确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM