How can I do to pass a function by parameter, later to be called in VB6? would be something like what I need, can be any of these options:
Private Sub Command1_Click()
Call callMethod(MyPrivateFunction)
Call callMethod(MyPublicFunction)
Call callMethod(MyPrivateSub)
Call callMethod(MyPublicSub)
End Sub
Private Function MyPrivateFunction()
MsgBox "MyPrivateFunction"
End Function
Public Function MyPublicFunction()
MsgBox "MyPublicFunction"
End Function
Private Sub MyPrivateSub()
MsgBox "MyPrivateSub"
End Sub
Public Sub MyPublicSub()
MsgBox "MyPublicSub"
End Sub
Public Function callMethod(ByRef func As Object)
Call func
End Function
IIRC there is an AddressOf
function in VB6 to get function addresses, but you will likely have great difficulty actually using that function address from within VB6.
The SOP way to handle this is with CallByName()
which allows you to, you know, call functions, etc. by their names.
finally, you can also take the high road, by using the standard OO solution to this: Instead of passing the function, write your own class that implements a special interface of your own design MyFunctionInterface
. This interface has only one method FunctionToCall(..)
, which you can implement in different classes to call the different functions that you need. Then you pass an instance of one of these classes to your routine, that receives it as MyFunctonInterface
and calls the FunctionToCall
method on it. Of course that takes a whole lot of minor design changes...
You can't pass a function, but you can pass an object that behaves as a function (called a "functor" sometimes). I use this all the time. If you "functor" class Implements an interface, the call will be type safe. For example:
Abstract class (Interface) IAction.cls:
Option Explicit
Public Sub Create(ByVal vInitArgs As Variant)
End Sub
Public Function exe() As Variant
End Function
Functor that displays a url in the default browser:
Option Explicit
Implements IAction
Dim m_sUrl As String
Public Sub IAction_Create(ByVal vInitArgs As Variant)
m_sUrl = vInitArgs
End Sub
Public Function IAction_exe() As Variant
Call RunUrl(m_sUrl) 'this function is defined elsewhere
Exit Function
You can now create a bunch of these classes, save them in a collection, pass them to any function or method that expects an IAction, etc...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With