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

How to create a cell-sized chart?
Tiny charts, called Sparklines, were added to Excel 2010. Look for Sparklines on the Insert tab.

Richard Schollar

MrExcel MVP
Joined
Apr 19, 2005
Messages
23,707
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
 

biker

New Member
Joined
May 3, 2006
Messages
6
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
 

Forum statistics

Threads
1,141,218
Messages
5,705,080
Members
421,377
Latest member
FerdiFuchs

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
Top