I want to compare two tables in the same sheet. I will select the first table and click on button to give as first input. Similarly I will give next table input. When I click 'compare' button, the result should be displayed by highlighting cells in the second table. Please help me to do this.
Below is the script I Used to compare two tables in two sheets. Please help me to find to give input using selection option
Private Sub CompareBtn_Click()
Dim first_index As Integer
Dim last_index As Integer
Dim sheet1 As Worksheet
Dim sheet2 As Worksheet
Dim r1 As Integer
Dim r2 As Integer
Dim found As Boolean
Dim rng As Range
Set sheet1 = Worksheets("Source")
Set sheet2 = Worksheets("Minus")
first_index = 1
last_index = sheet2.UsedRange.Rows.Count
For r2 = first_index To last_index
found = False
For r1 = first_index To last_index
If sheet1.Cells(r1, 1) = sheet2.Cells(r2, 1) _
And _
sheet1.Cells(r1, 2) = sheet2.Cells(r2, 2) _
Then
found = True
Exit For
End If
Next r1
If Not found Then
sheet2.Cells(r2, 1).Interior.ColorIndex = 35
sheet2.Cells(r2, 2).Interior.ColorIndex = 35
End If
Next r2
End Sub
Try the following code:
Sub CompareTable()
Dim oldTable As Range, newTable As Range, i As Integer, J As Integer, m As Integer, n As Integer
On Error Resume Next
Set oldTable = Application.InputBox(Prompt:="Please Select Raw Data", Title:="Range Select", Type:=8)
Set newTable = Application.InputBox(Prompt:="Please Select Processed Data", Title:="Range Select", Type:=8)
i = oldTable.Rows.Count
J = oldTable.Columns.Count
For m = 1 To i
For n = 1 To J
If oldTable.Cells(m, n) <> newTable.Cells(m, n) Then
newTable.Cells(m, n).Interior.ColorIndex = 6
End If
Next n
Next m
End Sub
This will ask you for two ranges. Select the two tables that you want to compare and the differences will be highlighted in the second table.
EDIT : _________________________________________________________________________________
Or you can update your code to:
Sub CompareBtn_Click()
Dim first_index As Integer
Dim last_index As Integer
Dim rows_index As Integer, columns_index As Integer
Dim sheet1 As Worksheet
Dim sheet2 As Worksheet
Dim r1 As Integer
Dim r2 As Integer
Dim found As Boolean
Dim rng As Range
Set sheet1 = Worksheets("Source")
Set sheet2 = Worksheets("Minus")
rows_index = sheet2.UsedRange.Rows.Count
columns_index = sheet2.UsedRange.Columns.Count
For r2 = 1 To rows_index
For r1 = 1 To columns_index
If sheet1.Cells(r2, r1) <> sheet2.Cells(r2, r1) Then
sheet2.Cells(r2, r1).Interior.ColorIndex = 35
End If
Next r1
Next r2
sheet2.Select
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.