Compile string as a code

0

I have a string in VBScript that I need to be executed as a code, how would I do it?

I have 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.

    
asked by anonymous 30.07.2018 / 18:48

2 answers

1

If you want to execute a statement 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 Eval , example:

Option Explicit

Dim numero
Dim codigo
Dim resultado

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

MsgBox resultado
    
30.07.2018 / 19:21
0

The problem is that to pass quotation marks inside quotes is necessary to escape them first, or this will not work because it will cause a syntax error:

Dim str

str = "MsgBox "Olá mundo""

Execute(str)

In VB it is necessary to pass a quotation mark in front of each asp you want to escape, like this:

Dim str

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

Execute(str)

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

"Olá mundo"

In:

""Olá mundo""

This is the escape of the quotes.

The use of Execute Gabriel already showed in a .vbs seems to work normal, in office "macros" I do not know how it behaves, however as an alternative it has this SOen suggestion: link (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
    
30.07.2018 / 20:12