Can I use a variable contain the name of a sub or function to call it?

G

Guest

I would like to be able to decide at run time which of several subs to
call and, when writing the code, it may be impossible to even know the name
of the sub.

That is, I cannot use code like:
if i > 5 then
call This()
else
call That()
endif

because I have no idea what the names of "This" or "That" may be.

I would like to do something equivalent to:
Sub MyCode(SubName as WhateverIsNeeded)
Call SubName
End Sub

Thanks for any help.
 
G

GS

Look at the 'CallByName' function.

Is there some reason why you can't include the module at design time?

In either scenario you cite, you still need to know the name of the
procedure to call so why does it matter how you implement this? We need
more info to better help you...
 
J

joeu2004

I would like to be able to decide at run time
which of several subs to call and, when writing
the code, it may be impossible to even know the
name of the sub.

Take a look at the help page for Application.Run. Be sure the limitations
fit your needs.
 
I

isabelle

hi,

Sub test()
Dim mc As String, nb As Integer
nb = Application.InputBox(prompt:="Choose a number between 1 and 10", Type:=1)
If nb > 5 Then mc = "This" Else mc = "That"
Call MyCode(mc)
End Sub

Sub MyCode(SubName As String)
Application.Run (SubName)
End Sub

Sub This()
MsgBox "This"
End Sub

Sub That()
MsgBox "That"
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top