본문 바로가기
Excel VBA

데이터 요약하기

2023. 8. 12.
Sub MergeProductDataWithFormatting()
    Dim x, i As Long, P As Long, k As Long, n As Long
    Dim ws As Worksheet
    Set ws = Sheets("Product")

    With ws.Range("a1").CurrentRegion
        x = .Value
        With CreateObject("Scripting.Dictionary")
            .Comparemode = 1
            For i = 1 To UBound(x)
                If .Exists(x(i, 1)) Then
                    n = .Item(x(i, 1))
                    x(.Item(x(i, 1)), 2) = x(.Item(x(i, 1)), 2) + x(i, 2)
                    x(.Item(x(i, 1)), 3) = x(.Item(x(i, 1)), 3) + x(i, 3)
                Else
                    P = P + 1
                    .Item(x(i, 1)) = P
                    For k = 1 To UBound(x, 2)
                        x(P, k) = x(i, k)
                    Next k
                End If
            Next i
        End With

        ' 데이터 출력
        Dim outputRange As Range
        Set outputRange = ws.Range("E1").Resize(P, UBound(x, 2))
        outputRange.Value = x

        ' 전체 테두리 추가
        With outputRange.Borders
            .LineStyle = xlContinuous
            .Weight = xlThin
        End With

        ' 첫 번째 행에 굵은 글꼴 적용
        With ws.Rows(1)
            .Font.Bold = True
        End With

        ' 열 너비 자동 조절
        outputRange.EntireColumn.AutoFit
    End With
End Sub

 

매크로 실행 전

 

매크로 실행 후

 

* 이건 공부를 위해 만든 코드이고 피벗테이블로 요약하는게 더 좋다고 생각합니다.