Sub Compare_Difference3()
Dim n&, eRow1&, eRow2&
Dim StartTime#, SecondsElapsed#
Dim key1 As Variant, key2 As Variant
Dim cell As Range
Dim DictA As Object, DictB As Object
Dim ws1 As Worksheet, ws2 As Worksheet
StartTime = Timer
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Set ws1 = ActiveWorkbook.Sheets(1)
Set ws2 = ActiveWorkbook.Sheets(2)
Set DictA = CreateObject("Scripting.Dictionary")
Set DictB = CreateObject("Scripting.Dictionary")
' Get last row for each data on Sheet1 and Sheet2
eRow1 = ws1.Range("A1").End(xlDown).Row
eRow2 = ws2.Range("A1").End(xlDown).Row
' Fill Dictionary
For n = 2 To eRow1
DictA.Add n, ws1.Range("A" & n) & " " & ws1.Range("B" & n)
Next
For n = 2 To eRow2
DictB.Add n, ws2.Range("A" & n) & " " & ws2.Range("B" & n)
Next
ws1.Range("D1") = "Diff (Sht2 - Sht1)"
For Each key1 In DictA
For Each key2 In DictB
If DictB(key2) = DictA(key1) Then
If ws2.Range("C" & key2) = ws1.Range("C" & key1) Then
ws2.Range("A" & key2, "C" & key2).Interior.ColorIndex = 6
DictB.Remove key2
Exit For
Else
ws2.Range("A" & key2, "B" & key2).Interior.ColorIndex = 6
ws1.Range("D" & key1) = ws2.Range("C" & key2) - ws1.Range("C" & key1)
Exit For
End If
End If
Next
Next
DictB.RemoveAll
For n = 2 To eRow2
DictB.Add n, ws2.Range("A" & n) & " " & ws2.Range("B" & n)
Next
ws2.Range("D1") = "Diff (Sht1 - Sht2)"
For Each key2 In DictB
For Each key1 In DictA
If DictA(key1) = DictB(key2) Then
If ws1.Range("C" & key1) = ws2.Range("C" & key2) Then
ws1.Range("A" & key1, "C" & key1).Interior.ColorIndex = 42
DictA.Remove key1
Exit For
Else
ws1.Range("A" & key1, "B" & key1).Interior.ColorIndex = 42
ws2.Range("D" & key2) = ws1.Range("C" & key1) - ws2.Range("C" & key2)
Exit For
End If
End If
Next
Next
' Sort ws1
With ws1.Sort
.SortFields.Clear
.SortFields.Add Key:=Range("A1"), SortOn:=xlSortOnValues, Order:=xlAscending
.SetRange Range("A1", "D" & eRow1)
.Header = xlYes
.Apply
End With
' Sort ws2
With ws2.Sort
.SortFields.Clear
.SortFields.Add Key:=Range("A1"), SortOn:=xlSortOnValues, Order:=xlAscending
.SetRange Range("A1", "D" & eRow2)
.Header = xlYes
.Apply
End With
' Return cursor to cell A1 for each worksheet
Application.Goto ws2.Range("A1"), True
Application.Goto ws1.Range("A1"), True
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
'Determine how many seconds code took to run
SecondsElapsed = Round(Timer - StartTime, 2)
'Notify user in seconds
MsgBox "This code ran successfully in " & SecondsElapsed & " seconds", vbInformation
End Sub