Compile string as code

Asked

Viewed 38 times

0

I have a string in Vbscript that I need to run as code, as I would do?

I read some articles about Eval and Execute Statement but I did not find a clear explanation or did not understand correctly...

for example:

Dim str

str = "Msgbox "Hello world""

How to compile this string as code?

Thank you for your attention.

  • The fact is that Vbscript is an interpreted, uncompilled language. See if this helps you: https://www.w3schools.com/asp/func_eval.asp

2 answers

2

If you want to execute an instruction that does not return a value, use Execute, example:

Option Explicit

Dim mensagem
Dim codigo

mensagem = "Oi!!!"
codigo = "MsgBox mensagem"

Execute codigo

If your code returns a value, use the Eval, example:

Option Explicit

Dim numero
Dim codigo
Dim resultado

numero = 7
codigo = "numero * 4"
resultado = Eval(codigo)

MsgBox resultado

0

The problem is that to quote inside quotes it is necessary to escape them first, ie this will not work because it will cause syntax error:

Dim str

str = "MsgBox "Olá mundo""

Execute(str)

In VB it is necessary to pass a quote in front of each Asp you want to escape, so:

Dim str

str = "MsgBox ""Olá mundo"""

Execute(str)

Note that to apply the quotes inside the string it was necessary to transform this:

"Olá mundo"

In:

""Olá mundo""

This way the quotes escape.


The use of Execute Gabriel already showed in one. vbs seems to work normally, in office "macros" I do not know how it behaves, however as an alternative has this suggestion of Soen: https://stackoverflow.com/a/43217874/1518921 (an example in Excel)

Sub StringExecute(strToExecute As String)
    Dim vbComp As Object
    Set vbComp = ThisWorkbook.VBProject.VBComponents.Add(1)
    vbComp.CodeModule.AddFromString "Sub foo()" & vbCrLf & strToExecute & vbCrLf & "End Sub"
    Application.Run vbComp.name & ".foo"
    ThisWorkbook.VBProject.VBComponents.Remove vbComp
End Sub

Sub Testing()
    StringExecute "MsgBox ""Olá mundo"""
End Sub

Browser other questions tagged

You are not signed in. Login or sign up in order to post.