如何编写一个在Excel VBA中获取范围或参数列表的函数?

时间:2010-08-30 14:20:19

标签: excel excel-vba range vba

例如,SUM可以执行以下操作:

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

它采用多个范围和/或单个单元格,并将它们全部添加。我的问题是如何使用VBA函数执行此操作,例如概括二进制XOR:

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

当我需要=BXOR(BXOR(BXOR(w,x),y),z)

时,它会变得很快

<小时/>

Marco功能的通用版本:

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

2 个答案:

答案 0 :(得分:3)

我认为您正在寻找ParamArray

您的代码应如下所示:

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

答案 1 :(得分:0)

您可以使用ParamArray传递可变数量的参数。类型必须为Variant

Function BXOR(ParamArray args() As Variant)