繁体   English   中英

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

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

我有范围,我想根据我在单元格Range(“ C5”)中输入的值来突出显示我的单元格范围。 如果我在单元格“ C5”中输入5,则需要将我范围内的5个单元格更改为黄色。 在此处输入图片说明

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

有人可以帮忙吗?

您需要引入一个计数器并计数:

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")次,则退出。

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

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”

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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