简体   繁体   中英

VBA how to run a string as a line of code

Is there a way to convert a string into an executable line of code?

something like:

Dim Line1 as String
Line1 = "MsgBox (""Hello"")"
Execute Line1

resulting in the pop up box saying Hello.

What I'm doing is pulling lines out of a text file. I can pull lines that are the names of form controls and use them to perform actions on those form controls but I'd like to go one step further and execute lines. I've seen claims that this would work:

Application.Run Line1

or make the variable an array and store it in element 1 eg and use

Application.Run Line1(1)

but it doesn't work for me.

Ok, while writing this I've also been experimenting. I found that

Eval (Line1)

will work when Line1 is a message box, but not when it is something like:

line1 = "DoCmd.OpenForm ""form1"""

Any tips would be appreciated.

Thanks

You can use,

 Eval("DoCmd.OpenForm(""form1"")") 

You have to make sure any functions you include use parentheses. Further reference, http://msdn.microsoft.com/en-us/library/office/aa172212(v=office.11).aspx

Visual Basic is a compiler language, and as such does not support the ability to execute human-readable code while it is running. All code written in VBA must first be compiled BEFORE the program runs the first time. However, SQL is an interpreter language, and can be handed code which it will execute line by line. You can also fetch contents for variables from other sources while the program runs, you just can't build a string while the program is running and then execute it in VBA directly.

It's not exactly what I was asking, I ended up going a slightly different direction, but here's what I ended up doing and it would probably be easily altered to more closely match my question. I actually took lines of text from an external text file and inserted them into a line of code. What I was doing in this example was just hiding columns, the external text file was a list of column names. (figuring out how to output that was fun too)

Open "C:\UserList.txt" For Input As #TextFile
While Not EOF(TextFile)
Line Input #TextFile, TextLine
Screen.ActiveDatasheet.Controls(TextLine).ColumnHidden = True
Wend

You didn't have to go through such extremes... as you are not actually dynamically executing code. The Controls() Property accepts a test string so you could have used any source including a much simpler table, or array.

The same thing could have been accomplished as in your initial example like so:

Dim Line1 as String
Line1 = "Hello"
MsgBox Line1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM