inspiration

아래와 같이 조건이 있다고 하자.

  • 오늘 날짜 또는 특정 기준일이 있다
  • 여러날짜들 중 특정 기준일의 월과 매칭하여, 이에 맞는 값을 합산한다

함수로 하면 별거 아닐 수 있겠지만, VBA로는 어떨까,

myimg



Sub MonthlySum_BySelection()

    Dim baseDateCell As Range
    Dim dateRange As Range
    Dim sumRange As Range
    Dim resultCell As Range

    Dim i As Long
    Dim resultSum As Double

    ' Store active cell at execution time
    Set resultCell = ActiveCell

    ' Select base date (single cell)
    Set baseDateCell = Application.InputBox( _
        Prompt:="Select the base date (single cell)", _
        Title:="Base Date", _
        Type:=8)

    ' Select date range
    Set dateRange = Application.InputBox( _
        Prompt:="Select the date range", _
        Title:="Date Range", _
        Type:=8)

    ' Select sum range (must be same size as date range)
    Set sumRange = Application.InputBox( _
        Prompt:="Select the sum range (same size as date range)", _
        Title:="Sum Range", _
        Type:=8)

    ' Validate range size
    If dateRange.Rows.Count <> sumRange.Rows.Count Or _
       dateRange.Columns.Count <> sumRange.Columns.Count Then

        MsgBox "Date range and sum range must be the same size.", vbCritical
        Exit Sub

    End If

    resultSum = 0

    ' Loop through each cell
    For i = 1 To dateRange.Cells.Count

        If Year(dateRange.Cells(i).Value) = Year(baseDateCell.Value) And _
           Month(dateRange.Cells(i).Value) = Month(baseDateCell.Value) Then

            resultSum = resultSum + sumRange.Cells(i).Value

        End If

    Next i

    ' Write result to originally active cell
    resultCell.ClearContents
    resultCell.Value = resultSum

    MsgBox "Monthly sum completed.", vbInformation

End Sub


sumif 를 쓰기 귀찮다면, 한번 해볼만 하지 않을까??

끝.