简体   繁体   English

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

[英]EXCEL VBA - Subtracting By Cell Color - Basic Subtraction Formula

Here is my VBA 这是我的VBA

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

The color of the grey cells I am using is, -4142 I found this by =CellColour(5,11) 我正在使用的灰色单元格的颜色是-4142,我通过=CellColour(5,11)

I currently have Two rows that contain monthly Sales data, Once the month ends I manually color the row gray, ""-4142" 我目前有两行包含每月的销售数据,当月结束时,我将行手动涂成灰色,“-4142”

I have a section for totals D6 which is a sum of a few cells D6 = Sum(D9:D12) 我有一个总计D6的部分,它是几个单元格的总和D6 = Sum(D9:D12)

What I want to accomplish is inside the D6 cell... subtract this gray number. 我要完成的操作是在D6单元内...减去此灰色数字。

Cell D6 Formula: Sum(D9:D12)-If(Cellcolour *IN ROWS F11:Q12* = *GRAY "-4142) 单元格D6公式: Sum(D9:D12)-If(Cellcolour *IN ROWS F11:Q12* = *GRAY "-4142)

End result SUM D9:D12 MINUS WHATEVER NUMBERS ARE GRAY FROM ROWS F11:Q12 最终结果SUM D9:D12减去行F11:Q12灰色数字

I think my problem lies within my inability to create the proper formula. 我认为我的问题在于无法创建正确的公式。

I feel like just doing conditional formatting might be easier? 我觉得仅执行条件格式可能会更容易?

Any help would be awesome. 任何帮助都是极好的。

Thanks! 谢谢!

Using a cell color to encode information is not a great approach: you'd be much better off with a "Status" column (which could then drive conditional formatting to add the color, but also can be more-easily used in other formulas) 使用单元格颜色对信息进行编码不是一个好方法:使用“状态”列会更好(它可以驱动条件格式来添加颜色,但也可以更轻松地用在其他公式中)

That aside, your function has a problem: 除此之外,您的函数还有一个问题:

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

...here the Cells() will always apply to the ActiveSheet, which may or may not be the one you expect/want. ...在这里, Cells()将始终应用于ActiveSheet,它可能是您期望/想要的那个,也可能不是。

This might explain why your "grey" cells give -4142, which is actually the code for "no fill" (xlNone) 这可能可以解释为什么您的“灰色”单元格给出-4142,这实际上是“不填充”(xlNone)的代码

This is more explicit in referencing the correct sheet, because you're using a Range parameter in place of numeric arguments: 这在引用正确的工作表时更加明确,因为您使用了Range参数代替数字参数:

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

EDIT: This might be more what you need: 编辑:这可能是您需要的更多:

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

Then you can do something like: 然后,您可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM