【问题标题】:Excel Conditional Formatting is incorrect when value is entered by VBA Code通过 VBA 代码输入值时 Excel 条件格式不正确
【发布时间】:2022-02-11 22:49:53
【问题描述】:

我遇到了这个问题的一些问号,希望你能帮我解决这个问题。

在 2 列中,我得到了一些格式化为文本的数字,例如“1.234”。从 VBA 代码单击按钮后输入此值。在此之后,第一个单元格还获得了一些条件格式,如果值彼此相等,则显示红色或绿色 BG。

条件格式如下:

With Sheet2.Range(Sheet2.Cells(5, find_column.Column), Sheet2.Cells(intTotalRows, find_column.Column))
    .FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, Formula1:="=RC" & find_column_compare.Column
    .FormatConditions(1).Font.Color = -16752384
    .FormatConditions(1).Interior.Color = 13561798
    .FormatConditions(1).StopIfTrue = True
End With
With Sheet2.Range(Sheet2.Cells(5, find_column.Column), Sheet2.Cells(intTotalRows, find_column.Column))
    .FormatConditions.Add Type:=xlCellValue, Operator:=xlNotEqual, Formula1:="=RC" & find_column_compare.Column
    .FormatConditions(2).Font.Color = -16383844
    .FormatConditions(2).Interior.Color = 13551615
    .FormatConditions(2).StopIfTrue = True
End With

因此,如果数字相同,例如,这将按预期工作。 1.234 这个单元格是绿色的,如果不是红色的话。

如果我将单元格值手动更改为其他任何值,BG 颜色会按预期在红色和绿色之间切换。但是这里的重点是不要手动输入结束号,所以我得到了这行代码进行计算:

Cells(active_cell_row, find_column.Column) = Round(Cells(active_cell_row, Col - 1) / Cells(active_cell_row, Col), 3)

这会在单元格中输入正确的数字,但即使值相同,条件格式也始终为红色。如果我手动覆盖相同的值,条件格式将切换为绿色...

【问题讨论】:

  • 尝试在代码后添加计算,只是一个想法,不知道它是否有效

标签: excel vba conditional-formatting


【解决方案1】:

好吧,没关系,我自己解决了这个问题..

如果有人遇到这个问题:

首先将值声明为字符串...

Dim txt As String: txt = Round(Cells(active_cell_row, Col - 1) / Cells(active_cell_row, Col), 3)
Cells(active_cell_row, find_column.Column) = txt

【讨论】:

  • 不知何故将数字转换为字符串似乎是个坏主意。
  • OT:如果您需要将变量“转换”为另一个变量,请使用type conversion
猜你喜欢
  • 2021-09-01
  • 2012-11-19
  • 2011-10-02
  • 1970-01-01
  • 2018-04-21
  • 2014-03-19
  • 1970-01-01
  • 2016-10-02
  • 2012-04-04
相关资源
最近更新 更多