Sheet1
+------+-------+
| ID | Name |
+------+-------+
| 1245 | James |
| 9377 | Jacob |
| 6201 | David |
| . | . |
| . | . |
| . | . |
+------+-------+
Sheet2
+------+-------+
| ID | Name |
+------+-------+
| 1245 | James |
| 9007 | Adam |
| 9377 | Jacob |
| 6201 | David |
| . | . |
| . | . |
| . | . |
+------+-------+
In theory, both sheets are carbon copy of each other with the exception that Sheet2 have additional data. Sheet1 contains 10000 rows and Sheet2 contains 15000. How do I do a comparison between both worksheets to show/highlight the 5000 distinct rows in Sheet2?
For tasks like this I use a adodb recordset to store what was on the first sheet. Then i read up the second sheet and look to see if it was on the first.
In you VBA IDE go to the tools menu and select references. Select "Microsoft ActiveX Data Objects 2.8 Library."
Dim rs As New ADODB.Recordset
Dim ws As Excel.Worksheet
Dim lRow As Long
Set ws = Application.ActiveSheet
'Add fields to your recordset for storing data. You can store sums here.
With rs
.Fields.Append "Row", adInteger
.Fields.Append "ID", adInteger
.Fields.Append "NAME", adChar, 50
.Open
End With
lRow = 1
'Loop through and record what is in the first sheet
Do While lRow <= ws.UsedRange.Rows.count
rs.AddNew
rs.Fields("Row").Value = lRow
rs.Fields("ID").Value = ws.Range("A" & lRow).Value
rs.Fields("NAME").Value = ws.Range("B" & lRow).Value
rs.Update
lRow = lRow + 1
ws.Range("A" & lRow).Activate
Loop
'Switch to the second worksheet
Set ws = Nothing
Set ws = ActiveWorkbook.Sheets("Sheet2")
ws.Activate
'Loop through and compare to what was on the first column
lRow = 1
Do While lRow <= ws.UsedRange.Rows.count
rs.Filter = ""
rs.Filter = "ID=" & ws.Range("A" & lRow).Value
If rs.RecordCount = 0 Then
'We don't have a match, color the row
Rows(lRow).Interior.Color = vbBlue
End If
lRow = lRow + 1
ws.Range("A" & lRow).Activate
Loop
You can just use the following function on Sheet2
to lookup Sheet2
's values and see if they exist on Sheet1
:
=IF(COUNTIFS(A2,Sheet1!A:A,B2,Sheet1!B:B)>0,"","X")
This is assuming you enter the formula in C2
on Sheet2
. COUNTIFS()
just checks Sheet1
for the ID
and Name
and returns the number of rows found that match. If we find it, we don't care ( ""
). If we don't find it, then it's exclusive to Sheet2
and we'll mark it with an "X"
.
Of course, you can do this in VBA as well:
With Sheet2.Range("C2:C" & Sheet2.UsedRange.Rows.Count)
.Formula = "=IF(COUNTIFS(A2,Sheet1!A:A,B2,Sheet1!B:B)>0,"""",""X"")"
.Value = .Value ' (If you want to remove the formula)
End With
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.