|
楼主 |
发表于 2023-4-4 16:36
|
显示全部楼层
- Sub CheckDuplicateData()
- Dim ws As Worksheet
- Dim dict1 As Object, dict2 As Object
- Dim lastRow As Long, i As Long
- Dim cell As Range
- Dim duplicate As Boolean
- Dim duplicateFound1 As Boolean
- Dim duplicateFound2 As Boolean
-
- Set dict1 = CreateObject("Scripting.Dictionary")
- Set dict2 = CreateObject("Scripting.Dictionary")
-
- '恢复原来颜色
- For Each ws In ThisWorkbook.Worksheets
- If ws.Name = "表1" Or ws.Name = "表2" Then
- lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
- For i = 2 To lastRow
- ws.Cells(i, 1).Interior.ColorIndex = xlNone
- Next i
- End If
- Next ws
-
- '检测表1中的重复数据
- For Each cell In Sheets("表1").Range("A2:A" & Sheets("表1").Range("A" & Rows.Count).End(xlUp).Row)
- If Not dict1.Exists(cell.value) Then
- dict1.Add cell.value, cell.Address
- Else
- duplicate = True
- Sheets("表1").Range(dict1(cell.value)).Interior.Color = vbYellow
- cell.Interior.Color = vbYellow
- End If
- Next cell
-
- '检测表2中的重复数据
- For Each cell In Sheets("表2").Range("A2:A" & Sheets("表2").Range("A" & Rows.Count).End(xlUp).Row)
- If Not dict2.Exists(cell.value) Then
- dict2.Add cell.value, cell.Address
- Else
- duplicate = True
- Sheets("表2").Range(dict2(cell.value)).Interior.Color = vbYellow
- cell.Interior.Color = vbYellow
- End If
- Next cell
-
- '提示重复数据
- For Each cell In Sheets("表1").Range("A2:A" & Sheets("表1").Range("A" & Rows.Count).End(xlUp).Row)
- If cell.Interior.Color = vbYellow Then
- duplicateFound1 = True
- Exit For
- End If
- Next cell
-
- For Each cell In Sheets("表2").Range("A2:A" & Sheets("表2").Range("A" & Rows.Count).End(xlUp).Row)
- If cell.Interior.Color = vbYellow Then
- duplicateFound2 = True
- Exit For
- End If
- Next cell
-
- If duplicateFound1 And duplicateFound2 Then
- MsgBox "表1和表2中都存在重复数据,请检查标记为黄色的单元格。"
- ElseIf duplicateFound1 Then
- MsgBox "表1中存在重复数据,请检查标记为黄色的单元格。"
- ElseIf duplicateFound2 Then
- MsgBox "表2中存在重复数据,请检查标记为黄色的单元格。"
- End If
- End Sub
复制代码 以上是AI机器人写的代码,
|
|