gpt4 book ai didi

excel - 条件格式空白单元格-VBA

转载 作者:行者123 更新时间:2023-12-04 22:32:03 24 4
gpt4 key购买 nike

如果 B 列中的单元格小于 F 列中的值,我需要突出显示该单元格。例如,如果单元格 B2 为 10 且 F2 为 20,则 B2 应为红色。但是在 B 列中有空白单元格,我不希望这些单元格突出显示。例如,B6 为空白,但 F6 为 10。在我的代码中,B6 也变为红色。

另外,我将如何突出显示已突出显示的同一行中的单元格。例如,如果 B2 突出显示,则突出显示 F2。

我的代码如下:

Sub threecf()
Dim rg As Range
Dim cond1 As FormatCondition, cond2 As FormatCondition
Set rg = Range("B2", Range("B2").End(xlDown))

'clear any existing conditional formatting
rg.FormatConditions.Delete

'define the rule for each conditional format
Set cond1 = rg.FormatConditions.Add(xlCellValue, xlLess, "=f2")
Set cond2 = rg.FormatConditions.Add(xlCellValue, xlEqual, "=isempty(f2)")

'define the format applied for each conditional format
With cond1
.Interior.Color = vbRed
.Font.Color = vbWhite
End With

With cond2
.Interior.Color = vbWhite
.Font.Color = vbWhite
End With

End Sub

最佳答案

正如我的评论中提到的,使用公式。无需使用 VBA

最简单的方式(推荐方式)

我推荐这种方式,因为它考虑了正在添加的新行。

  • 选择 Col B
  • 选择主页选项卡 |条件格式 |新规则 |使用公式确定要格式化的单元格
  • 输入公式=AND(B1<F1,B1<>"")
  • 选择格式 |填写标签
  • 将填充颜色设置为红色 :)

  • 定制方式
  • 手动选择单元格 B2 到 col B 中的最后一行
  • 选择主页选项卡 |条件格式 |新规则 |使用公式确定要格式化的单元格
  • 输入公式=AND(B2<F2,B2<>"")
  • 选择格式 |填写标签
  • 将填充颜色设置为红色 :)

  • VBA方式

    如果你仍然想要 VBA,那么试试这个
    Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long

    '~~> Change as applicable
    Set ws = Sheet1

    With ws
    lRow = .Range("B" & .Rows.Count).End(xlUp).Row

    With .Range("B2:B" & lRow)
    .FormatConditions.Add Type:=xlExpression, Formula1:="=AND(B2<F2,B2<>"""")"
    .FormatConditions(.FormatConditions.Count).SetFirstPriority

    With .FormatConditions(1).Interior
    .PatternColorIndex = xlAutomatic
    .Color = 255
    .TintAndShade = 0
    End With

    .FormatConditions(1).StopIfTrue = False
    End With
    End With
    End Sub

    关于excel - 条件格式空白单元格-VBA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51933594/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com