DIAdem

cancel
Showing results for 
Search instead for 
Did you mean: 

Execute sub inside another sub using a variable instead of subname?

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

0 Kudos
Message 1 of 4
(4,838 Views)

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?  
0 Kudos
Message 2 of 4
(4,834 Views)

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

0 Kudos
Message 3 of 4
(4,804 Views)

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

0 Kudos
Message 4 of 4
(4,772 Views)