VBA Lọc dữ liệu trùng tự động trong Excel

VBA Lọc dữ liệu trùng tự động trong Excel

Giã sử bạn có 1 dữ liệu như sau 

Mã học viên
a
b
c
d
e
a

Có 2 cách code VBA Excel tìm dữ liệu trùng

  1. Code VBA copy dữ liệu trùng ra một vị trí chỉ định
  2. Code VBA thay đổi màu chữ khi dữ liệu bi trùng

1. Code VBA copy dữ liệu trùng ra một vị trí chỉ định

  Dim tenCotXuLy As String
    tenCotXuLy = "B"
    
    Dim vitriXuatDL_Ten As String
    vitriXuatDL_Ten = "E"
    Dim vitriXuatDL_Dong As Integer
    vitriXuatDL_Dong = 3


    Dim arr As Variant
    Row_start = ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlNext).Row + 1
    Row_end = ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    
    arr = Range(tenCotXuLy & Row_start & ":" & tenCotXuLy & Row_end).Value
    
    Dim sl_timduoc As Integer
    
    For i = Row_start To Row_end
       gtTim = Range(tenCotXuLy & i).Value
       
       sl_timduoc = 0
       For j = 1 To UBound(arr)
        gt_arr = arr(j, 1)
        If gtTim = gt_arr Then
            sl_timduoc = sl_timduoc + 1
        End If
       Next ' J tim mang
       If sl_timduoc > 1 Then
            Range(vitriXuatDL_Ten & vitriXuatDL_Dong).Value = gtTim
            vitriXuatDL_Dong = vitriXuatDL_Dong + 1
       End If
    Next

2. Code VBA thay đổi màu chữ khi dữ liệu bi trùng

 

Dòng nào trùng sẽ đổi màu chữ thành màu đỏ vba


 Dim tenCotXuLy As String
    tenCotXuLy = "B"

    Dim arr As Variant
    Row_start = ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlNext).Row + 1
    Row_end = ActiveSheet.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    
    arr = Range(tenCotXuLy & Row_start & ":" & tenCotXuLy & Row_end).Value
    
    Dim sl_timduoc As Integer
    
    For i = Row_start To Row_end
       gtTim = Range(tenCotXuLy & i).Value
       
       sl_timduoc = 0
       For j = 1 To UBound(arr)
        gt_arr = arr(j, 1)
        If gtTim = gt_arr Then
            sl_timduoc = sl_timduoc + 1
        End If
       Next ' J tim mang
       Range(tenCotXuLy & i).Select
       If sl_timduoc > 1 Then
            With Selection.Font
                .Color = -16776961
                .TintAndShade = 0
            End With
       Else
            With Selection.Font
                .ColorIndex = xlAutomatic
                .TintAndShade = 0
            End With
       End If
       
    Next

Video hướng dẫn code lọc dữ liệu VBA Excel

Bài viết liên quan:

VBA Lọc dữ liệu trùng tự động trong Excel