并肩作战的好兄弟实现快速汇总:字典 数组
文章作者:taller
图文整理:看见星光
前言
实例需求
料号和机种号为统计的关键字段
未交数量求和
交期汇总,包含时间和数量
示例代码
Sub LoadData() Dim aData, aRes(), lst, iRow, iCol, iKeyCol, Dic Const COLUMNS_QTY = 21 With Sheets('交货排程') iKeyCol = 5 lst = .Cells(.Rows.Count, iKeyCol).End(xlUp).Row aData = .Cells(2, 1).Resize(lst, COLUMNS_QTY).Value End With Set Dic = CreateObject('Scripting.Dictionary') For iRow = 3 To UBound(aData, 1) skey = aData(iRow, 5) & '|' & aData(iRow, 6) If Len(skey) > 1 Then If Dic.exists(skey) Then Dic(skey) = Array(Val(aData(iRow, 9)) + Dic(skey)(0), Dic(skey)(1)) Else Dic(skey) = Array(Val(aData(iRow, 9)), '') End If For iCol = 11 To UBound(aData, 2) If Val(aData(iRow, iCol)) > 0 Then sdate = VBA.Replace(Format(aData(2, iCol), 'm-d'), '-', '/') Debug.Print Dic(skey)(1) & ',' & sdate & '*' & aData(iRow, iCol) Dic(skey) = Array(Dic(skey)(0), Dic(skey)(1) & ',' & sdate & '*' & aData(iRow, iCol)) End If Next iCol End If Next iRow ReDim aRes(1 To Dic.Count, 1 To 4) n = 1 For Each d In Dic.keys akey = Split(d, '|') aRes(n, 1) = akey(0) aRes(n, 2) = akey(1) aRes(n, 3) = Dic(d)(0) aRes(n, 4) = Mid(Dic(d)(1), 2) n = n + 1 Next ' 结果数组aRes回写到工作表中 With Sheets('结果') .Range('2:10000').ClearContents .Cells(2, 1).Resize(Dic.Count, 4).Value = aRes .Range('a1').CurrentRegion.Borders.LineStyle = xlContinuous End With Set Dic = NothingEnd Sub
代码解析
aData = .Cells(2, 1).Resize(lst, COLUMNS_QTY).Value
skey = aData(iRow, 5) & '|' & aData(iRow, 6
aData(iRow, 9)
做为数组第一个元素,第二元素暂时留空。Val(aData(iRow, 9)) + Dic(skey)(0)
将未交数量进行累加,并保留已有的交期信息Val(aData(iRow, 9)) + Dic(skey)(0)
。If Dic.exists(skey) Then Dic(skey) = Array(Val(aData(iRow, 9)) + Dic(skey)(0), Dic(skey)(1))Else Dic(skey) = Array(Val(aData(iRow, 9)), '')End If
Dic(skey)(0)='xxx'
的形式。For iCol = 11 To UBound(aData, 2)
If Val(aData(iRow, iCol)) > 0 Then
sdate = VBA.Replace(Format(aData(2, iCol), 'm-d'), '-', '/')
Debug.Print Dic(skey)(1) & ',' & sdate & '*' & aData(iRow, iCol)
Dic(skey) = Array(Dic(skey)(0), Dic(skey)(1) & ',' & sdate & '*' & aData(iRow, iCol))
End If
Next iCol
Mid(Dic(d)(1), 2)
用于去掉交期信息中的第一个逗号。For Each d In Dic.keys
akey = Split(d, '|')
aRes(n, 1) = akey(0)
aRes(n, 2) = akey(1)
aRes(n, 3) = Dic(d)(0)
aRes(n, 4) = Mid(Dic(d)(1), 2)
n = n + 1
Next
后记
赞 (0)