2

I'm using VBScript and I am wondering if is there any way to call a function name stored in string variable?

Here is my attempt?

a = "b"

sub b() 
    msgbox "c"
end sub

a()

But it always result in an error

Type mismatch 'a'

Teiv
  • 2,605
  • 10
  • 39
  • 48

3 Answers3

17

The correct answer is: Use GetRef() as in:

Function F(p)
  F = p + p
End Function

Dim FP : Set FP = GetRef("F")

WScript.Echo FP("a")
WScript.Echo FP(123)

Output:

aa
246
Ekkehard.Horner
  • 38,498
  • 2
  • 45
  • 96
  • This is a better answer and should be the accepted one. This method also works in ASP Classic. – Jagu Mar 09 '22 at 05:10
4

Seems like e.g. this should work:

Dim a
a = "Call b()"
Eval(a)

Sub b
   ' Do stuff
End Sub
KevinH
  • 2,034
  • 1
  • 12
  • 12
  • 6
    @user433531 Please look at the answer of Ekkehard.Horner, `GetRef` is the right (and secure!) way to do it. `Eval` is not secure, uses global scope, is slow and you cannot easily pass arguments in your function. And a function pointer created by GetRef can be passed around as an object, which is a huge pro. – AutomatedChaos Oct 30 '12 at 06:34
-3
Dim x

Sub b

 print "xxx"' Do stuff
End Sub

x = "call b()"

Execute(eval("x"))
Sport
  • 8,570
  • 6
  • 46
  • 65
morten
  • 1