是否可以执行在特定 excel 单元格中编写的代码?
例如:在 Range("A1")
我有 text -> debug.print("Test")
.我需要一些方法来从 VBA 代码中执行它。
可能吗?
最佳答案
首先,使用this answer以确保以编程方式访问 VBA 模型。然后,使用 this method这为位于工作表单元格中的简单命令创建了一个字符串解析器。这应该足以让你继续前进。
演示:
Option Explicit
Sub test()
Dim strCode As String
strCode = Sheet1.Range("A1").Text
StringExecute strCode
End Sub
Sub StringExecute(s As String)
' Credits to A.S.H., see https://stackoverflow.com/questions/43216390/how-to-run-a-string-as-a-command-in-vba
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
关于excel - VBA 执行存储在单元格中的代码 - 有可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46071620/