简体   繁体   中英

Highlight a value in Column B based on Value in a selected cell in Column A (Excel VBA)

I want to highlight, in Excel, a value in column B based on the same value in Column A.

As soon as I select cell A2 the same values in B1 and B3 are highlighted with a color.

When I select A3 the same value in B4 is highlighted with a color. The previous highlighted cells B1 and B3 do not have a color anymore.

I've tried to do this based on Worksheet_Selection_Change but I can't figure out how this will work.

Example:

  • Cell A1 = 50 B1 = 100
  • Cell A2 = 100 B2 = 80
  • Cell A3 = 120 B3 = 100
  • Cell A4 = 20 B4 = 120

Are you thinking of something like this?

If the amount of data in column B is very large, it might be more efficient using a different method, but I believe this should work fine for a small worksheet.

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim r As Range, c As Range
    
    If Target.Rows.Count = 1 And Target.Columns.Count = 1 Then
        Set r = Me.Range("B1:B" & Me.Range("B" & Me.Rows.Count).End(xlUp).Row)
        
        r.Interior.Color = xlNone
        
        For Each c In r
            If c = Target Then
                c.Interior.Color = vbGreen
            End If
        Next c
    End If
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM