Try this code. Copy this code to workbook xls2. It will copy the contents of xls1 to a temp worksheet. Then it will copy the contents of xls2 to the temp worksheet and compare both. The result will be provided in the temp worksheet.
Option Explicit
Private Sub compare_files()
Dim lrow As Long, lrow1 As Long, lrow2 As Long, i As Long
Worksheets.Add(afteR:=Worksheets(Worksheets.Count)).Name = "Temp"
With Worksheets("Temp")
Workbooks("xls1.xl.xls").Worksheets("Sheet1").Columns(2).Copy .Range("A1")
.Range("B1").Value = "Sheet"
lrow = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("B2:B" & lrow).Value = "1"
lrow = Worksheets("Sheet1").Range("C" & Rows.Count).End(xlUp).Row
Worksheets("Sheet1").Range("C2:C" & lrow).Copy .Range("A" & .Rows.Count).End(xlUp).Offset(1, 0)
lrow1 = .Range("B" & .Rows.Count).End(xlUp).Row
lrow2 = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("B" & lrow1 + 1 & ":B" & lrow2).Value = "2"
.Sort.SortFields.Add Key:=Range("A:A"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With .Sort
.SetRange Range("A:B")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
For i = lrow2 To 2 Step -1
If .Range("A" & i).Value = .Range("A" & i - 1).Value And .Range("B" & i).Value <> .Range("B" & i - 1).Value Then
.Rows(i & ":" & i - 1).Delete
lrow = lrow - 2
End If
Next i
.Columns("B:B").Delete
End With
End Sub
Copy the Excel VBA code
Select the workbook in which you want to store the Excel VBA code
Hold the Alt key, and press the F11 key, to open the Visual Basic Editor
Choose Insert | Module
Where the cursor is flashing, choose Edit | Paste
To run the Excel VBA code:
Choose View | Macros
Select a macro in the list, and click the Run button.
Bookmarks