嘿伙计我需要一些帮助。下面我放置了一个函数代码按颜色对单元格求和,然后我写了一个子函数来执行该函数。我一直收到运行时“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
答案 0 :(得分:1)
我已经整理了一个代码段,其中包含了我在评论中提到的更改。我创建了一个字符串来保存公式,以便于调试。
...
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
...