Excel VBA:返回计算结果的单元格值

时间:2012-08-16 12:37:36

标签: excel vba excel-vba

我有以下VBA功能:

Function IndexOfColor(InRange As Range, ColorIndex As Long) As Excel.Range
Dim R As Range

Application.Volatile True
If IsValidColorIndex(ColorIndex) = False Then
    IndexOfColor = 0
    Exit Function
End If

For Each R In InRange.Cells
    If R.Interior.ColorIndex = ColorIndex Then
        IndexOfColor = R
        Exit Function
    End If
Next R

IndexOfColor = 0
End Function

在我的Excel表格中,我称之为:

=IndexOfColor(D15:M24,37)

始终获得"#VALUE"。我调试了这个函数,直到最后,没有问题。虽然这应该只返回1个结果(我正在查看范围,并且只有一个彩色单元格),我也尝试将其作为数组结果(CTRL-SHIFT-ENTER)。

建议?

1 个答案:

答案 0 :(得分:1)

这是你在尝试什么?如果单元格没有小数,则可以将Variant替换为Long

Function IndexOfColor(InRange As Range, ColorIndex As Long) As Variant
    Dim R As Range

    IndexOfColor = 0

    On Error GoTo Whoa

    Application.Volatile True

    If Not IsValidColorIndex(ColorIndex) = False Then
        For Each R In InRange.Cells
            If R.Interior.ColorIndex = ColorIndex Then
                IndexOfColor = R.Value
                Exit For
            End If
        Next R
    End If
Whoa:
End Function