1

Is it possible to execute a function whose definition is stored in a variable in VBScript? For example:

Set fun = "Sub fun" & 
          " MsgBox 1" &
          "End Sub"

the variable fun has the function definition so is it now possible to somehow execute this function using eval or something else?

4
  • If you look up eval in help it will tell you related functions at the bottom. Try it.
    – user6017774
    Commented Dec 2, 2016 at 6:40
  • I think it is Execute statement.
    – sauram1234
    Commented Dec 2, 2016 at 7:18
  • Use Call ExecuteGlobal("sub fun()" & vbCrLf & "msgbox 1" & vbCrLf & "end sub"). That will dynamically create the procedure fun() but you'll still need to call it afterwards.
    – user692942
    Commented Dec 2, 2016 at 8:27
  • 1
    Note that doing this is not good practice and usually a sign of bad design choices. Commented Dec 2, 2016 at 9:56

1 Answer 1

2

It is possible with the use of ExecuteGlobal().

Dim cmd : cmd = "Sub fun()" & vbCrLf & "MsgBox 1" & vbCrLf & "End Sub"
'Call ExecuteGlobal() to add the fun() procedure definition into the global scope.
Call ExecuteGlobal(cmd)
'Call the procedure now it's defined.
Call fun()

Note: Depending on the context used, it would be wise to sanitise any input that is use to build the ExecuteGlobal() statement as it could be possible to inject unwanted code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.