假設Excel有一張銷售明細表:
欄位:A=日期、B=產品、C=數量、D=單價。
目標:用簡單的VBA,各「產品」的「銷售總額(數量×單價)」彙總到新的工作表。
範例程式碼(放置標準模組)
文字
Sub SummarySalesByProduct()
Dim wsSrc As Worksheet
Dim wsDst As Worksheet
Dim lastRow As Long
Dim dict As Object
Dim i As Long
Dim product As String
Dim amount As Double
' 原始資料工作表
Set wsSrc = ThisWorkbook.Worksheets("SalesData")
' 找最後一列
lastRow = wsSrc.Cells(wsSrc.Rows.Count, "A").End(xlUp).Row
' 建立 Dictionary 來彙總金額
Set dict = CreateObject("Scripting.Dictionary")
For i = 2 To lastRow ' 假設第 1 列是標題
product = wsSrc.Cells(i, "B").Value
amount = wsSrc.Cells(i, "C").Value * wsSrc.Cells(i, "D").Value
If dict.Exists(product) Then
dict(product) = dict(product) + amount
Else
dict.Add product, amount
End If
Next i
' 建立輸出工作表
On Error Resume Next
Application.DisplayAlerts = False
Worksheets("SummaryByProduct").Delete
Application.DisplayAlerts = True
On Error GoTo 0
Set wsDst = ThisWorkbook.Worksheets.Add
wsDst.Name = "SummaryByProduct"
' 輸出標題
wsDst.Range("A1").Value = "產品"
wsDst.Range("B1").Value = "銷售總額"
' 輸出資料
Dim key As Variant
Dim rowOut As Long
rowOut = 2
For Each key In dict.Keys
wsDst.Cells(rowOut, "A").Value = key
wsDst.Cells(rowOut, "B").Value = dict(key)
rowOut = rowOut + 1
Next key
' 可以再加上格式,例如貨幣格式
wsDst.Columns("A:B").AutoFit
End Sub
重點解說
使用CreateObject("Scripting.Dictionary")“匯總”,類似 SQL 的 GROUP BY。
迴圈逐列讀取原始數據,計算金額後累計對應產品。
最後輸出到新工作表,避免覆蓋原始數據,方便檢查與再次分析。
沒有留言:
張貼留言