Any number of input variables.

biker

New Member
Joined
May 3, 2006
Messages
6
I want to make a function “myFunc” that makes some calculations on numbers in different cells. The number of cells are not known and they can be in different sheets. How do I declare the function to make it capable to handle any number of input values?

It is intended to be used from an excel worksheet like =myFunc(A1, D4, G2) or = myFunc(A1, D4, G2, H6, L2) …

How do I declare it?
(this will not do:
Code:
Public Function myFunc(inputCells As Range) As Variant
since the cells can be spread out)

How is the built in SUM function declared? It works with =SUM(A1:A4) as well as =SUM(A1, B5, H6) ?
 

Excel Facts

Pivot Table Drill Down
Double-click any number in a pivot table to create a new report showing all detail rows that make up that number
Hi Biker

You need to use the keyword ParamArray in the arguments list to your functions. An example of a Sum function could be:

Code:
Function Summer(ParamArray rngs()) As Double
Summer = Application.WorksheetFunction.Sum(rngs)
End Function

You can access the individual values in rngs() like you would in anormal array:

rngs(1) acceses the first valuepassed to ParamArray, rngs(2) the second and so on. Only the last argument in the function can be declared as a ParamArray.

Hope this helps!

Richard
 
Upvote 0
I found an answer my self:

Code:
Function myFunc(ParamArray VList() As Variant) As Variant
Dim ArrayItem As Variant
Dim i As Integer


'loop through items.
For Each ArrayItem In VList
   For i = 1 To ArrayItem.cells.Count
         
      'do something useful, ex:
      if ArrayItem.cells(i).Value=...
   Next i
Next ArrayItem

End Function
 
Upvote 0

Forum statistics

Threads
1,214,924
Messages
6,122,294
Members
449,077
Latest member
Rkmenon

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top