Sub CrossCompareAndHighlight()
Dim ws As Worksheet
Dim lastRow1 As Long, lastRow2 As Long
Dim i As Long, j As Long
Dim cValue1 As String, mValue1 As String
Dim cValue2 As String, mValue2 As String
Dim matchFound As Boolean
' 設定工作表(假設兩份資料在同一個工作表中,第一份在A1開始,第二份在A100開始)
' 請根據實際情況調整
Set ws = ActiveSheet
' 找到第一份資料的最後一行(假設從第1行開始)
lastRow1 = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row
' 找到第二份資料的最後一行(假設從第100行開始)
lastRow2 = ws.Cells(ws.Rows.Count, "M").End(xlUp).Row
' 清除之前的標記
ws.Range("Q1:R" & lastRow1).ClearContents
ws.Range("Q1:R" & lastRow1).Interior.ColorIndex = xlNone
' 比對第一份資料中的每一行
For i = 1 To lastRow1
cValue1 = ws.Cells(i, "C").Value
mValue1 = ws.Cells(i, "M").Value
' 初始化匹配標誌
matchFound = False
' 在第二份資料中查找匹配
For j = 1 To lastRow2
cValue2 = ws.Cells(j, "C").Value
mValue2 = ws.Cells(j, "M").Value
' 比較C欄和M欄的值
If cValue1 = cValue2 And mValue1 = mValue2 Then
matchFound = True
Exit For
End If
Next j
' 如果沒有找到匹配,則標記為不吻合
If Not matchFound Then
ws.Cells(i, "Q").Value = "不吻合"
ws.Cells(i, "R").Value = "不吻合"
ws.Cells(i, "Q").Interior.Color = RGB(255, 200, 200) ' 淡紅色
ws.Cells(i, "R").Interior.Color = RGB(255, 200, 200) ' 淡紅色
End If
Next i
' 比對第二份資料中的每一行(反向比對)
For j = 1 To lastRow2
cValue2 = ws.Cells(j, "C").Value
mValue2 = ws.Cells(j, "M").Value
' 初始化匹配標誌
matchFound = False
' 在第一份資料中查找匹配
For i = 1 To lastRow1
cValue1 = ws.Cells(i, "C").Value
mValue1 = ws.Cells(i, "M").Value
' 比較C欄和M欄的值
If cValue1 = cValue2 And mValue1 = mValue2 Then
matchFound = True
Exit For
End If
Next i
' 如果沒有找到匹配,則標記為不吻合
If Not matchFound Then
ws.Cells(j, "Q").Value = "不吻合"
ws.Cells(j, "R").Value = "不吻合"
ws.Cells(j, "Q").Interior.Color = RGB(255, 200, 200) ' 淡紅色
ws.Cells(j, "R").Interior.Color = RGB(255, 200, 200) ' 淡紅色
End If
Next j
MsgBox "比對完成!", vbInformation
End Sub