简体   繁体   中英

How do I search for matching values in a range?

I have a range in Excel that looks like this:

  | Symptom       | Number|  
1 | back pain     | 7     |  
2 | neck pain     | 583   |  
3 | shoulder pain | 5098  |  
4 | eye pain      | 23467 |  
5 | back pain     | 23    |  
6 | neck pain     | 65756 |  
7 | shoulder pain | 234   |  
8 | eye pain      | 98    |

I want the values in Number to be compared against each other based on the value in Symptom. For example, back pain appears in Symptom twice, so I want 23 compared against 7. Upon determining which is larger, I want the second instance of the Symptom to be colored red or green, red if its Number is larger than the first instance, green if it's smaller.

Initially I tried writing code with 2 ranges, one with the first instance of each Symptom, and another range with the second instance of each Symptom. I tried writing a For Each loop within a For Each loop, but that's not allowed, so I'm stuck as to how to proceed. My code:

Sub RankColor()
    Dim SelecRng As Range
    Dim OrgNumOld As Integer
    Dim SearchTerm As String

    Set SelecRngOld = Application.Selection
    Set SelecRngOld = Application.InputBox("Range", SelecRng, Type:=8)

    Set SelecRngNew = Application.Selection
    Set SelecRngNew = Application.InputBox("Range", SelecRng, Type:=8)

    For Each cell In SelecRngOld
    Set SearchTerm = cell.Value
    OrgNumOld = Cells(cell.Row, 2).Value
        For Each cell in SelecRngNew
            If Cells(cell.Row, 2) > OrgNumOld Then 'Compares the
            Cells(cell.Row, 2).Color = RGB(256, 0, 0)
            ElseIf Cells(cell.Row, 2) > OrgNumOld Then
            Cells(cell.Row, 2).Color = RGB(0, 256, 0)
            End If
        End If
        Next
    Next

End Sub

Create two conditional formatting rules.

Red:

=AND(INDEX($B:$B,MATCH($A1,$A:$A,0))<$B1,MATCH($A1,$A:$A,0)<>ROW())

Green:

=AND(INDEX($B:$B,MATCH($A1,$A:$A,0))>$B1,MATCH($A1,$A:$A,0)<>ROW())

Both should Apply to $B:$B

在此处输入图片说明

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