嵌套循环时执行

时间:2019-07-29 14:52:18

标签: excel vba

具有四列的简单表,其中包含数据的column 1被称为_Log Hour,具有数据的column 2被称为Calls。每小时Columns 34 _Hour logged_Sum Calls当前为空,等待填充。

_Log Hour   Calls   _HourLogged _Sum Calls per Hour
8             3     
9             2     
9             4     
9             7     
9             2     
10            2     
10            2     
10            4     

我已经尝试了Do while的基础

Sub automate()
    r = 2
    Do While Cells(r, 1) <> ""
    Cells(r, 3) = Cells(r, 1) * Cells(r, 2)
    r = r + 1
    Loop

End Sub

只是尝试看看它是如何工作的,那是成功的,但是第一个_LogHour应该用什么,在_Hourlogged中输入,然后_LogHour不变想要总和通话。

例如,一个更新的表看起来像这样

_Log Hour   Calls   _HourLogged _Sum Calls per Hour
8             3         8                 3
9             2         9                15
9             4     
9             7     
9             2     
10            2         10                8
10            2     
10            4

1 个答案:

答案 0 :(得分:1)

这是一种可用于此类摘要的模式:

Sub automate()

    Const ROW_START As Long = 2
    Const COL_HR As Long = 1
    Const COL_CALLS As Long = 2
    Const COL_HR_SUMM As Long = 3
    Const COL_CALLS_SUMM As Long = 4

    Dim r As Long, rw As Range, currentHr, hr, rwHr As Long, sht As Worksheet

    Set sht = ActiveSheet
    r = ROW_START

    Do While sht.Cells(r, COL_HR).Value <> ""
        hr = sht.Cells(r, COL_HR).Value
        If r = ROW_START Or hr <> currentHr Then '<< at start, or a new hour value?
            rwHr = r                             '<< store the row we first saw this hour
            currentHr = hr                       '<< store the hour
            sht.Cells(rwHr, COL_HR_SUMM).Value = currentHr
            sht.Cells(rwHr, COL_CALLS_SUMM).Value = Cells(r, COL_CALLS).Value
        Else
            'not a new hour, so update the previously-saved row
            With sht.Cells(rwHr, COL_CALLS_SUMM)
                .Value = .Value + sht.Cells(r, COL_CALLS).Value
            End With
        End If

        r = r + 1

    Loop

End Sub