01-27-2009 09:02 AM
Hello!
Is it possible to run a sub using a variable for the subname?
I've created a sub and I want to run different subs each time inside of the main sub. Using a ordinary variable for the subname to run inside main sub seems not possible, is there another possibility?
regards
Sven
01-27-2009 10:30 AM
Hello Sven!
Yes you can! There are to nice commands in VBS for this 'Execute' and 'Eval'. I show you a simple example:
Call Caller("MySubA")
Call Caller("MySubB")
Sub Caller(ByRef sgSubName)
Call Execute(sgSubName)
End Sub
Sub MySubA
MsgBox "Hello A!"
End Sub
Sub MySubB
MsgBox "Hello B!"
End Sub
If you want to pass parameters an get a result you have to use 'Eval' like this:
MsgBox Caller("MySubA","Hello ")
MsgBox Caller("MySubB","Hello ")
Function Caller(ByRef sgSubName, ByRef sgParam)
Caller = Eval( sgSubName & "(sgParam)")
End Function
Function MySubA( ByRef sgParam)
MySubA = sgParam & "A!"
End Function
Function MySubB( ByRef sgParam)
MySubB = sgParam & "B!"
End Function
Matthias
Matthias Alleweldt Project Engineer / Projektingenieur | Twigeater? |
01-29-2009 09:41 AM
Hi Sven,
Matthias (Twigeater) gave you an excellent answer to the exact question you asked. I've used the Execute function as he describes in a number of case, and it works just fine, once you have it debugged. The main problem I have with using the Execute function is that any programming errors are very hard to debug. So whenever I can choose a different approach, I try to avoid the Execute function. Please consider the following alternative approach, which may not solve the problem you have at hand, but will solve many needs where you might otherwise be tempted to use the Execute or Eval functions:
Sub Main()
SubToRun = DetermineSubToRun(FileName, SQLdb, or_whatever...)
Select Case SubToRun
Case "ShowDialog" : Call ShowDialog()
Case "RunAnalysis" : Call RunAnalysis()
Case "CreateReport" : Call CreateReport()
End Select ' SubToRun
End Sub ' Main()
This approach will be much easier to debug and maintain,
Brad Turpin
DIAdem Product Support Engineer
Natonal Instruments
02-02-2009 05:18 AM
Hello Matthias, Hello Brad,
thanks a lot for helping out. Currently I'm using Matthias solution, but I'm still working on optimization of my scripts, so I'll consider your comments too, Brad.
It's great today to have a board like this! When I was starting programming in DIAdem in year 2000 (AUT-scripts) it was mutch harder to get solutions!
Regards
Sven