Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Passing a reference to a function 1

Status
Not open for further replies.

Algernon83

Programmer
Jun 25, 2004
50
US
In a program I'm writing, it would be useful to be able to pass in a function as an argument to another function, so a portion of the receiving function's behavior is determined by this argument. Is this possible in VBA? If so, how?
 
Very easy. Here is a sample:
[tt]
Sub TestNestedFunctions()
MsgBox Multiplyer(3, Adder2(5, 6))
End Sub

Function Multiplyer(A As Integer, B As Integer) As Integer
Multiplyer = A * B
End Function

Function Adder2(A As Integer, B As Integer) As Integer
Adder2 = A + B
End Function
[/tt]
 
That's not quite what I meant. What I need to do is to have a function receive another as an argument, rather than calling one that's hard-coded. This would be more akin to:

Sub TestNestedFunctions(a as Function)
MsgBox a(3, 4)
End Sub

Function Multiplyer(A As Integer, B As Integer) As Integer
Multiplyer = A * B
End Function

call TestNestedFunctions(Multiplyer)
 
Ok, try this:
[tt]
Option Explicit

Sub test()
MsgBox "Multiply then Add 3 and 4:" & vbNewLine _
& "Mult: " & AnyFunction("Multiplyer", 3, 4) & vbNewLine _
& "Add.: " & AnyFunction("Adder", 3, 4)
End Sub

Function AnyFunction(f As String, A As Integer, B As Integer) As Integer
AnyFunction = Evaluate(f & "(" & A & "," & B & ")")
End Function

Function Multiplyer(A As Integer, B As Integer) As Integer
Multiplyer = A * B
End Function

Function Adder(A As Integer, B As Integer) As Integer
Adder = A + B
End Function
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top