【问题标题】:Sum By Colour - Offset Excel VBA按颜色求和 - 偏移 Excel VBA
【发布时间】:2018-02-19 17:30:50
【问题描述】:

如果单元格是某种颜色,但我想加起来的值是偏移的,我想加起来。例如,如果我正在寻找黄色单元格并且 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

【问题讨论】:

  • 这个颜色是通过条件格式设置的吗?如果是,你需要.DisplayFormat.Interior.Color
  • 你没有提到到底是什么问题。手足无措,莫非有时候cell.offset(0,-19)会报错?如果是,一个简单的错误检查 (Cell.Column >19) 应该可以解决问题

标签: excel vba sum offset


【解决方案1】:

由于硬编码的 Offset(),您的函数不灵活 - 您最好通过三个范围:

  • 单元格来指定要求和的颜色
  • 检查颜色的范围
  • 对应值求和的范围

可能应该在下面的代码中添加一个检查,以确保参数 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

【讨论】:

  • 非常感谢,会添加dim check
【解决方案2】:

什么是偏移量(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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-17
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 2015-06-22
    • 2018-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多