![](/img/trans.png)
[英]How to compare two named ranges in same workbook but different worksheets?
[英]compare two set of columns in two excel worksheets in same workbook
工作表1
+------+-------+
| ID | Name |
+------+-------+
| 1245 | James |
| 9377 | Jacob |
| 6201 | David |
| . | . |
| . | . |
| . | . |
+------+-------+
工作表2
+------+-------+
| ID | Name |
+------+-------+
| 1245 | James |
| 9007 | Adam |
| 9377 | Jacob |
| 6201 | David |
| . | . |
| . | . |
| . | . |
+------+-------+
從理論上講,兩個工作表都是彼此的復本,但Sheet2具有其他數據。 Sheet1包含10000行,Sheet2包含15000行。如何在兩個工作表之間進行比較以顯示/突出顯示Sheet2中的5000個不同的行?
對於此類任務,我使用adodb記錄集來存儲第一張紙上的內容。 然后,我閱讀了第二張紙,看是否在第一張紙上。
在您的VBA IDE中,轉到工具菜單,然后選擇引用。 選擇“ Microsoft ActiveX數據對象2.8庫”。
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
您可以在Sheet2
上使用以下函數來查找Sheet2
的值,並查看它們是否存在於Sheet1
:
=IF(COUNTIFS(A2,Sheet1!A:A,B2,Sheet1!B:B)>0,"","X")
假設您在Sheet2
C2
輸入公式。 COUNTIFS()
僅檢查Sheet1
的ID
和Name
並返回找到的匹配行數。 如果找到它,我們將不在乎( ""
)。 如果找不到,則它是Sheet2
專用的,我們將其標記為"X"
。
當然,您也可以在VBA中執行此操作:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.