【问题标题】:Function to sum cells by color按颜色对单元格求和的功能
【发布时间】:2015-04-30 20:55:27
【问题描述】:

下面我放置了一个函数代码来按颜色对单元格求和。我写了一个 sub 来执行这个函数。

我收到运行时“1004”错误。我不知道是什么部分导致了错误。我看不到问题。

    Function ColorFunction(rColor As Range, rRange As Range, Optional SUM As Boolean)
    Dim rCell As Range
    Dim lCol As Long
    Dim vResult

    lCol = rColor.Interior.ColorIndex

    If SUM = True Then
        For Each rCell In rRange
            If rCell.Interior.ColorIndex = lCol Then
                vResult = WorksheetFunction.SUM(rCell, vResult)
            End If
        Next rCell
    Else
        For Each rCell In rRange
            If rCell.Interior.ColorIndex = lCol Then
                vResult = 1 + vResult
            End If
        Next rCell
    End If

    ColorFunction = vResult
    End Function

    Sub sumbycolor()

    NextRow = Range("B" & Rows.Count).End(xlUp).Row + 9
    Range("B" & NextRow).Select
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 65535
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With

    Dim lr As Long, critRange As String, sumRange As String
    lr = Cells(Rows.Count, "O").End(xlUp).Row
    sumRange = Range("O2:O" & lr).Address

    CellColor = Range("B" & Rows.Count).End(xlUp).Row + 9

    NextRow = Range("C" & Rows.Count).End(xlUp).Row + 9
    Range("C" & NextRow).Select
    ActiveCell.FormulaR1C1 = "=ColorFunction(" & CellColor & "," & sumRange & ",TRUE)"

    End Sub

【问题讨论】:

  • 一方面,您在以下语句中传递整数CellColorActiveCell.FormulaR1C1 = "=ColorFunction(" & CellColor & "," & sumRange & ",TRUE)",其中函数需要一个范围。仔细检查您放入公式以调用函数的数据类型。
  • 啊哈,我也刚刚注意到您正在使用FormulaR1C1,但以“A1”样式表示法传递 sumRange。使用ActiveCell.Formula=...

标签: excel vba background-color


【解决方案1】:

我整理了一个代码 sn-p,其中包含我在 cmets 中提到的对您的问题的更改。为了便于调试,我创建了一个字符串来保存公式。

...
Dim lr As Long, critRange As String, sumRange As String
Dim intCellColorRow As Integer
Dim strCellColorRange As String
Dim strFormula As String

lr = Cells(Rows.Count, "O").End(xlUp).Row
sumRange = Range("O2:O" & lr).Address

intCellColorRow = Range("B" & Rows.Count).End(xlUp).Row + 9
strCellColorRange = Range("B" & intCellColorRow).Address

NextRow = Range("C" & Rows.Count).End(xlUp).Row + 9
Range("C" & NextRow).Select
strFormula = "=ColorFunction(" & strCellColorRange & "," & sumRange & ",TRUE)"
ActiveCell.Formula = strFormula
...

【讨论】:

  • 感谢您的帮助!
猜你喜欢
  • 2023-02-03
  • 1970-01-01
  • 2013-05-04
  • 1970-01-01
  • 2013-07-01
  • 2018-04-24
  • 1970-01-01
  • 1970-01-01
  • 2020-07-02
相关资源
最近更新 更多