计算变量范围vba

时间:2016-07-21 19:45:16

标签: excel vba

我正在尝试使用countif公式在VBA中实现条件格式。它确实有效,但我想实现一个可变范围。我试过以下没有成功

 With Range("AI7").FormatConditions _
        .Add(xlExpression, Formula1:="=AND(COUNTIF($C$7:$AG$7;""B"")<=3;COUNTIF($C$7:$AG$7;""R"")<=5)")
        .Interior.Color = RGB(185, 207, 203)
  End With

如何使范围内的范围动态。我试过了:

With Range("AI7").FormatConditions _
        .Add(xlExpression, Formula1:="=COUNTIF(R[7]C[3], R[7]C[31])="B"")
        .Interior.Color = RGB(248, 194, 203)
    End With

1 个答案:

答案 0 :(得分:1)

这是一种方法。您必须以您需要的方式动态获取列字母,但您可以将其放入下面的sCol变量中。

Dim sCol as String

 sCol = "AG" 'you'll have to define the column in whatever way you need

 With Range("AI7").FormatConditions _
        .Add(xlExpression, Formula1:="=AND(COUNTIF($C$7:$" & sCol & "$7;""B"")<=3;COUNTIF($C$7:$" & sCol & "$7;""R"")<=5)")
        .Interior.Color = RGB(185, 207, 203)
  End With