Use Excel to compare data present in two different sheets in the same workbook

Yesterday one of my colleague asked me if, it was possible to compare two different sheets in excel. I told him, "Everything is Possible in Excel". I thought it can be done with the help of Excel inbuilt functions. I tried, I failed. I thought why not write a small macro to do the same. Here I present the same. Before you copy and paste the code, I would like to elucidate few things. First, the sheets to compared must be present in the same excel having the macro. Second, either you name those sheets as Sheet1 and Sheet2 or change the name accordingly in the code.


Sub Button1_Click()

Dim r1, r2 As Range

Set r1 = Worksheets("sheet1").Range("A1")

Set r2 = Worksheets("sheet2").Range("A1")

No_Of_Rows_r1 = Worksheets("Sheet1").Range("A10000").End(xlUp).Row

No_Of_Cols_r1 = Worksheets("Sheet1").Range("A1").End(xlToRight).Column

No_Of_Rows_r2 = Worksheets("Sheet2").Range("A10000").End(xlUp).Row

No_Of_Cols_r2 = Worksheets("Sheet2").Range("A1").End(xlToRight).Column

If ((No_Of_Rows_r1 <> No_Of_Rows_r2) Or (No_Of_Cols_r1 <> No_Of_Cols_r2)) Then

    MsgBox "Row/Column Mismatch"

    Exit Sub

Else

    MsgBox "Row/Column Match Sucessful"   

End If

  

For row_comparison = 1 To No_Of_Rows_r1

    For col_comparison = 1 To No_Of_Cols_r1

        If (r1.Offset(row_comparison - 1, col_comparison - 1).Value <> r2.Offset(row_comparison - 1, col_comparison - 1).Value) Then

            MsgBox "Data Mismatch at Sheet2 at Cell = " & r1.Offset(row_comparison - 1, col_comparison - 1).Address

            Exit Sub

        End If

    Next col_comparison

Next row_comparison



MsgBox "No Mismatch Found"

End Sub

This worked for him and I hope it works for you too. Instead of for...next, one can also use foreach...in...next.

Happy VBA....ing