【问题标题】:VBA in Excel 2007 won't execute nested for loopsExcel 2007 中的 VBA 不会执行嵌套的 for 循环
【发布时间】:2014-11-13 06:03:51
【问题描述】:

我编写了嵌套的 For 循环,即使满足条件,它也不会执行 For 循环的代码。我尝试注释掉最外面的 For 循环,但内部循环也不起作用。 我正在使用 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 

感谢您的帮助

【问题讨论】:

  • 您有Cells(a, i),但没有定义i。应该是Cells(a, b)

标签: excel vba for-loop nested-loops execution


【解决方案1】:

你的 For 循环应该写成:

For a = 10 To XXX

而不是:

For a = 10 To a = XXX

【讨论】:

    【解决方案2】:

    试试这个:

    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 
    

    另外,您可能会考虑在第一个 for 循环中完全限定您的范围(Worksheets("worksheetName").Range("B" &amp; Rows.Count)... 而不仅仅是 Range("B" &amp; Rows.Count)...)现在,它将使用当前活动工作表的范围。因此,除非这是您的意图,否则最好是明确的。

    【讨论】:

    • For 循环现在可以工作了,谢谢。但是,当我将 For a = 10 To Worksheets("DistanceLookupTable").(Range("B" & Rows.Count).End(xlUp).Row) 步骤 1 它以红色突出显示并说存在语法错误时跨度>
    • 范围部分不应有括号。您可能会考虑将其分配给变量,而不是直接在 for 循环中对其进行硬编码。像lastColumn = Worksheets("DistanceLookupTable").Range("B" &amp; Rows.Count)... 等。这样,您可以通过单步执行代码来检查该语句正在评估的内容。然后你的 for 循环将是 For a = 10 to lastColumn.
    猜你喜欢
    • 1970-01-01
    • 2016-11-15
    • 2012-09-09
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多