vba函数中的可选范围

时间:2012-07-19 02:24:30

标签: excel excel-vba vba

我试图在一个范围内返回列数,有时我需要一个范围,但是,有时我需要多个范围。

我已经设置了可选范围,因此我可以选择多个范围。如果我在函数原型中引用了一个我没有在电子表格中提供的范围,那么我得到#Value!错误。

我需要一种方法来检查可选范围是否为空,空为空等等。所以我不必参考范围。

这是VBA功能原型: -

Function GetColoumnCount(ARange1 As Range, Optional ARange2 As Range, Optional ARange3 As Range, Optional ARange4 As Range) As Integer

    Dim Result As Integer
    Result = 0

    Result = ARange1.Columns.Count ' This works
    Result = ARange1.Columns.Count + ARange2.Columns.Count ' This doesn't work

    GetColoumnCount = Result    
End Function

在我的电子表格中,我必须在单元格中输入此功能才能使用 =GetColoumnCount(BC34:BK34, BC35:BD35, BE35:BF35, BG35:BH35)
 这违背了可选论证的目的。

2 个答案:

答案 0 :(得分:2)

尝试这样

Function GetColoumnCount(ARange1 As Range, Optional ARange2 As Range, Optional ARange3 As Range, Optional ARange4 As Range) As Long  
    Dim Result As Long
    Result = 0

    Result = ARange1.Columns.Count ' This works
    If Not ARange2 Is Nothing Then
        Result = Result + ARange2.Columns.Count
    End If

    GetColoumnCount = Result    
End Function

答案 1 :(得分:1)

如果在参数中使用ParamArray关键字,则可以提供可变数量的参数。

Public Function GetColumnCount(ParamArray Ranges() As Variant) As Long

    Dim lReturn As Long
    Dim i As Long
    Dim rResult As Range
    Dim rArea As Range

    'Loop through the Ranges array supplied by ParamArray
    For i = LBound(Ranges) To UBound(Ranges)
        'Only work with those array members that are ranges
        If TypeName(Ranges(i)) = "Range" Then
            'Use Union to combine all the ranges
            If rResult Is Nothing Then
                Set rResult = Ranges(i)
            Else
                Set rResult = Application.Union(rResult, Ranges(i))
            End If
        End If
    Next i

    'Loop through the Areas and add up the columns
    If Not rResult Is Nothing Then
        For Each rArea In rResult.Areas
            lReturn = lReturn + rArea.Columns.Count
        Next rArea
    End If

    GetColumnCount = lReturn

End Function

使用:

=getcolumncount(E2:K18) = 7
=getcolumncount(D4:L14,N4:P14) =12 (9+3)
=getcolumncount(C7:F15,H7:L15,K7:N15) =11 (omits double counting overlap)