鉴于我有以下内容
<Sheet 1>
Item QTY
A 5
B 1
C 3
<Sheet 2>
Item QTY
A 15
B 4
C 1
D 8
Run Code Online (Sandbox Code Playgroud)
生成显示工作表1和2之间差异的报告的最佳方法是什么?
喜欢
<Difference>
Item QTY
A 10
B 3
C -2
D 8
Run Code Online (Sandbox Code Playgroud)
在 Excel VBA 中,使用Dictionary。使用其中一张表中的项目作为键,使用数量作为值。将工作表 1 的项目/数量对放入字典中,然后遍历工作表 2 的项目,相应地更新字典以获取其中的差异。最后将结果填入表3。
编辑:这是代码中的完整示例(您必须设置对 Microsoft 脚本运行时的引用才能使其以这种方式工作):
Option Explicit
Sub CreateDiff()
Dim dict As New Dictionary
Dim sh1 As Worksheet, sh2 As Worksheet, sh3 As Worksheet
Dim i As Long, v As String
Set sh1 = ThisWorkbook.Sheets("Sheet1")
Set sh2 = ThisWorkbook.Sheets("Sheet2")
Set sh3 = ThisWorkbook.Sheets("Sheet3")
For i = 2 To sh1.Cells.SpecialCells(xlCellTypeLastCell).Row
v = Trim(sh1.Cells(i, 1).Value)
dict(v) = -sh1.Cells(i, 2).Value
Next
For i = 2 To sh2.Cells.SpecialCells(xlCellTypeLastCell).Row
v = Trim(sh2.Cells(i, 1).Value)
If dict.Exists(v) Then
dict(v) = dict(v) + sh2.Cells(i, 2).Value
Else
dict(v) = sh2.Cells(i, 2).Value
End If
Next
For i = 0 To dict.Count - 1
v = dict.Keys(i)
sh3.Cells(i + 2, 1) = v
sh3.Cells(i + 2, 2) = dict(v)
Next
End Sub
Run Code Online (Sandbox Code Playgroud)