標題: [發問] VBA sum 問題 [打印本頁] 作者: john2006168 時間: 2010-6-5 12:21 標題: VBA sum 問題
本帖最後由 john2006168 於 2010-6-5 12:23 編輯
[attach]1149[/attach]要做到好像sheet2,相同的ref no,sum of ctn and gw.其他不變
shee1
ref no ctn gw remark
john001 1 6 go
john002 2 2 go
john002 2 3 go
john002 1 2 go
john003 1 7 go
john004 1 8 go
john005 1 9 go
john006 1 10 go
john007 2 1 go
john007 2 1 go
john008 3 6 go
john009 4 7 go
john010 5 8 go
Sheet2
ref no ctn gw remark
john001 1 6 go
john002 5 7 go
john003 1 7 go
john004 1 8 go
john005 1 9 go
john006 1 10 go
john007 4 2 go
john008 3 6 go
john009 4 7 go
john010 5 8 go作者: Hsieh 時間: 2010-6-5 14:35
使用陣列方式
Sub Ex()
Dim Ar(), M, E As Range, R
ReDim Preserve Ar(1 To 1)
Ar(1) = Array("ref no", "Sum of ctr", "Sum of gw", "remark")
M = Array(Ar(1)(0))
For Each E In Sheet1.Range("A2", Sheet1.[d65536].End(xlUp)).Rows
R = Application.Match(E.Cells(1, 1).Value, M, 0)
If IsNumeric(R) Then
Ar(R)(1, 2) = Ar(R)(1, 2) + E.Cells(1, 2)
Ar(R)(1, 3) = Ar(R)(1, 3) + E.Cells(1, 3)
Else
ReDim Preserve Ar(1 To UBound(Ar) + 1)
Ar(UBound(Ar)) = E.Value
M = Split(Join(M, ",") & "," & Ar(UBound(Ar))(1, 1), ",")
End If
Next
Sheet2.Columns("A:D") = ""
Sheet2.[a1].Resize(UBound(Ar), 4).Value = Application.Transpose(Application.Transpose(Ar))
End Sub作者: john2006168 時間: 2010-6-5 22:45
Option Explicit
Sub TEST()
Dim Brr, i&, N&, xR, Y, j&, B&, C&
Set Y = CreateObject("Scripting.Dictionary")
Set xR = Range([Sheet1!D1], [Sheet1!A65536].End(3))
Brr = xR
For i = 2 To UBound(Brr)
If Y(Brr(i, 1)) = "" Then
Y(Brr(i, 1)) = Y.Count + 1: N = Y(Brr(i, 1))
For j = 1 To UBound(Brr, 2): Brr(N, j) = Brr(i, j): Next
Else
N = Y(Brr(i, 1))
For j = 2 To 3: Brr(N, j) = Brr(N, j) + Brr(i, j): Next
End If
B = B + Brr(i, 2): C = C + Brr(i, 3)
Next
With xR.Item(1, 14).Resize(Y.Count + 1, UBound(Brr, 2))
.EntireColumn.Clear: .Value = Brr: .Item(Y.Count + 2, 1) = "總計"
.Item(Y.Count + 2, 2) = B: .Item(Y.Count + 2, 3) = C
End With
Set Y = Nothing: Set xR = Nothing: Erase Brr
End Sub