在单元格保持不变的情况下计算运行总计

时间:2018-07-31 21:04:12

标签: excel vba

我正在创建一个宏,该宏根据相邻列中的条件创建运行总计。我可以使用公式组合来执行此操作,但我希望能够在VBA中执行此操作。到目前为止,我的代码可以处理几行,但最多不能超过4行。

        LastColumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
        LastRow1 = .Cells(.Rows.Count, 1).End(xlUp).Row
        .Range("O1") = ""

    If LastRow1 = 1 Then
        MsgBox "No Closed-Won for " & RepName
        ElseIf LastRow1 = 2 Then
            .Cells(2, LastColumn + 1).Formula = "=F2"
        ElseIf LastRow = 3 Then
            k = 0
            For k = 3 To LastRow1
            .Cells(k, LastColumn + 2).Value = Month(Worksheets(RepName.Text).Cells(k, 8))
            Next k
            .Cells(3, LastColumn + 1).Formula = "=F3+O2"
        ElseIf LastRow1 = 4 Then
            .Cells(2, LastColumn + 1).Value = .Cells(2, 6).Value
            .Cells(3, LastColumn + 1).Formula = "=F3+O2"
            .Cells(4, LastColumn + 1).Formula = "=F4+O3"
        ElseIf LastRow1 > 4 Then
            .Cells(2, LastColumn + 1).Value = .Cells(2, 6).Value
            .Cells(3, LastColumn + 1).Formula = "=F3+O2"
            Call Q1
        Else: 'do nothing
    End If

(这是处理该特定操作的代码段)我认为必须有更好的方法来执行此操作,但是我不确定它是什么。任何想法将不胜感激。

Example of what the final product should look like

1 个答案:

答案 0 :(得分:2)

单元格C2中使用的公式为

=IF(B2=B1,C1+A2,A2)

并根据需要向下复制

创建该公式(如果需要的话)的代码是(Excel将负责更新单元格引用)

Sub Demo()

    Dim rng As Range
    Dim ws As Worksheet
    Set ws = ActiveSheet
    With ws
        Set rng = .Range(.Cells(2, 1), .Cells(.Rows.Count, 1).End(xlUp)).Offset(, 2)
        rng.Formula = "=IF(B2=B1,C1+A2,A2)"
    End With
End Sub