首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >根据日期汇总每行数据

根据日期汇总每行数据
EN

Stack Overflow用户
提问于 2015-08-10 18:17:53
回答 1查看 60关注 0票数 0

我有一些数据,如下所示,从第2-7行。

我想把前几个月的所有数据合并成一行,所以从下面的图片中,我想将05/05/2014-07/09/2014的数据合并起来,但保留最近一个月最的数据--的数据--而不是加在一起。因此,我需要将G列和H列中的数据进行汇总,对于第2-4行,其他列都不重要。

第11-14行是我想要达到的目标。我将如何做到这一点(宏或其他)?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-10 20:56:49

看看这是否能让你开始:

代码语言:javascript
运行
复制
Sub Summary()
    Dim FirstDataRow As Long
    Dim LastDataRow As Long
    Dim DataRow As Long
    Dim cDates As Long
    Dim cAmounts As Long
    Dim CutoffDate As Date
    Dim EarliestOldDate As Date
    Dim LatestOldDate As Date
    Dim SumOfOld As Long
    Dim OldMonthsRow As Long
    Dim OffSetToSummaryTable As Long
    Dim InputRow As Long
    Dim OutputRow As Long
    Dim TheDate As Date
    Dim TheAmount As Long
    Dim ws As Worksheet

    ' INITIALIZE
    ' Assume we're operating on the activesheet
    Set ws = ActiveSheet

    ' Assume data starts in Row 2
    FirstDataRow = 2

    ' Assume data is a contiguous block
    LastDataRow = ws.Range("F" & CStr(FirstDataRow)).End(xlDown).Row

    ' Assume 3 empty rows between input and summary table
    OffSetToSummaryTable = 3

    ' Calculate row where sum of old months goes
    OldMonthsRow = LastDataRow + OffSetToSummaryTable + 1

    ' Calculate the cutoff date = first date of current month
    CutoffDate = DateSerial(2015, 1, 1)
    ' CutoffDate = DateSerial(Year(Date), Month(Date), 1)

    ' Column where dates are
    cDates = 6

    ' Column where amounts are
    cAmounts = 7

    ' Initialize earliest and latest old dates, and sum of old
    EarliestOldDate = DateSerial(3000, 12, 31)  ' Way out in the future
    LatestOldDate = DateSerial(1904, 1, 1)      ' Way back in the past
    SumOfOld = 0


    ' PROCESS THE DATA
    OutputRow = OldMonthsRow
    For InputRow = FirstDataRow To LastDataRow
        TheDate = ws.Cells(InputRow, cDates)
        TheAmount = ws.Cells(InputRow, cAmounts)

        If TheDate >= CutoffDate Then
            ' Add at the bottom of the summary table
            OutputRow = OutputRow + 1
            ws.Cells(OutputRow, cDates).Formula = TheDate
            ws.Cells(OutputRow, cAmounts).Formula = TheAmount
        Else
            ' Update results for previous months
            EarliestOldDate = IIf(TheDate < EarliestOldDate, TheDate, EarliestOldDate)
            LatestOldDate = IIf(TheDate > LatestOldDate, TheDate, LatestOldDate)
            SumOfOld = SumOfOld + TheAmount
        End If

    Next InputRow

    ' WRITE RESULTS TO SUMMARY ROW
    ws.Cells(OldMonthsRow, cDates).Formula = Format(EarliestOldDate, "dd/mm/yyyy") & " - " & Format(LatestOldDate, "dd/mm/yyyy")
    ws.Cells(OldMonthsRow, cAmounts).Formula = SumOfOld

    Set ws = Nothing
End Sub
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31926430

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档