Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional ranges in vba function

Tags:

excel

vba

I am trying to return the columns count on a range, sometimes I need one range, but, sometimes I need more than one range.

I have put in optional ranges so I can choose multiple ranges. If I reference a range in the function prototype that I have not supplied in the spreadsheet I get the #Value! error.

I need a way to check if the optional ranges are null, void empty etc. so I don't have to reference the range.

This is the VBA Function Prototype:-

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

In my spreadsheet I have to enter this in a cell for the function to work.
=GetColoumnCount(BC34:BK34, BC35:BD35, BE35:BF35, BG35:BH35)
this defeats the purpose of having optional arguments.

like image 770
GrooverMD Avatar asked Jul 19 '12 02:07

GrooverMD


1 Answers

Try it like this

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
like image 174
RBarryYoung Avatar answered Sep 26 '22 08:09

RBarryYoung