如何使用VBA对Excel中的行进行汇总

时间:2018-06-27 02:31:04

标签: excel vba excel-vba sum

我正在使用VBA创建我的第一个模块,但不确定如何汇总行。我想知道是否有人可以帮助我。我有交易记录,附有图片:

enter image description here

我正在尝试在日期组之间插入一个中断(空白行)(将特定日期的所有交易分组),然后在对应日期的每一列下的中断中添加总计。我的代码如下,但是由于不确定语法,因此我对如何创建总和保持了信心。这是我想出的代码:

    Sub InsertRowsBetweenDates()
'
' InsertRowsBetweenDates Macro
' Insert Rows in between two dates that are not equal
'
Dim x As Integer
Dim y As Integer
Dim row1 As Range
Dim row2 As Range
Dim t As Integer 'tracking how many cells to add together


'define x as cell row value
x = 2
'define y as cell row value
y = 3
'start tracker at 0
t = 0
'row 1 and row 2 get their values
Set row1 = Cells(x, 4)
Set row2 = Cells(y, 4)

'Do until there are no more entries in the worksheet (or really until row 1 has no value)
Do Until row1.Value = False
    x = x + 1
    y = y + 1
    Set row1 = Cells(x, 4)
    Set row2 = Cells(y, 4)
    t = t + 1

    'If row 1 and 2 don't equal each other, insert a row above row 2
    If row1 <> row2 Then
        row2.EntireRow.Insert Shift:=xlDown

        'sum up t rows for subtotal and tax [THIS IS WHAT IM STUCK ON]


        'skip the break            
        x = x + 2
        y = y + 2
        Set row1 = Cells(x, 4)
        Set row2 = Cells(y, 4)
        t = 0

    End If
Loop

End Sub

如您所见,我可以工作了,尽管它仅适用于该文件,因为行和列的位置都经过硬编码,但这只是一个开始。在这一点上,我有一个跟踪器来跟踪已计数的行数,我想我只需要插入代码即可对行进行汇总。我将如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

我认为您正在完全走错路。 除非我完全完全必须

为什么?

因为您要将数据与报表放在一起。当有人需要插入一行时会发生什么?当有人必须维护您的代码时会发生什么?

查看以下选项:  1.将源用作table并以pivot table进行总结  2.添加一列并使用SUMIF函数

通过这些方法,您可以完全避免使用VBA,但仍然可以获取所需的报告。祝你好运!

相关问题