楼主 herelazy |
Q:如何用VBA根据出库和入库工作表中的源数据,在总表中汇总计算出库和入库数量及库存数量? 如图:
A:- Sub justtest()
- Dim d, ArrTemp, StrTemp$, oI&, ArrRe(), K&, dErr, StrErr$
- On Error Resume Next
- Set d = CreateObject("scripting.dictionary")
- Set dErr = CreateObject("scripting.dictionary")
- With Sheets("入")
- ArrTemp = .Range("a1").CurrentRegion.Value
- For oI = 2 To UBound(ArrTemp, 1)
- StrTemp = ArrTemp(oI, 1) & ArrTemp(oI, 2)
- If d.exists(StrTemp) Then
- ArrRe(3, d(StrTemp)) = ArrRe(3, d(StrTemp)) + ArrTemp(oI, 3)
- Else: K = K + 1: ReDim Preserve ArrRe(1 To 5, 1 To K)
- d.Add StrTemp, K: ArrRe(1, K) = ArrTemp(oI, 1)
- ArrRe(2, K) = ArrTemp(oI, 2): ArrRe(3, K) = ArrTemp(oI, 3)
- End If
- Next oI
- End With
- With Sheets("出")
- ArrTemp = .Range("a1").CurrentRegion.Value
- For oI = 2 To UBound(ArrTemp, 1)
- StrTemp = ArrTemp(oI, 1) & ArrTemp(oI, 2)
- If d.exists(StrTemp) Then
- ArrRe(4, d(StrTemp)) = ArrRe(4, d(StrTemp)) + ArrTemp(oI, 3)
- Else:
- dErr(StrTemp) = ""
- End If
- Next oI
- End With
- With Sheets("总表")
- For oI = 1 To K
- ArrRe(5, oI) = ArrRe(3, oI) - ArrRe(4, oI)
- Next
- .Range("a2:e" & .Rows.Count).ClearContents
- .Range("a2").Resize(K, 5) = Application.Transpose(ArrRe)
- End With
- If dErr.Count > 0 Then
- StrErr = "存在以下出库有而未入库项目未计入统计:" & vbCrLf & Join(dErr.keys, ",")
- End If
- MsgBox "处理完毕。" & StrErr
- Set d = Nothing
- Set dErr = Nothing
- End Sub
出入库和库存数量统计.rar |