简体   繁体   English

VBA-在Excel中将字符串作为命令执行

[英]VBA - Execute string as command in Excel

In the last 30 minutes I am trying to execute a string in VBA as a command. 在过去的30分钟中,我试图在VBA中作为命令执行字符串。 The command is like this and it runs ok: 该命令是这样的,它可以正常运行:

activesheet.chb_g_ba1.visible = true

What I am trying to do is to set "chb_g_ba1" as a variable, because there are "chb_g_ba2", "chb_g_ba3", etc as well. 我试图做的是将“ chb_g_ba1”设置为变量,因为也有“ chb_g_ba2”,“ chb_g_ba3”等。

What I have tried so far - things like: 到目前为止,我已经尝试过-像:

dim l_counter as long: l_counter = 1
Evaluate (CStr("me.chb_g_ba" & l_counter & ".visible = true"))

Or even Eval 甚至评估

Eval (CStr("me.chb_g_ba" & l_counter & ".visible = true"))

Eval is a function in MS Access VBA, but obviously it is not present in Excel. Eval是MS Access VBA中的功能,但显然在Excel中不存在。 Pretty much my question is extremely similar to this one: VBA how to run a string as a line of code , but it is for Excel, not for Access. 我的问题几乎与此非常相似: VBA如何将字符串作为代码行运行 ,但这是针对Excel而不是Access。

So, any ideas are welcomed! 因此,欢迎任何想法! :) :)

Credit to CPearson : 归功于CPearson

There is a way to do that but we have to add a new module dynamically with required code and delete while finished. 有一种方法可以做到,但是我们必须用所需的代码动态添加一个新模块,并在完成后删除它。

References: Microsoft Visual Basic for Applications Extensibility 5.3 参考:Microsoft Visual Basic应用程序可扩展性5.3

Sub test()
    Set VBComp = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_StdModule)
    VBComp.Name = "NewModule"
    Set VBCodeMod = ThisWorkbook.VBProject.VBComponents("NewModule").CodeModule
    Dim l_counter As Long
    l_counter = 1
    With VBCodeMod
        LineNum = .CountOfLines + 1
        .InsertLines LineNum, _
        "Sub MyNewProcedure()" & Chr(13) & "UserForm1.chb_g_ba" & l_counter & ".Visible = True" & Chr(13) & "End Sub"
    End With
    'run the new module
    Application.Run "MyNewProcedure"
    UserForm1.Show
    'Delete the created module
    ThisWorkbook.VBProject.VBComponents.Remove VBComp
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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