【发布时间】: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
【问题讨论】:
-
一方面,您在以下语句中传递整数
CellColor:ActiveCell.FormulaR1C1 = "=ColorFunction(" & CellColor & "," & sumRange & ",TRUE)",其中函数需要一个范围。仔细检查您放入公式以调用函数的数据类型。 -
啊哈,我也刚刚注意到您正在使用
FormulaR1C1,但以“A1”样式表示法传递 sumRange。使用ActiveCell.Formula=...。
标签: excel vba background-color