我正在尝试编写一个函数来计算由于条件格式而着色的单元格的数量。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
发布于 2020-05-14 04:55:47
此设计中存在错误:
Function DFColor(addr As String)
DFColor = Range(addr).DisplayFormat.Interior.color
End Function
单元格地址作为字符串传递,然后使用Range()
转换为range对象,但是由于Range()
(在常规代码模块中)默认为ActiveSheet,如果具有条件格式的工作表不是ActiveSheet,您将得到错误的结果(因此您看到的是零)。
这是更健壮的-在实际范围内传递并直接使用:
Function DFColor(c As Range)
DFColor = c.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() & ")") '<<EDITED
If color <> 16777215 Then '16777215 is the blank color value
count = count + 1
End If
Next cell
CountColoredCells = count
End Function
我已经在链接的帖子上编辑了版本
https://stackoverflow.com/questions/61782455
复制相似问题