按颜色求和-偏移量Excel VBA
如果一个单元格是某种颜色,我想加上数值,但我想加上的数值是偏移的。例如,如果我正在寻找黄色单元格,A1和A2为黄色,则将B1和B2相加。用户应该能够选择颜色。我已经花了几个小时试图找出如何做到这一点,我是非常新的VBA。任何帮助都将不胜感激按颜色求和-偏移量Excel VBA,excel,vba,sum,offset,Excel,Vba,Sum,Offset,如果一个单元格是某种颜色,我想加上数值,但我想加上的数值是偏移的。例如,如果我正在寻找黄色单元格,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 =
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,-19)?这与B1+B2无关。应该是这样的
total=total+(单元格偏移量(0,1)+单元格偏移量(1,1))
考虑到安排在A:A列中。
也用于过滤:
如果cell.Interior.ColorIndex=ColIndex和cell.offset(1,0).Interior.ColorIndex=ColIndex
由于硬编码的偏移量(),您的函数是不灵活的-您最好通过三个范围:
- 单元格指定要求和的颜色
- 范围以检查中的颜色
- 从中求和相应值的范围
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
这个颜色是由条件格式设置的吗?如果是,您需要
.DisplayFormat.Interior.Color
。您没有提到问题的确切原因。在一个肢体上行走,可能是因为有时单元格偏移量(0,-19)
会导致错误吗?如果是,一个简单的错误检查(Cell.Column>19
)应该可以完成这个任务。如果您做了这么多,您将添加dim检查