嵌套的For / Do While /虽然无法到达VBA / Macro中的外部循环

时间:2018-10-29 19:58:49

标签: excel vba excel-vba for-loop

我试图通过对一列值中的值求平均值来将#N/A填充到值表中。逻辑是从#N/A的位置开始,使用两个指针在特定值的上方和下方查找接下来的两个非#N/A值,然后对它们进行平均以填充#N/A。这是代码:-

Sub generate_NA_cutoffs()

Worksheets("Final cutoffs2").Activate

Dim i As Integer, j As Integer
Dim fwd As Integer, rev As Integer
Dim o As Integer

o = 15

For j = 3 To j = 6 'Go column-wise
    For i = 7 To i = 12 ' Go row-wise
        If i = 7 And Application.WorksheetFunction.IsNA(Cells(i, j).Value) = True Then
            Cells(i, j + o).Value = 0
        ElseIf i = 12 And Application.WorksheetFunction.IsNA(Cells(i, j).Value) = True Then
            Cells(i, j + o).Value = 1
        ElseIf Application.WorksheetFunction.IsNA(Cells(i, j).Value) = True Then
            fwd = i + 1
            rev = i - 1
            Do While Application.WorksheetFunction.IsNA(Cells(fwd, j).Value) = True
                fwd = fwd + 1
            Loop
            Do While Application.WorksheetFunction.IsNA(Cells(rev, j + o).Value) = True
                rev = rev - 1
            Loop
            'take the avg of 2 non NA values
            Cells(i, j + o).Value = (Cells(fwd, j).Value + Cells(rev, j + o).Value) * 0.5
        Else
            Cells(i, j + o).Value = Cells(i, j).Value
        End If

        'i = i + 1
    Next i

    'j = j + 1
Next j

End Sub

数据如下:- Tables view

O是图像第三张表中左起的第三列和第三列之间的偏移量。这两个循环应该使用表1中的值来填充表3。我尝试了Do While和While的变体,但这也带来了相同的问题。一旦运行,就没有报告的错误,只有第一列没有输出。 有人可以帮助我了解这里发生了什么或我在这里想念的是什么。 如果需要为此问题添加更多说明,请告诉我。

感谢一堆!

1 个答案:

答案 0 :(得分:1)

由于您需要使用开始和结束值来定义For loop

For counter = start To end [Step increment]
   {...statements...}
Next [counter]

更改此设置将解决您的问题:

For j = 3 To j = 6-> For j = 3 To 6

For i = 7 To i = 12-> For i = 7 To 12