更改与特定单元格相同的单元格的颜色

时间:2020-03-23 09:59:42

标签: excel vba

我需要遍历一个范围并找到等于单元格C3中元素的值。然后,我需要更改它们的颜色。我有这段代码,只生成此范围内的随机值。我需要进行哪些更改才能使其正常工作?

Public Sub Random()

    With Range("A2:C24")
        .Formula = "=RANDBETWEEN(5,50)"
        .Value = .Value
    End With

End Sub

1 个答案:

答案 0 :(得分:0)

随机范围条件格式化

  • 根据需要更改常量部分中的值。

Option Explicit

Sub Random()
    Const strRange As String = "A2:C24"   ' Target Range Address
    Const strCrit As String = "C3"        ' Criteria Cell Address
    Const strFormula As String = "=RANDBETWEEN(5,20)"   ' Formula
    Const lngColor As Long = 6            ' ColorIndex (e.g. 6 - Yellow)

    Dim Cell As Variant   ' Current Cell (For Each Control Variable)
    Dim lngCrit As Long   ' Criteria Value

    ' In Target Range ...
    With Range(strRange)
        ' ... "apply" formula.
        .Formula = strFormula
        ' ... "replace" formula with values.
        .Value = .Value
        ' ... "clear" previous colors.
        .Interior.ColorIndex = 0
    End With

    ' Assign value of Criteria Cell to Criteria Value.
    lngCrit = Range(strCrit).Value

    ' Loop through cells of Target Range.
    For Each Cell In Range(strRange)
        ' Check if value of Current Cell is equal to Criteria Value.
        If Cell.Value = lngCrit Then
            ' Change color of Current Cell.
            Cell.Interior.ColorIndex = lngColor
        End If
    Next

End Sub
相关问题