views:

44

answers:

2

With SUM for instance, I can do things like:

=SUM(F5:F7,F6:F8,A1,E7:G7,F7,2,7)

Which takes multiple ranges and/or individual cells and it adds them all up. My question is how do I do this with a VBA function, e.g. to generalize a binary XOR:

Function BXOR(A As Integer, B As Integer) As Integer
    BXOR = CLng(A) Xor CLng(B)
End Function

It gets old fast when I have to =BXOR(BXOR(BXOR(w,x),y),z)


Generalized version of Marco's function:

Function BXOR(ParamArray vars() As Variant) As Long
    Dim i,j As Long
    BXOR = 0

    For i = 0 To UBound(vars)
        If Not IsObject(vars(i)) Then
            ' Handle explicitly passed integer arguments, e.g. BXOR(1,[...])
            BXOR = BXOR Xor CLng(vars(i))
        ElseIf IsArray(vars(i).Value2) Then
            ' Handle 1-D ranges of cells, e.g. BXOR(A1:A3,[...])
            For j = 1 To UBound(vars(i).Value2)
                BXOR = BXOR Xor CLng(vars(i)(j).Value2)
            Next j
        Else
            ' Handle individual cells, e.g. BXOR(A1,[...])
            BXOR = BXOR Xor CLng(vars(i).Value2)
        End If
    Next i
End Function
+3  A: 

I think that you are looking for a ParamArray

Your code should look like this:

Function BXor(ParamArray vars() As Variant) as Long
    Dim i As Long
    Dim tmp As Long

    For i = 0 To UBound(vars)
        tmp = tmp Xor clng(vars(i))
    Next

    BXor = tmp
End Function
Marco
Works well for any number (0+) of cells, but is there any way to determine if one of the ParamArray elements is a range (e.g. `A1:A3`) instead of a number and iterate through it?
Nick T
You should use "isObject" function. And if you want to be sure that it is a Excel.Range, you can use "TypeName" function.
Marco
It seems like I needed to handle the arguments three different ways; see question
Nick T
A: 

You can use ParamArray to pass a variable number of arguments. The type has to be Variant.

Function BXOR(ParamArray args() As Variant)
Nick Hebb