Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

VBA Function That Works with Range and Array

$
0
0

I am trying to write a UDF that takes either a range or an array from the user and iterates over it. If I declare it as a range like so:

Function Test(param As Range) As Variant    Dim total As Integer    Dim cell As Range    total = 0    For Each cell In param        total = total + cell.Value2    Next    Test = totalEnd Function

it works fine when called like =TEST(C22:C24) but gives an error when called like =TEST({1,2,3,4}). On the other hand if I declare it as a variant like so:

Function Test(param As Variant) As Variant    Dim i As Integer, total As Integer    total = 0    On Error GoTo endfunc    For i = 1 To 100        total = total + param(i)    Nextendfunc:    Test = totalEnd Function

it works fine when called like =TEST({1,2,3,4}) but when called like =TEST(C22:C24) it keeps on going way past the end of the range I give it (which is why I gave it the upper bound of 100). I can't use UBound on the variant to get the upper bound, it gives an error. Is there any way to get one function to work in both situations?


Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>