首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >带颜色的有条件格式的单元格计数

带颜色的有条件格式的单元格计数
EN

Stack Overflow用户
提问于 2020-05-14 02:43:49
回答 1查看 76关注 0票数 0

我正在尝试编写一个函数来计算由于条件格式而着色的单元格的数量。UDF不能使用DisplayFormat属性,所以Tim Williams在下面写了这个很棒的解决方案。当我将函数初始输入到单元格中时,它工作得很好。但是,当我更改它所指向的某个单元格中的值时,函数会报告0。然后,我必须重新输入函数以使其正确回答。

有人知道为什么会这样吗?以及如何修复它?

代码语言:javascript
运行
复制
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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-05-14 04:55:47

此设计中存在错误:

代码语言:javascript
运行
复制
Function DFColor(addr As String)
    DFColor = Range(addr).DisplayFormat.Interior.color
End Function

单元格地址作为字符串传递,然后使用Range()转换为range对象,但是由于Range() (在常规代码模块中)默认为ActiveSheet,如果具有条件格式的工作表不是ActiveSheet,您将得到错误的结果(因此您看到的是零)。

这是更健壮的-在实际范围内传递并直接使用:

代码语言:javascript
运行
复制
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

我已经在链接的帖子上编辑了版本

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61782455

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档