根据另一个单元格中的数值更改x个单元格的颜色

时间:2018-05-17 12:58:45

标签: vba excel-vba excel

我有范围,我想突出显示基于单元格范围(“C5”)输入值的单元格范围。如果我在单元格“C5”中输入5,则我的范围内的5个单元格需要更改为黄色。 enter image description here

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

有人可以帮忙..

2 个答案:

答案 0 :(得分:0)

你需要引入一个计数器并计算:

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

这个想法是,每次代码循环时,计数器都会增加1,因此cnt = cnt + 1。如果它完全循环N Range("C2")次,则退出。

答案 1 :(得分:0)

您可以使用Areas()对象的Range()属性:

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

注意:在MY_RANGE范围内,有两个" H10"出现