开发者

How can I write a UDF in Excel VBA to filter a range of cells?

I've gotten into the habit of marking outlying data by changing cell styles. I'd like to write a UDF in excel to take a Range of cells as input, and return the subset of that range that is not marked as an outlier.

This is what I have tried:

Function ValidCells(rCells As Range) As Range
    Dim c As Range
    For Each c In rCells
        If c.Style <> "Bad" Then
            Set ValidCells = Ra开发者_JS百科nge(c, ValidCells)
        End If
    Next
End Function

My intent is to be able to do =Sum(ValidCells(A1:D1)), and have it only sum the non-styled data.

However, ValidCells seems to return an empty range every time. What am I doing wrong?


Are you sure it's returning an empty range? When I try running this, VBA raises an error on your 'Set' line. If you're calling the routine as a UDF from the worksheet you won't see the VBA error, but the UDF should stop executing and return #VALUE!.

In any case, you can do what you want, but there is one big caveat. First, the code:

Function ValidCells(rCells As Range) As Range
    Dim valid As Range

    Dim c As Range
    For Each c In rCells
        If c.Style <> "Bad" Then
            If valid Is Nothing Then
                Set valid = c
            Else
                Set valid = Union(valid, c)
            End If
        End If
    Next

    Set ValidCells = valid
End Function

The idea is to build up a multi-area range using VBA's 'Union' method. So, for example, if I put a bad cell in C8, and call ValidCells(B7:D9), this returns the multi-area range $B$7:$D$7,$D$8,$B$8:$B$9,$C$9:$D$9. You can then use the result with SUM just fine.

The caveat is that changing cell styles won't trigger this UDF to recalculate. Normally, you'd be able to add a line like this:

    Call Application.Volatile(True)

to your UDF and it would recalc on every change to the workbook. However, it seems like changing a cell style doesn't qualify as a "change" for volatility purposes. So, you can get what you want out of the UDF, but there appears to be no real way to make it work like a "normal" one as far as recalculation goes, even if you mark it as volatile. You'll have to remain aware of that if you use it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜