VBA how to run a string as a line of code

前端 未结 4 1213
余生分开走
余生分开走 2020-12-21 01:24

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

something like:

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


        
相关标签:
4条回答
  • 2020-12-21 02:12

    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
    
    0 讨论(0)
  • 2020-12-21 02:26

    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

    0 讨论(0)
  • 2020-12-21 02:26

    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
    
    0 讨论(0)
  • 2020-12-21 02:27

    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.

    0 讨论(0)
提交回复
热议问题