【问题标题】:Excel Formula with VBA使用 VBA 的 Excel 公式
【发布时间】:2015-07-23 21:35:56
【问题描述】:

需要公式将一列中的文本与不同工作表中的文本匹配并计算突出显示的单元格。这类似于执行 sumif,但不是在静态列中返回数值,而是返回突出显示的单元格的计数。

我已成功编写 VBA 来计算给定列中突出显示的单元格,但现在必须匹配名称。意思是,如果 A1:A50 列中的名称与 Sheet2 列 J1:J52 中的名称匹配,则返回工作表 2 X 列中突出显示的单元格的计数。

计算高亮单元格的公式:countbycolor('sheet2'!J4:J1847,A52)

VBA:

Function CountByColor(InputRange As Range, ColorRange As Range) As Long
    Dim cl As Range, TmpCount As Long, ColorIndex As Integer
    Application.Volatile
    ColorIndex = ColorRange.Interior.ColorIndex
    TmpCount = 0
    On Error Resume Next
    For Each cl In InputRange.Cells
    If cl.Interior.ColorIndex = ColorIndex _
        Then TmpCount = TmpCount + 1
    Next cl
    CountByColor = TmpCount
End Function

【问题讨论】:

  • A1:A50 包含 50 个单元格,以检查包含 52 个单元格的 J1:J52。您是要查看 A1 中的文本是否包含在 J1:J52 中的任何位置,还是要检查 A1 文本是否等于 J1 文本?
  • 如果存在,则返回计数。
  • 两者混合,只是因为除了使用 VBA 之外,我想不出任何其他方法来计算彩色单元格。如果有办法做我需要的事情(匹配名称并计算彩色单元格)而不使用 VBA,那么我一定会试一试。
  • 老实说,我没有尝试将Namesbackcolor 一起使用,但仅与font color 一起使用,如图所示Here 如果您愿意,您可以尝试将其与This 和看看有没有效果?

标签: vba excel


【解决方案1】:

为条件范围添加一个参数并实现Application.Countif 应该就足够了。

Function CountByColorAndName(InputRange As Range, NameRange As Range, ColorRange As Range) As Long
    Dim cl As Range, TmpCount As Long, ColorIndex As Integer
    Application.Volatile
    ColorIndex = ColorRange.Interior.ColorIndex
    TmpCount = 0
    On Error Resume Next
    For Each cl In InputRange.Cells
        If cl.Interior.ColorIndex = ColorIndex and _
          cbool(application.countif(NameRange , cl.value)) then _
            TmpCount = TmpCount + 1
    Next cl
    CountByColor = TmpCount
End Function

示例语法:

=CountByColorAndName('sheet2'!J4:J1847, A1:A50, A52)

由于您对这种情况的描述涉及 Sheet2 列 J1:J52'sheet2'!J4:J1847,因此有点混乱。如果这不合适,请澄清。

MATCH function 实际上比COUNTIF function 更有效,无论是在工作表上还是在 VBA 中。这应该会减少一些计算负载。

    For Each cl In InputRange.Cells
        If cl.Interior.ColorIndex = ColorIndex then _
          if not iserror(application.match(cl.value, NameRange , 0)) then _
            TmpCount = TmpCount + 1
    Next cl

【讨论】:

  • 谢谢。我将尝试这两种解决方案。您发现我在 J 列的描述错误是正确的; J4:J1847 是正确的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-16
  • 2018-04-12
相关资源
最近更新 更多