如何在VBA中将字符串作为命令运行 [英] How to run a string as a command in VBA

查看:757
本文介绍了如何在VBA中将字符串作为命令运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面有这个简单的VBA代码,我不知道为什么不起作用。

I have this simple VBA code below, and I don't know why is not working.

Sub Run()
    test = "MsgBox" & """" & "Job Done!" & """"
    Application.Run test     
End Sub

我想要什么要做的就是将VBA命令作为文本放入变量中,然后作为命令运行。在这种情况下,我想像 MsgBox Job Done! 一样运行并打印:

What I want to do is to put the VBA Command into a variable as text and run it as a command. In this case, I want to run like MsgBox "Job Done!" and print just:


工作完成!

Job Done!


推荐答案

您可能会喜欢添加自己的字符串执行者:

You may be tempted by adding your own string "Executer":

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

Sub Testing()
    StringExecute "MsgBox" & """" & "Job Done!" & """"
End Sub

这篇关于如何在VBA中将字符串作为命令运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆