简体   繁体   中英

Change the color of x number of cells based on the numeric value from another cell

I have range and i want to highlight my range of cells based value i enter in cell Range("C5"). If i enter 5 in cell "C5" then 5 cells in my range needs to be changed to yellow color. 在此处输入图片说明

Dim MY_RANGE As Range
Dim VALUE1 As Integer
Dim CEL As String

Set MY_RANGE = Range("H8,J8,L8,N8,H10,H10,J10,L10,N10,H12,J12,L12,N12,H14,J14,L14,N14,H16,J16,L16,N16,N16")
VALUE1 = Range("C2")

For Each CEL In MY_RANGE.Cells
    If CEL.Value = VALUE1 Then
        With CEL
                 .Italic = False
                .Bold = True
                .Color = 255
                .TintAndShade = 0
        End With
    End If
Next CEL

Can someone help pls..

You need to introduce a counter and to count:

Public Sub TestMe()

    Dim myRange     As Range
    Dim myCell      As Range

    Set myRange = Range("H8,J8,L8,N8,H10,H10,J10,L10,N10,H12,J12,L12,N12,H14,J14,L14,N14") 

    Dim cnt     As Long
    Dim times   As Long
    times = Range("C2")

    For Each myCell In myRange    
        With myCell
            .Interior.Color = vbBlue
        End With

        cnt = cnt + 1
        If cnt = times Then Exit Sub            
    Next myCell

End Sub

The idea is that every time the code loops the counter is increased with 1 , hence cnt = cnt + 1 . If it loops N exactly Range("C2") times, it exits.

you can use Areas() property of Range() object:

Public Sub ColorCells()
    Dim iCell As Long

    With Range("H8,J8,L8,N8,H10,J10,L10,N10,H12,J12,L12,N12,H14,J14,L14,N14") ' reference your range
        For iCell = 1 To Range("C2").Value ' loop through needed areas
            .Areas(iCell).Interior.Color = vbYellow
        Next
    End With
End Sub

Note: in your MY_RANGE range there were two "H10" occurrences

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