- B1: Khởi động Microsoft Excel.
- B2: Nhấn ALT + F11 để bắt đầu Visual Basic Editor.
- B3: Vào Menu Inser\Module
- B2: Nhấn ALT + F11 để bắt đầu Visual Basic Editor.
- B3: Vào Menu Inser\Module
- B4: Nhập toàn bộ đoạn mã sau vào
Sub Highlight_Duplicate()
Dim ws As Worksheet
Dim cell As Range
Dim myrng As Range
Dim clr As Long
Dim lastcell As Range
Dim i As Long
Dim lastrow As Long
Set ws = ThisWorkbook.ActiveSheet
'Vung can danh dau gia tri trung nhau
Set myrng = ws.Range("C4:F" & Range("C" & ws.Rows.Count).End(xlUp).Row)
With myrng
Set lastcell = .Cells(.Cells.Count)
End With
myrng.Interior.ColorIndex = xlNone
clr = 3
For Each cell In myrng
'Kiem tra so gia tri trung nhau trong vung, neu co hai gia tri trung nhau tro len thi thuc hien
If Application.WorksheetFunction.CountIf(myrng, cell) > 1 Then
'Neu la o dau tien cua cac gia tri trung nhau trong vung
If myrng.Find(what:=cell, lookat:=xlWhole, MatchCase:=False, after:=lastcell).Address = cell.Address Then
'Thiet lap mau
cell.Interior.ColorIndex = clr
clr = clr + 1
i = i + 1
Else
'Thiet lap mau tu o thu 2 voi cac gia tri trung nhau
cell.Interior.ColorIndex = myrng.Find(what:=cell, lookat:=xlWhole, MatchCase:=False, after:=lastcell).Interior.ColorIndex
End If
End If
Next
'Lay dong cuoi cung cua vung du lieu
lastrow = Cells(Rows.Count, "A").End(xlUp).Row
Range("A" & lastrow + 2).Value = "Tong so co " & i & " gia tri trung nhau"
End Sub
Dim ws As Worksheet
Dim cell As Range
Dim myrng As Range
Dim clr As Long
Dim lastcell As Range
Dim i As Long
Dim lastrow As Long
Set ws = ThisWorkbook.ActiveSheet
'Vung can danh dau gia tri trung nhau
Set myrng = ws.Range("C4:F" & Range("C" & ws.Rows.Count).End(xlUp).Row)
With myrng
Set lastcell = .Cells(.Cells.Count)
End With
myrng.Interior.ColorIndex = xlNone
clr = 3
For Each cell In myrng
'Kiem tra so gia tri trung nhau trong vung, neu co hai gia tri trung nhau tro len thi thuc hien
If Application.WorksheetFunction.CountIf(myrng, cell) > 1 Then
'Neu la o dau tien cua cac gia tri trung nhau trong vung
If myrng.Find(what:=cell, lookat:=xlWhole, MatchCase:=False, after:=lastcell).Address = cell.Address Then
'Thiet lap mau
cell.Interior.ColorIndex = clr
clr = clr + 1
i = i + 1
Else
'Thiet lap mau tu o thu 2 voi cac gia tri trung nhau
cell.Interior.ColorIndex = myrng.Find(what:=cell, lookat:=xlWhole, MatchCase:=False, after:=lastcell).Interior.ColorIndex
End If
End If
Next
'Lay dong cuoi cung cua vung du lieu
lastrow = Cells(Rows.Count, "A").End(xlUp).Row
Range("A" & lastrow + 2).Value = "Tong so co " & i & " gia tri trung nhau"
End Sub
Trong ví dụ này, Kênh phần mềm đang để vùng cần đánh dấu từ cột C: F, các bạn có thể thay đổi địa chỉ của vùng này tùy vào dữ liệu thực tế.
- B5: Chạy Macro có tên Highlight_Duplicate
0 Response to "Đánh dấu các giá trị trùng nhau bằng những màu khác nhau bằng VBA trong Excel"
Đăng nhận xét