【问题标题】:VBA conditional formatting cells with value that are greater than or less than值大于或小于的 VBA 条件格式单元格
【发布时间】:2024-01-24 10:35:01
【问题描述】:

我正在尝试编写一个宏代码,它将对一系列单元格执行以下操作

  1. 条件格式仅适用于单元格已输入值的情况
  2. 如果单元格中的值小于 $I$6 和/或大于 $M$6 ,则突出显示红色,如果不是,则不突出显示(或不应用)。

这用于对输入的数据进行规格检查,以确保数字在规格范围内。谢谢!

我尝试了什么:

Sub SpecCheck()
    Dim iRow As Range
    Set iRow = Range("f16:l34")

    For Each cell In iRow
        If cell.Value <> "" And cell.Value > "I6" And cell.Value < "M6" Then
            cell.Interior.Color = RGB(255, 0, 0)
        End If
    Next
End Sub

我尝试了新代码,但没有成功。也不确定是否重要,但代码是用工作表的“通用”代码编写的。

Sub SpecCheck()

Dim iRow As Range, cell As Range 
Dim lowSpec As Range
Dim highSpec As Range
Set iRow = Range("f16:l34")
Set lowSpec = Range("r6")
Set highSpec = Range("s6")

For Each cell In iRow
 If cell.Value <> "" And cell.Value > highSpec And cell.Value < lowSpec Then
    cell.Interior.Color = RGB(255, 0, 0)
 End If
Next

End Sub

【问题讨论】:

  • I'm trying to write a macro code...好吧,那它怎么了...?所以不是 "Write code for me site"。向我们展示您到目前为止尝试了什么以及您遇到的问题。
  • Sub SpecCheck() Dim iRow As Range Set iRow = Range("f16:l34") For Each cell In iRow If cell.Value "" And cell.Value > "I6" And cell .Value

标签: vba excel conditional-formatting


【解决方案1】:

您需要指定这些是范围,而不是字符串:

Sub SpecCheck()
Dim iRow As Range, cell as Range ' I also added the cell as Range
Set iRow = Range("f16:l34")

For Each cell In iRow
    If cell.Value <> "" And cell.Value > Range("$I$6").Value And cell.Value < Range("$M$6").Value Then
        cell.Interior.Color = RGB(255, 0, 0)
    End If
Next
End Sub

【讨论】:

  • 合并单元格会影响代码吗?我的两个范围在一个合并的单元格中......
  • @Sid.T. - 是的,它会。你能发布一个快速截图吗?您必须取消合并,并确保两个单元格都有数据。通常最好避免合并单元格,只需使用格式使它们看起来合并,IMO。你能澄清一下吗? $I$6 类似于 Value is 123,您只需要检查 123?
  • 只是为了检查它是否是合并的单元格,我将单元格范围更改为 r6 和 s6。我要检查的值是否低于 299 和高于 311.Private Sub SpecCheck() Dim iRow As Range, cell As Range ' 我还将单元格添加为 Range Dim lowSpec As Range Dim highSpec As Range Set iRow = Range ("f16:l34") Set lowSpec = Range("r6") Set highSpec = Range("s6") For Each cell In iRow If cell.Value "" And cell.Value > highSpec And cell.Value
  • @Sid.T. - 你能把它发布到你的 OP 中,并格式化为代码吗?这里很难读。