excel 检查VBA中的两列中是否存在值,并突出显示它们,忽略任一列中多余的重复项

pgx2nnw8  于 2022-12-30  发布在  其他
关注(0)|答案(1)|浏览(172)

我正在尝试让VBA查看一列中的值,然后检查另一列中是否存在相同的值。
然后,我尝试高亮显示两列中显示相同值的相同数量的单元格,这意味着如果相同值在一列中显示的次数与在另一列中显示的次数不同,我需要高亮显示每列中相同数量的单元格,而不高亮显示任何“多余”的重复值。
这张图片说明了我试图完成的任务。EXCEL SCREENSHOT
如图所示,这些值已被突出显示到它们在任一列中显示的程度,而其他重复值未被突出显示。
我尝试了这段代码,但它不起作用,并突出显示了我不希望得到突出显示的单元格。我试图循环通过列,并忽略已经突出显示的单元格。

Sub highlightMatchingValues()

'Declare variables
    Dim cellC As Range, cellE As Range

'Loop through each cell with a value in column C
       For Each cellC In Range("C:C").Cells
        If Not IsEmpty(cellC) And cellC.Interior.ColorIndex = xlNone Then 'ignore empty cells and cells that are already highlighted

'Loop through each cell with a value in column E
     For Each cellE In Range("E:E").Cells
            If Not IsEmpty(cellE) And cellE.Interior.ColorIndex = xlNone Then 'ignore empty cells and cells that are already highlighted
                 If cellC.value = cellE.value Then 'check for a match

'Highlight both cells green
    cellC.Interior.Color = vbGreen
    cellE.Interior.Color = vbGreen

               End If
             End If
         Next cellE
    End If
    Next cellC

End Sub
4nkexdtk

4nkexdtk1#

这里有一个可以解决您问题的解决方案

'Sheet name = sheetName

'First columns variables (column C = index 3)
Dim firstLine1 As Long
Dim lastLine1 As Long

firstLine1 = 1
lastLine1 = Worksheets("sheetName").Cells(Rows.Count, 3).End(xlUp).Row
    
'Second columns variables (column E = index 5)
Dim firstLine2 As Long
Dim lastLine2 As Long

firstLine2 = 1
lastLine2 = Worksheets("sheetName").Cells(Rows.Count, 5).End(xlUp).Row

'loop
For i = firstLine1 To lastLine1
    For j = firstLine2 To lastLine2
        If (Worksheets("sheetName").Cells(i, 3).Value = Worksheets("sheetName").Cells(j, 5)) Then
            If (Worksheets("sheetName").Cells(j, 5).Interior.Color <> vbGreen) Then
                Worksheets("sheetName").Cells(i, 3).Interior.Color = vbGreen
                Worksheets("sheetName").Cells(j, 5).Interior.Color = vbGreen
                Exit For
            End If
        End If
    Next j
Next i

相关问题