pdutt
pdutt

Reputation: 1

how to determine at runtime which function to call in vbscript

The range of input values possible is quite huge in my case. So a select-case methodology will not work. So based on my input say flowers.. doffodil,lily,rose,etc, my function name to call would be flowerdoffodil(), flowerlily(), flowerrose(), etc. Ech of these functions are already defined. Only which one to call will need to be determined at runtime based on my input. Is there a way to do this in vb script? Note: I am a rookie programmer and am using QTP for automation.

Upvotes: 0

Views: 264

Answers (1)

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38775

Use GetRef() as in:

Option Explicit

Function flowerdoffodil()
  flowerdoffodil = "my name is daffodil!"
End Function

Function flowerlily()
  flowerlily = "my name is lily!"
End Function

Function flowerrose()
  flowerrose = "my name is rose!"
End Function

Dim aInp : aInp = Split("doffodil lily rose")
Dim sFnc
For Each sFnc In aInp
    Dim fncX : Set fncX = GetRef("flower" & sFnc)
    Dim sRes : sRes = fncX()
    WScript.Echo sFnc, TypeName(fncX), sRes
Next

output:

cscript 30161364.vbs
doffodil Object my name is daffodil!
lily Object my name is lily!
rose Object my name is rose!

Further food for thought: You can use a Dictionary:

Dim dicFncs : Set dicFncs = CreateObject("Scripting.Dictionary")
Set dicFncs("doffodil") = GetRef("flowerdoffodil")
Set dicFncs("lily") = GetRef("flowerlily")
Set dicFncs("rose") = GetRef("flowerrose")

and call the function(s) like:

Dim sRes : sRes = dicFncs(sFnc)()

(See also: 1, 2, 3)

Upvotes: 5

Related Questions