Sub TEST_A01()
Dim Arr, xD, i&, j%, N&, T$, U&
Set xD = CreateObject("Scripting.Dictionary")
Sheets("工作表2").UsedRange.EntireRow.Delete
Arr = Range([工作表1!I1], [工作表1!A1].Cells(Rows.Count, 1).End(xlUp))
For i = 2 To UBound(Arr)
T = Arr(i, 2) & "|"
If Arr(i, 4) = "組合折扣" Then T = T & "S"
For j = 6 To 9: xD(T & j) = xD(T & j) + Arr(i, j): Next
Next i
'-----------------------------------
For i = 2 To UBound(Arr)
If Arr(i, 4) = "組合折扣" Then GoTo i01
T = Arr(i, 2) & "|"
N = N + 1
For j = 1 To 5: Arr(N + 1, j) = Arr(i, j): Next
For j = 6 To 9
Arr(N + 1, j) = Arr(i, j) + Arr(i, j) * (xD(T & "S" & j) / xD(T & j))
Next j
i01: Next i
'-----------------------------------
[工作表2!A1:I1].Resize(N + 1) = Arr
End Sub
Sub TEST_A01()
Dim Arr, xD, i&, j%, N&, T$, U&
'↑宣告變數
Set xD = CreateObject("Scripting.Dictionary")
'↑令xD變數是 字典
Sheets("工作表2").UsedRange.EntireRow.Delete
'↑令表2使用儲存格所在的列刪除
Arr = Range([工作表1!I1], [工作表1!A1].Cells(Rows.Count, 1).End(xlUp))
'↑令Arr變數是 二維陣列,以表1的A~I欄儲存格值帶入陣列中
For i = 2 To UBound(Arr)
'↑設順迴圈
T = Arr(i, 2) & "|"
'↑令T變數是第2欄陣列值連接"|"符號的新字串
If Arr(i, 4) = "組合折扣" Then T = T & "S"
'↑如果第4欄陣列值是 "組合折扣"字串!就令T變數再連接"S"字元
For j = 6 To 9: xD(T & j) = xD(T & j) + Arr(i, j): Next
'↑設順迴圈!令T變數連接j迴圈數的新字串當key,
'其item值各累加j變數當欄的Arr陣列值
Next i
'-----------------------------------
For i = 2 To UBound(Arr)
'↑設順迴圈
If Arr(i, 4) = "組合折扣" Then GoTo i01
'↑如果第4欄陣列值是 "組合折扣"字串!就不處理後續,跳到i01位置繼續執行
T = Arr(i, 2) & "|"
'↑令T變數是第2欄陣列值連接"|"符號的新字串,加"|"是防萬一
N = N + 1
'↑令N變數累加1(累加結果列數,一開始就+1是為了空出標題的列)
For j = 1 To 5: Arr(N + 1, j) = Arr(i, j): Next
'↑設順迴圈!令Arr陣列從第二列開始寫入結果值(1~5欄)
For j = 6 To 9
'↑設順迴圈
Arr(N + 1, j) = Arr(i, j) + Arr(i, j) * (xD(T & "S" & j) / xD(T & j))
'↑令6~9欄Arr陣列值結果列是
'迴圈列個欄值+ 迴圈列個欄值*(組合折扣總金額/非組合折扣總金額)
'計算組合折扣後平均價格(因為組合折扣值是負值,所以是用相加計算)
Next j
i01: Next i
'-----------------------------------
[工作表2!A1:I1].Resize(N + 1) = Arr
'↑令表2寫入Arr陣列值,超過結果值的陣列值忽略
End Sub作者: Andy2483 時間: 2023-6-2 16:46
謝謝論壇,謝謝各位前輩
後學藉此帖學習陣列與字典,學習方案如下,請各前輩指教
Option Explicit
Sub TEST()
Dim Brr, Y, R&, i&, j%, T$, K$
Set Y = CreateObject("Scripting.Dictionary")
Sheets("工作表2").[A:I].ClearContents
Brr = Range([工作表1!I1], [工作表1!A65536].End(3))
K = "組合折扣"
For i = 2 To UBound(Brr)
T = Brr(i, 4): T = Brr(i, 2) & "|" & IIf(T = K, K, "")
For j = 6 To 9: Y(T & j) = Y(T & j) + Brr(i, j): Next
Next
For i = 2 To UBound(Brr)
If Brr(i, 4) = K Then GoTo i01
T = Brr(i, 2) & "|"
R = R + 1
For j = 1 To 5: Brr(R + 1, j) = Brr(i, j): Next
For j = 6 To 9
Brr(R + 1, j) = Brr(i, j) + Brr(i, j) * (Y(T & K & j) / Y(T & j))
Next j
i01: Next i
[工作表2!A1:I1].Resize(R + 1) = Brr
Set Y = Nothing: Erase Brr
End Sub