Mã VBA so sánh dữ liệu sheet1 và sheet2 , lấy shee2 làm gốc, kết quả không trùng lặp của sheet2 ghi vào sheet3 trùng lặp ghi vào sheet 4
Mã VBA Cập Nhật
Sub RemoveAndRecordDuplicates()
Dim ws1 As Worksheet, ws2 As Worksheet, ws3 As Worksheet, ws4 As Worksheet
Dim cell As Range
Dim dict As Object
Dim dictDuplicates As Object
Dim i As Long
Dim key As Variant
' Thiết lập các worksheet
Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
Set ws3 = ThisWorkbook.Sheets("Sheet3")
Set ws4 = ThisWorkbook.Sheets("Sheet4")
' Xoá nội dung cũ trong Sheet3 và Sheet4
ws3.Cells.Clear
ws4.Cells.Clear
' Tạo đối tượng Dictionary để lưu trữ giá trị của Sheet1
Set dict = CreateObject("Scripting.Dictionary")
' Tạo đối tượng Dictionary để lưu trữ giá trị trùng lặp
Set dictDuplicates = CreateObject("Scripting.Dictionary")
' Đọc dữ liệu từ Sheet1 và lưu vào Dictionary
With ws1
For i = 1 To .Cells(.Rows.Count, 1).End(xlUp).Row
dict(.Cells(i, 1).Value) = True
Next i
End With
' Xử lý dữ liệu từ Sheet2 và phân loại trùng lặp
With ws2
For Each cell In .Range("A1:A" & .Cells(.Rows.Count, 1).End(xlUp).Row)
If dict.exists(cell.Value) Then
' Nếu giá trị trùng lặp, lưu vào Dictionary trùng lặp
If Not dictDuplicates.exists(cell.Value) Then
dictDuplicates.Add cell.Value, True
End If
Else
' Nếu giá trị không trùng lặp, sao chép vào Sheet3
ws3.Cells(ws3.Cells(ws3.Rows.Count, 1).End(xlUp).Row + 1, 1).Value = cell.Value
End If
Next cell
End With
' Ghi các giá trị trùng lặp vào Sheet4
With ws4
i = 1
For Each key In dictDuplicates.keys
.Cells(i, 1).Value = key
i = i + 1
Next key
End With
' Thông báo hoàn tất
MsgBox "Đã hoàn tất việc loại bỏ giá trị trùng lặp và ghi kết quả vào Sheet3 và Sheet4.", vbInformation
End Sub
Giải Thích Cập Nhật
Nhận xét
Đăng nhận xét