I can't seem to find an answer to this question: can I create a user-defined function in Excel VBA that uses an array from some sub-procedure, and then in Excel use that function to return a value?
From this site (http://www.cpearson.com/excel/passingandreturningarrays.htm) I found this example:
Sub AAATest()
Dim StaticArray(1 To 3) As Long
Dim Result As Long
StaticArray(1) = 10
StaticArray(2) = 20
StaticArray(3) = 30
Result = SumArray(Arr:=StaticArray)
Debug.Print Result
End Sub
Function SumArray(Arr() As Long) As Long
'''''''''''''''''''''''''''''''''''''''''''
' SumArray
' This sums the elements of Arr and returns
' the total.
'''''''''''''''''''''''''''''''''''''''''''
Dim N As Long
Dim Total As Long
For N = LBound(Arr) To UBound(Arr)
Total = Total + Arr(N)
Next N
SumArray = Total
End Function
How should I use this function (SumArray) in an Excel cell?
What are the arguments required?
I think I've tried every possible combination of things, but can't seem to get it working. I want the cell with this UDF to return a value (which is Total).
Thanks in advance!
Added more info
Thanks for the answers! However I'll try to rephrase my question from a different angle. What I ultimately want to achieve is a user-defined function which I can use in any Excel cell, for example "=MYOWNFUNCTION(N,M)" which takes two parameters as input: value N and value M. Using these values the function MYOWNFUNCTION finds the closest "combination" of values N and M from a 3D array specified and generated in a separate Sub() and returns the corresponding value from the 3rd row of third axis of the 3D array. The first and the second row of the 3D array are N and M respectively.
So to make my task as simple as possible, I want this to happen?
- Generate a 3D array with dimensions of 100*100*3 in some Subprocedure and fill it with values using functions not relevant to the problem here.
- Generate a function (MYOWNFUNCTION) which uses the data in this previously generated 3D array and finds the closest combination or pair of values N and M, which are user-given inputs.
- I can insert =MYOWNFUNCTION(N,M) with N and M of my choice in an Excel cell and get the corresponding result. By correspondence I mean that for example 3Darray(14,14,1) represents the value of N with parameters (14,14) and 3Darray(14,14,2) represents the value of M with parameters (14,14) and the value of (14,14,3) is the one I want to be returned. The function MYOWNFUNCTION goes through the 3Darray values and finds the nearest match of user-given input values.
The reason why I don't include the creation of the 3D array in the same function is that it's quite large and takes a few seconds to generate. I just want to use the data of the generated 3Darray so I only have to calculate it once.
I hope this makes sense.
