PDA

View Full Version : Solved: A function as a variable? Pass function as parameter? function pointer?



MattKlein
05-15-2008, 04:12 PM
I come from a C programming background and am not very familar with VB. I was wondering, in VBA is there such a thing as a "function pointer" or a variable type that is ment to hold function names that I can pass as arguments?

Thanks!

-Matt

mikerickson
05-15-2008, 04:22 PM
This syntax should work for you.

Sub test()
Dim ftnName As String
Dim argument As String
Dim result As String

ftnName = "myFunction"
argument = "cat"

result = Application.Run(ftnName, argument)

MsgBox result
End Sub

Function myFunction(inString As String) As String
myFunction = inString & " has " & Len(inString) & " letters."
End FunctionNote that when useing Run to call a function, the names of the arguments can't be used.
In VBA, both function and sub's are refered to with string variables of their names. The OnKey, OnAction and OnTime use the sub's name (as a string) as their arguments.

MattKlein
05-21-2008, 02:02 PM
Thanks Mikerickson! I think I can make this work for what I'm looking for!

Paul_Hossler
05-21-2008, 04:26 PM
Note that when using Run to call a function, the names of the arguments can't be used.


Don't understand what you mean. In 2003 this works


Sub Test()
Dim F As String

F = "test1"
MsgBox Application.Run(F, "Passing as string", 1234)

F = "test2"
MsgBox Application.Run(F, "Passing another string", 4321)
End Sub

Function Test1(X As String, Y As Long) As String
Test1 = X & " -- " & Y
End Function

Function Test2(X As String, Y As Long) As String
Test2 = X & " -- " & Y
End Function


Paul

mikerickson
05-21-2008, 06:31 PM
Consider the UDF:

Function myFtn(firstVal As Double, secondVal As Double) As Double
myFtn = firstVal + (2 * secondVal)
End Function

This syntax (which returns 21) has no equivalent using Run.

myFtn(secondVal:=10, firstVal:=1)

Paul_Hossler
05-22-2008, 08:38 AM
Gotcha -- but since this works



Sub mySub()
MsgBox Application.Run("myFtn", 1, 10)
End Sub


and involves less typing, I can handle it

Paul