打印一个variables的名字
我可能会在使用googlesearch不好,因为我找不到下面的问题的答案:
Sub TEST() Dim sthstring as string sthstring = "Hello World" end sub
虽然我们都知道使用msgbox打印“Hello world”很容易,但是可以打印出variables的名称(在这种情况下, “sthstring” )以及如何?
编辑:请不要提供如下答案:
Dim someotherstring as string someotherstring = "sthstring"
因为我打算find一种方法来打印variables的“名称”,谢谢
阅读评论后,我认为你可能会觉得这个答案有用。
VBA不像@Monty Wild已经提到的那样支持reflection,但是添加对Microsoft Visual Basic for Applications Extensibility 5.3
引用可以让你访问VBE对象。 然后,您可以在VBA项目中迭代对象模块,并以String
格式检索模块的整个代码。
考虑以下内容(将其粘贴在新的工作簿的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
您的code
variables现在存储在Module1
的确切代码,您可以通过打开即时窗口ctrl + g来检查该代码。
你可能想编写/使用某种Find
function来反汇编string组件来检索variables名称和值,但我不会build议这样做,因为它可以变得相当棘手。
您可以进一步简单地访问代码。
从Pearson更新优秀的代码
- 显示设置对Microsoft Visual Basic for Applications Extensibility 5.3的引用不是访问VBIDE的先决条件
- 实际上parsing出任何代码模块中任何
Dim XX As String
并报告
样本输出
Dim sthstring As String(Module1 at:Line:2)
Dim strSub As String(Module2 at:Line:2)
Dim FindWhat As String(Module2 at:Line:11)
Dim ProcName As String(Module3 at:Line:9)
码
Sub GetVariable() Dim strSub As String strSub = "As String" Call SearchCodeModule(strSub) End Sub
Function SearchCodeModule(ByVal strSub) Dim VBProj As Object Dim VBComp As Object Dim CodeMod As Object Dim FindWhat As String Dim SL As Long ' start line Dim EL As Long ' end line Dim SC As Long ' start column Dim EC As Long ' end column Dim Found As Boolean
Set VBProj = ActiveWorkbook.VBProject For Each VBComp In VBProj.VBComponents Set CodeMod = VBComp.CodeModule With CodeMod SL = 1 EL = .CountOfLines SC = 1 EC = 255 Found = .Find(target:=strSub, StartLine:=SL, StartColumn:=SC, _ EndLine:=EL, EndColumn:=EC, _ wholeword:=False, MatchCase:=False, patternsearch:=False) Do Until Found = False If Left$(Trim(.Lines(SL, 1)), 3) = "Dim" Then Debug.Print Trim(.Lines(SL, 1) & " (" & CStr(VBComp.Name) & " at: Line: " & CStr(SL)) & ")" EL = .CountOfLines SC = EC + 1 EC = 255 Found = .Find(target:=strSub, StartLine:=SL, StartColumn:=SC, _ EndLine:=EL, EndColumn:=EC, _ wholeword:=True, MatchCase:=False, patternsearch:=False) Loop End With Next VBComp End Function
这很难直接做,因为VBA没有反映,即不能直接引用自己。
然而;
由于在评论中您提到要编写引用自身的代码,因此可以通过在工具/引用对话框中引用Microsoft Visual Basic for Applications Extensibility 5.3
来实现。 这使您能够引用VBA代码,并从那里您可以编写自行打印的代码。
看到
- MSFT参考1 ,和
- MSFT参考2
这可能是不可能的,因为variables名只是指向数据的指针。 你可以有几个variables都指向同一个对象(虽然在VBA中,我不认为string被视为对象,所以这是不可能的,除了ByRef函数调用)。