【发布时间】:2020-05-13 18:43:48
【问题描述】:
我正在尝试编写一个函数来计算由于条件格式而被着色的单元格。 UDF 不能使用 DisplayFormat 属性,所以 Tim Williams 在下面写了这个绝妙的解决方案。当我最初将函数输入到单元格时,它工作得很好。但是,当我更改它指向的其中一个单元格中的值时,该函数会报告 0。然后我必须重新输入该函数以使其正确回答。
有人知道为什么会这样吗?以及如何解决?
Function DFColor(addr As String)
DFColor = Range(addr).DisplayFormat.Interior.color
End Function
Function CountColoredCells(rng As Range) As Long
Dim count As Long, color As Long, cell As Range
count = 0
For Each cell In rng.Cells
color = rng.Parent.Evaluate("DFColor(""" & cell.Address() & """)")
If color <> 16777215 Then '16777215 is the blank color value
count = count + 1
End If
Next cell
CountColoredCells = count
End Function
这是他的解决方案帖子的链接 - https://stackoverflow.com/a/54757688/7053791
【问题讨论】:
-
最好根据Conditional Format规则的逻辑实际计数,而不是这种方法。
-
^ 这是要走的路。当您可以直接使用逻辑时,您只是使用条件格式作为中间人。即在 VBA 中重新创建条件格式逻辑。刚刚意识到我对你原来的问题留下了同样的评论哈
-
这种方法在大多数情况下可能会更好,但对我来说不是。在我的特殊情况下,拥有一个函数是最好的方法,我需要为我的工作表的用户界面设置条件格式。你知道我在 19 列中有 23 种不同的条件格式规则。我不会在 VBA 中编写该 逻辑。它已经在 ocnditional 格式中进行了说明。上面的方法效果很好。我只需要它在单元格更改时自动更新。这就是我的问题的目标。
标签: vba user-defined-functions conditional-formatting