Excel 2010按日期汇总

时间:2016-11-02 17:47:48

标签: excel-vba excel-2010 vba excel

我有这个宏用于按日期汇总总条目。宏可以每天运行两次或三次,这会导致问题,因为它想要按日期求和。当我运行它并将总数放在E列的最后一个单元格中时,我希望下次运行宏时保留该总数,但是现在它将删除最后一个条目并将新总数加上前一个总数。怎么能改变?我希望这是我解释它的方式。

Sub Sum_TodaysDate()

Dim sh As Worksheet
Set sh = ActiveSheet

Dim LastRow As Long, iCount As Long
Dim icell As Range
Dim dSplit As Variant
Dim dIndex As Date


LastRow = sh.Range("D" & Rows.Count).End(xlUp).Row
iCount = 0

For Each icell In sh.Range("D2:D" & LastRow)
    dSplit = Split(icell.Value, " ")
    dIndex = Format(dSplit(0), "mm/dd/yyyy")
    If dIndex = Date Then
        iCount = iCount + 1
        icell.Offset(0, 1).Value = "|"
    End If
Next icell


sh.Range("E" & LastRow).Value = iCount
sh.Range("E" & LastRow).Font.Color = vbRed


Application.ScreenUpdating = True
ThisWorkbook.Save

End Sub

1 个答案:

答案 0 :(得分:0)

如果您希望宏中不包含当前在E列中的任何内容,以便之前的计数保持不变,请更改以下行:

icell.Offset(0, 1).Value = "|"

If IsEmpty(icell.Offset(0, 1)) Then
    icell.Offset(0, 1).Value = "|"
Endif

如果您希望新计数仅为自上次运行宏以来添加的记录数(并且数据按日期顺序排列),则可以将其修改为:

If IsEmpty(icell.Offset(0, 1)) Then
    icell.Offset(0, 1).Value = "|"
Else
    iCount = 0
Endif