我希望创建一个宏按钮来比较Excel中的A列和B列,并在C列中列出任何差异。
答案 0 :(得分:2)
创建一个工具栏,其上有一个运行Sub SelectionCompare的按钮。突出显示包含数据的2列,然后单击按钮。 BLAM!
您可以调整此代码,以便更好地处理空白,行标题,重复项,检测不正确的启动条件(如无选择或选择不正确),或检测/防止在输出列中覆盖数据。
Function ClipRange(Value As Excel.Range) As Excel.Range
Set ClipRange = Application.Intersect(Value, Value.Parent.UsedRange)
End Function
Function RangeToDict(Value As Excel.Range) As Object
Dim Cell As Excel.Range
Set RangeToDict = CreateObject("Scripting.Dictionary")
For Each Cell In Value
If Not RangeToDict.Exists(Cell.Value) Then
RangeToDict.Add Cell.Value, 1
End If
Next
End Function
Sub ColumnCompare(Column1 As Excel.Range, Column2 As Excel.Range, OutputColumn As Excel.Range)
Dim Dict1 As Object
Dim Dict2 As Object
Dim Cell As Excel.Range
Dim Key As Variant
Set Dict1 = RangeToDict(ClipRange(Column1))
Set Dict2 = RangeToDict(ClipRange(Column2))
Set Cell = OutputColumn.Cells(1, 1)
For Each Key In Dict1
If Not Dict2.Exists(Key) Then
Cell.Value = Key
Set Cell = Cell.Offset(1, 0)
End If
Next
For Each Key In Dict2
If Not Dict1.Exists(Key) Then
Cell.Value = Key
Set Cell = Cell.Offset(1, 0)
End If
Next
End Sub
Sub SelectionCompare()
ColumnCompare Selection.Columns(1), Selection.Columns(2), Selection.Columns(2).Offset(0, 1)
End Sub