Excel VBA:如何基于颜色过滤范围,然后将结果输出到SUM

时间:2013-07-04 18:19:36

标签: excel excel-vba vba

我有一个函数FILTER_COL,它应该过滤范围为rng的单元格,这些单元格与from_cell中的单元格具有相同的颜色:

Function FILTER_COL(from_cell As String, rng As Range)
Dim colour As Integer
For Each cell In Range(from_cell)
    colour = cell.Interior.ColorIndex
Next cell

Dim Out As Variant
For Each cell In rng
    If cell.Interior.ColorIndex = colour Then
        Out.Add (cell.Value)
    End If
Next cell
FILTER_COL = Out
End Function

然后我将结果放入SUM中,如下所示:

SUM(FILTER_COL("A55",K50:K52))

它给出了一个#VALUE!如果K50:K52范围内的任何单元格与A55具有相同的颜色,则会出错。

1 个答案:

答案 0 :(得分:0)

您必须返回数组或范围对象。范围对象更适合,但如果没有颜色匹配,则无法指定空范围。所以我使用了一系列双打:

Function FILTER_COL(from_cell As String, rng As Range) As Double()
    Dim v() As Double
    ReDim v(rng.Count)
    Dim i As Integer
    i = 0

    Dim colour As Integer
    colour = Range(from_cell).Interior.ColorIndex

    Dim cell As Variant
    For Each cell In rng
        If cell.Interior.ColorIndex = colour And IsNumeric(cell.Value) Then
            v(i) = cell.Value
            i = i + 1
        End If
    Next cell

    FILTER_COL = v
End Function