excel VBA宏-识别重复行和特定行

zf9nrax1  于 2023-05-19  发布在  其他
关注(0)|答案(1)|浏览(164)

具有预期结果

的样本数据

Sub HighlightDuplicateRows()
    Dim ws As Worksheet
    Set ws = ActiveSheet ' Change this to the appropriate worksheet
    
    Dim lastRow As Long
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row ' Change "A" to the column where the data starts
    
    Dim firstNames As Object
    Set firstNames = CreateObject("Scripting.Dictionary")
    
    Dim lastNames As Object
    Set lastNames = CreateObject("Scripting.Dictionary")
    
    Dim uniqueIDs As Object
    Set uniqueIDs = CreateObject("Scripting.Dictionary")
    
    Dim i As Long
    For i = 2 To lastRow ' Assuming headers are in row 1
        Dim firstName As String
        firstName = ws.Cells(i, "A").Value ' Change "A" to the appropriate column for first name
        
        Dim lastName As String
        lastName = ws.Cells(i, "B").Value ' Change "B" to the appropriate column for last name
        
        Dim uniqueID As String
        uniqueID = ws.Cells(i, "C").Value ' Change "C" to the appropriate column for unique ID
        
        If firstNames.Exists(firstName) And lastNames.Exists(lastName) And uniqueIDs.Exists(uniqueID) Then
            ' Highlight the original row
            Dim origRow As Variant
            origRow = Application.Match(firstName & lastName & uniqueID, _
                ws.Range("A2:C" & i - 1), 0)
            If IsNumeric(origRow) Then
                ws.Rows(origRow).Interior.Color = RGB(255, 255, 0) ' Highlight the row yellow
            End If
            
            ' Highlight the current row
            ws.Rows(i).Interior.Color = RGB(255, 255, 0) ' Highlight the row yellow
        Else
            firstNames(firstName) = True
            lastNames(lastName) = True
            uniqueIDs(uniqueID) = True
        End If
    Next i
End Sub

我试图突出显示重复行和特定行规则1:如果First,Last name和Unique id重复多次,则突出显示行Rule 2:如果First,Last name重复多次且唯一id包含STATEWIDE,则突出显示该行,表示未选择正确的行
有人能帮忙吗?

tcomlyy6

tcomlyy61#

通常的方法根本不是使用VBA。
1.按State、Lastname、Firstname和UniqueID对列表进行排序
1.在整个表范围内输入两个条件格式公式
a.第一个-=OR($E2=$E1,$E2=$E3)将背景格式化为黄色
B.第二个-=OR(AND($A2=$A1,$B2=$B1,$D2=$D1),AND($A2=$A3,$B2=$B3,$D2=$D3))背景为橙子
重要的是不要在数字前面有美元符号锚
最后,如果出于某种原因,您仍然希望在VBA中使用它,您仍然应该遵循以下算法:在VBA中对整个表进行排序,然后在整个表上创建条件公式。警告,条件公式在VBA中有些棘手;数据结构复杂。

相关问题