VBA无限嵌套循环

时间:2020-04-19 02:00:56

标签: excel vba

我正在尝试编写嵌套的for循环以遍历一列中的行以进行一些计算,然后转到下一个列以再次执行。逻辑对我来说很有意义,但是工作表的输出在正确答案之间来回闪烁,并覆盖具有相同数字的所有内容,并且它会一直这样做。请让我知道是否需要澄清任何事情。


Sub findAvg2()
Dim maxVal As Double
Dim preHr As Double
Dim nextHr As Double
Dim cVal As Double
Dim pVal As Double
Dim nVal As Double
Dim avg As Double
Dim maxAvg As Double
Dim i As Integer 'row
Dim j As Integer 'col
Dim lRow As Integer
Dim lCol As Integer

lRow = Cells(Rows.count, 1).End(xlUp).row                    'Find the number of rows in column A(1)
lCol = Cells(1, Columns.count).End(xlToLeft).Column

For i = 19 To lRow
    For j = 2 To lCol
        maxVal = Cells(2, j).Value
        preHr = Cells(8, j).Value
        nextHr = Cells(9, j).Value
        avg = (maxVal + preHr + nextHr) / 3
        If Cells(i, j).Value > 0 Then
            pVal = Cells(i - 1, j).Value
            cVal = Cells(i, j).Value
            nVal = Cells(i + 1, j).Value
            maxAvg = (pVal + cVal + nVal) / 3
            If avg > maxAvg Then
                maxAvg = avg
            End If
        End If
        Cells(12, j).Value = maxAvg
        'Debug.Print maxAvg
    Next j
Next i

End Sub

1 个答案:

答案 0 :(得分:1)

我检查了您的代码,发现没有问题。我所做的修改对我来说似乎是装饰性的。这是结果。

Sub findAvg2()
    ' 005
    Dim maxVal As Double
    Dim preHr As Double
    Dim nextHr As Double
    Dim cVal As Double
    Dim pVal As Double
    Dim nVal As Double
    Dim Avg As Double
    Dim maxAvg As Double
    Dim Cl As Long                              ' last used column
    Dim Rl As Long                              ' last used row
    Dim C As Long                               ' column
    Dim R As Long                               ' row

    ' Find the number of used columns and roaws in the sheet
    Cl = Cells(1, Columns.Count).End(xlToLeft).Column
    Rl = Cells(Rows.Count, 1).End(xlUp).Row

    For R = 19 To Rl
        For C = 2 To Cl
            maxVal = Cells(2, C).Value
            preHr = Cells(8, C).Value
            nextHr = Cells(9, C).Value
            maxAvg = (maxVal + preHr + nextHr) / 3

            cVal = Cells(R, C).Value
            If cVal > 0 Then
                pVal = Cells(R - 1, C).Value
                nVal = Cells(R + 1, C).Value
                Avg = (pVal + cVal + nVal) / 3
                If Avg > maxAvg Then maxAvg = Avg
            End If
            Cells(12, C).Value = maxAvg
            'Debug.Print maxAvg
        Next C
    Next R
End Sub

这行代码可能存在缺陷。 For R = 19 To Rl。由于要在平均值计算中包括上一行,因此第18行必须包含数据。如果不是这样,并且您不能从评估中排除第一个数据行,则必须对初始maxAvg的计算进行特殊规定。

所有操作都在ActiveSheet上进行。我本能地不喜欢这种安排。除非您是从该工作表上的按钮调用子程序的,否则即使在这种情况下,如果一个智能alec想要使用F5代替,我也会在代码中命名该工作表。使用CodeName既可以提高安全性,又可以让用户自由地重命名工作表。该代码将在碰巧处于活动状态的任何工作表上运行。它甚至不必位于同一工作簿中。