2025年12月19日 星期五

VBA 資料分析教學:DAY 7

 假設你在Excel的Sales工作表中有以下欄位:

A欄:日期(日期)

B欄:業務員(營業員)

C欄:金額 (Amount)

目標:以VBA自動計算業務當月總銷售金額,並輸出至Summary工作表。



Sub SalesSummaryBySalesperson()

    Dim wsSrc As Worksheet

    Dim wsDst As Worksheet

    Dim lastRow As Long

    Dim dict As Object

    Dim i As Long

    Dim name As String

    Dim amt As Double

    Dim key As Variant

    Dim outRow As Long

    

    ' 來源與目的工作表

    Set wsSrc = ThisWorkbook.Worksheets("Sales")

    Set wsDst = ThisWorkbook.Worksheets("Summary")

    

    ' 找到來源資料最後一列(假設以 B 欄業務名稱為基準)

    lastRow = wsSrc.Cells(wsSrc.Rows.Count, "B").End(xlUp).Row

    

    ' 使用 Scripting.Dictionary 做彙總

    Set dict = CreateObject("Scripting.Dictionary")

    

    ' 從第 2 列開始,假設第 1 列為標題

    For i = 2 To lastRow

        name = wsSrc.Cells(i, "B").Value

        amt = wsSrc.Cells(i, "C").Value

        

        If dict.Exists(name) Then

            dict(name) = dict(name) + amt

        Else

            dict.Add name, amt

        End If

    Next i

    

    ' 清空 Summary 工作表舊資料

    wsDst.Cells.Clear

    

    ' 輸出標題

    wsDst.Range("A1").Value = "業務員"

    wsDst.Range("B1").Value = "總銷售額"

    

    ' 將彙總結果寫回工作表

    outRow = 2

    For Each key In dict.Keys

        wsDst.Cells(outRow, "A").Value = key

        wsDst.Cells(outRow, "B").Value = dict(key)

        outRow = outRow + 1

    Next key

    

    ' 簡單格式化:加上千分位以及粗體標題

    wsDst.Range("A1:B1").Font.Bold = True

    wsDst.Columns("A:B").AutoFit

    wsDst.Range("B2:B" & outRow - 1).NumberFormat = "#,##0"

    

End Sub


重點解說

使用Scripting.Dictionary“鍵值名稱”,鍵是業務員,值是銷售額,適合做總結分析。號

透過迴圈讀取每列數據,根據業務員名稱累加金額,最後批量輸出到匯總工作表,可避免在迴圈中間隙出現儲存格造成低落。號


這個寫法之後可以延伸:

增加月份條件,只彙總指定月份。

改為依「產品別」或「客戶別」做匯總。

安排AutoFilter或AdvancedFilter前處理資料重新匯總。

 

沒有留言:

張貼留言

指數變化(2026.01.23) 開始透過AI做整理

  指數變化(2026.01.23) 開始透過AI做整理 上周焦點: 1/13消費者物價相關 美國消費者物價指數(CPI)年增率:2.7%(符合預期),月增率:0.3%。 美國核心CPI年增率:2.6%。 1/14企業庫存、房市、能源及房貸相關 美國企業庫存月增率:0.3%(10...