Expand Start Date to End Date with Series of EOMONTHs

前端 未结 2 1260
梦如初夏
梦如初夏 2020-12-19 17:59

I have a data table containing ids with a start date and end date associated with both.

RowNo   AcNo     StartDate     EndDate
  1     R125     01/10/2017            


        
2条回答
  •  隐瞒了意图╮
    2020-12-19 18:39

    Try it as a nested For ... Next loop using DateDiff to determine the number of months. Collecting the progressive values in an array will speed up execution before dumping them back to the worksheet.

    Option Explicit
    
    Sub eoms()
        Dim a As Long, m As Long, ms As Long, vals As Variant
        With Worksheets("Sheet2")
            .Range("F1:G1") = Array("AcNo", "EOMONTHs")
            For a = 2 To .Cells(.Rows.Count, "B").End(xlUp).Row
                ms = DateDiff("m", .Cells(a, "C").Value2, .Cells(a, "D").Value2)
                ReDim vals(1 To ms + 1, 1 To 2)
                For m = 1 To ms + 1
                    vals(m, 1) = .Cells(a, "B").Value2
                    vals(m, 2) = DateSerial(Year(.Cells(a, "C").Value2), _
                                            Month(.Cells(a, "C").Value2) + m, _
                                            0)
                Next m
                .Cells(.Rows.Count, "F").End(xlUp).Offset(1, 0).Resize(UBound(vals, 1), UBound(vals, 2)) = vals
            Next a
            .Range(.Cells(2, "G"), .Cells(.Rows.Count, "G").End(xlUp)).NumberFormat = "mmm yy"
        End With
    End Sub
    

    VBA's DateSerial can be used as a EOMONTH generator by setting the day to zero of the following month.

    Note in the following image that the generated months are the EOMONTH of each month in the series with mmm yy cell number formatting.

提交回复
热议问题