如果单元格是某种颜色但我想要添加的值是偏移的,我想添加值。例如,如果我正在寻找黄色细胞和A1& A2是黄色然后是B1和& B2在一起。用户应该能够选择颜色。我花了几个小时试图弄清楚如何做到这一点,我对VBA很新。任何帮助将非常感激。
Function SumByColor(CellColor As Range, rRange As Range)
Dim ColIndex As Integer
Dim total As Long
Dim cell As Range
ColIndex = CellColor.Interior.ColorIndex
For Each cell In rRange
If cell.Interior.ColorIndex = ColIndex Then
total = total + cell.Offset(0, -19).Value 'adds all the values in range with offset of 0,-19
End If
Next cell
SumByColor = total
End Function
答案 0 :(得分:1)
由于硬编码偏移(),您的功能不灵活 - 您最好通过三个范围:
应该在下面的代码中添加一个检查,以确保参数2和3的尺寸相同。
Function SumByColor(CellColor As Range, ColorRange As Range, SumRange As Range)
Dim ColIndex As Long, i As Long
Dim total As Double
ColIndex = CellColor.Interior.ColorIndex
For i = 1 To ColorRange.Cells.Count
If ColorRange.Cells(i).Interior.ColorIndex = ColIndex Then
total = total + SumRange.Cells(i).Value 'adds the values from SumRange
End If
Next cell
SumByColor = total
End Function
答案 1 :(得分:0)
什么是偏移量(0,-19)?这与B1 + B2无关。它应该像
total=total+(cell.offset(0,1)+cell.offset(1,1))
,
鉴于rRange位于A:A列中。 也用于过滤:
If cell.Interior.ColorIndex=ColIndex and cell.offset(1,0).Interior.ColorIndex=ColIndex