EXCEL VBA - 按单元格颜色减去 - 基本减法公式

时间:2018-02-19 17:18:59

标签: excel vba excel-vba excel-formula conditional-formatting

这是我的VBA

Function CellColour(Irow As Integer, Icol As Integer) As Long
CellColour = Cells(Irow, Icol).Interior.ColorIndex
End Function

我使用的灰色细胞的颜色是-4142 我是通过=CellColour(5,11)

找到的

我目前有两行包含每月销售数据,一旦月结束,我手动为行灰色,“”-4142“

我有一个总计D6的部分,它是几个单元格的总和 D6 =总和(D9:D12)

我想要完成的是在D6单元格内...减去这个灰色数字。

细胞D6配方: Sum(D9:D12)-If(Cellcolour *IN ROWS F11:Q12* = *GRAY "-4142)

最终结果SUM D9:D12减去任何数字都是灰色的F11:Q12

我认为我的问题在于我无法创造出正确的公式。

我觉得只是做条件格式化可能更容易吗?

任何帮助都会很棒。

谢谢!

1 个答案:

答案 0 :(得分:0)

使用单元格颜色对信息进行编码并不是一个很好的方法:使用" Status"列(然后可以驱动条件格式添加颜色,但也可以更容易地在其他公式中使用)

除此之外,您的功能有问题:

Function CellColour(Irow As Integer, Icol As Integer) As Long
    CellColour = Cells(Irow, Icol).Interior.ColorIndex
End Function

...此处Cells()将始终适用于ActiveSheet,可能是您希望/想要的那个。

这可以解释为什么你的"灰色"单元格给出-4142,这实际上是" no fill" (xlNone)

这在引用正确的工作表时更明确,因为您使用Range参数代替数字参数:

Function CellColour(r As Range) As Long
    CellColour = r.Cells(1).Interior.ColorIndex
End Function

编辑:这可能更符合您的需求:

Function SumByColour(r As Range, indx As Long) As Long
    Dim c As Range, t As Double, v
    Application.Volatile
    For Each c In r.Cells
        v = c.Value
        If IsNumeric(v) And c.Interior.ColorIndex = indx Then
            t = t + v
        End If
    Next c
    SumByColour = t
End Function

然后你可以做类似的事情:

 =SUM(D9:D12)-SumByColour(F11:Q12, 15)