问题描述
由于无法找到以下问题的答案,我在谷歌搜索上可能很糟糕:
Sub TEST()昏暗的sthstring作为字符串sthstring =世界你好"结束子
虽然我们都知道使用msgbox轻松打印"Hello world" ,但是否可以打印出变量名(在本例中为"sthstring" )以及如何?
请不要提供以下答案:
将其他字符串作为字符串someotherstring ="sthstring"
我想找到一种打印变量的名称"的方法,谢谢
阅读评论后,我认为您可能会发现此答案很有用.
VBA不像@Monty Wild所提到的那样支持反射,但是添加对 Microsoft Visual Basic for Applications Extensibility 5.3
的引用可以使您访问VBE对象.然后,您可以在VBA项目中迭代对象模块,并以 String
格式检索模块的整个代码.
考虑以下内容(将其粘贴在新工作簿的 Module1
中)
Sub Main()昏暗的代码作为字符串代码= GetCodeModule("Module1")调试打印代码结束子私有函数GetCodeModule(ByVal codeModuleName As String)As StringDim VBProj作为VBIDE.VBProject昏暗的VBComp作为VBIDE.VBComponent将CodeMod变暗为VBIDE.CodeModule设置VBProj = ThisWorkbook.VBProject设置VBComp = VBProj.VBComponents(codeModuleName)设置CodeMod = VBComp.CodeModuleGetCodeModule = CodeMod.Lines(1,CodeMod.CountOfLines)结束功能
您的 code
变量现在存储了 Module1
中的确切代码,您可以通过打开即时窗口 + .
您可能想编写/使用某种 Find
函数来反汇编String组件以检索变量名称和值,但我不建议您这样做,因为这样做会很棘手./p>
I might be bad at googling as I couldn't find the answer to below question:
Sub TEST()
Dim sthstring as string
sthstring = "Hello World"
end sub
While we all know it's easy to use msgbox to print "Hello world", is it possible to print out the variable's name (which in this case, "sthstring") and how?
EDIT: please do not provide with answer such as:
Dim someotherstring as string
someotherstring = "sthstring"
as I meant to find a way to print the 'name' of the variable, thanks
After reading comments I think you may find this answer useful.
VBA doesn't support reflection just like @Monty Wild has mentioned already but adding references to Microsoft Visual Basic for Applications Extensibility 5.3
grants you the access the VBE object. You can then iterate object modules in your VBA Project and retrieve the entire code for a module in a String
format.
Consider the following (Stick it in a new workbook's Module1
)
Sub Main()
Dim code As String
code = GetCodeModule("Module1")
Debug.Print code
End Sub
Private Function GetCodeModule(ByVal codeModuleName As String) As String
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
Set VBProj = ThisWorkbook.VBProject
Set VBComp = VBProj.VBComponents(codeModuleName)
Set CodeMod = VBComp.CodeModule
GetCodeModule = CodeMod.Lines(1, CodeMod.CountOfLines)
End Function
Your code
variable now stores the exact code that is in your Module1
you can check that by opening the Immediate Window +.
You may want to write/use some sort of a Find
function to disassemble the String components to retrieve variable names and values but I wouldn't recommend doing it as it's can get quite tricky.
这篇关于打印变量名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!