Excel VBA 条件格式和函数

Excel VBA Conditional Formatting AND-Function

更新:

我尝试对以下情况使用条件格式:

如果 C 列中的单元格(从 C9 开始)Tabelle3.Range(Tabelle3.Cells(9, 3), Tabelle3.Cells(lastcell, 3))

  1. 不为空Cell <>""
  2. 满足 Tabelle4 单元格 B2 中规定的条件 Tabelle4.Range("B2")

Interior.Color应更改为Cellclr,其Font.Color应更改为Fontclr

开始旧 Post: 我查看了有关条件格式的各种帖子,但找不到任何内容,这非常宝贵地解决了我的问题。

我想将条件格式应用于将不断扩展的 Excel 工作簿。因此,我写了下面的代码:

Sub ConForm()

Dim lastcell As Long
Dim Cellclr As Long
Dim Fontclr As Long

lastcell = Tabelle3.Range("A1048576").End(xlUp).Row
Cellclr = RGB(232, 245, 246)
Fontclr = RGB(26, 155, 167)

Set C = Tabelle3.Range(Tabelle3.Cells(9, 3), Tabelle3.Cells(lastcell, 3))

    With C.FormatConditions.Add( _
            Type:=xlExpression, _
            Formula1:="=AND($C9<>"""";"$C9.Value <= Tabelle4.Range(""B2"").Value)")
        .Interior.Color = Cellclr
        .Font.Color = Fontclr
    End With

End Sub

如果我只使用以下范围和公式:

Range("C9")
Formula1:="=C9<>""""") 

代码适用于单元格 C9。但是,如前所述,应该是这个公式

=AND($C9<>"""";"$C9.Value <= Tabelle4.Range(""B2"").Value

申请范围

Tabelle3.Range(Tabelle3.Cells(9, 3), Tabelle3.Cells(lastcell, 3))

有人知道我在哪里发了 mistake/mistakes 以及如何解决这个问题吗?

您需要正确连接字符串和值。

示例:

MyVariable = "ccc"
result = "aaa" & "bbb" & MyVariable & "AnotherString"
'result is "aaabbbcccAnotherString"

我不确定你尝试了什么,但你的意思可能类似于

Formula1:="=AND($C9<>"""";" & Range("$C9").Value <= Tabelle4.Range("B2").Value & ")")

或者更可能是

Formula1:="=AND($C9<>"""";$C9<=Tabelle4!B2)")

更新:

Formula1:="=AND($C9<>"""";$C9<=" & Tabelle4.Range("B2").Value & ")")

首先,检查格式上的颜色,看看什么是字符串,什么不是 - 公式中间有一个神秘的额外 ",它首先会阻止代码编译.您还曾尝试将 VBA 代码 (Tabelle4.Range("B2").Value) 放入 Excel 公式中,但这行不通。

宏为运行时如果想固定Tabelle4.Range("B2").Value的值,可以改

Formula1:="=AND($C9<>"""";"$C9.Value <= Tabelle4.Range(""B2"").Value)")

Formula1:="=AND($C9<>"""";$C9<=" & Tabelle4.Range("B2").Value & ")")