I want to do this: ‘If there’s a module X containing a function Y then call it, otherwise don’t.’
I’m aware that I can use CallByName(Object, MethodName, ...) to call a method or property of an object instance.
Is it possible to call a global sub/function which is not bound to an object?
//Module1 Public Sub DoSomething End Sub //Module2 Public Sub TriggerDoSomething On Error Resume Next CallByName2 'Module1', 'DoSomething', ... End Sub
I know, it would be better to refactor my code to wrap DoSomething into a class, but currently this is not possible as it would break the code of my coworkers in a way that could not be fixed in a few hours.
It really would be easier to CallByName a class – can’t you just wrap the module(s) with a class that redirects the calls to the module?
It’s possible to call routines in modules by name using a FunctionDelegator. This is explained in Matt Curland’s excellent book Advanced Visual Basic 6.
Googling might find you some hacks using CallWindowProc, but Matt Curland says that’s dangerous. Which is pretty much the final word on the matter 🙂
EDIT: RS Conley’s answer doesn’t use a module, use a class that has a instancing property of GlobalMultiUse and you will be able to use CallByName. This will work if your code is in a DLL rather than an EXE. RS Conley suggests in any case it is more flexible to have a minimal EXE with nearly all functionality in a DLL: this may well be true.