簡體   English   中英

檢查 VBA 中的兩列中是否存在值並突出顯示它們,在任何一列中遺漏多余的重復項

[英]Check if value exists in two columns in VBA and highlight them, leaving out excess duplicates in either column

我試圖讓 VBA 查看一列中的值,然后檢查另一列中是否存在相同的值。

然后,我試圖在顯示相同值的兩列中突出顯示相同數量的單元格,這意味着如果相同的值在一列中顯示的次數與另一列中的次數不同,我需要突出顯示相同數量的每列中的單元格,並保留任何“多余”的重復值而不突出顯示。

圖片說明了我正在努力完成的事情。 EXCEL 截圖

如圖所示,這些值已突出顯示到它們在任一列中顯示的程度,而其他重復值沒有突出顯示。

我嘗試了這段代碼,但它不起作用,並突出顯示了我不希望突出顯示的單元格。 我試圖遍歷列並忽略已經突出顯示的單元格。

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

這里有一個解決方案可以解決您的問題

'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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM