VBA如何获取变量的名称字符串

VBA怎么样提取变量的名称?
比如有一个变量mub=123,怎么获得“mub”这个字符串

VBA没有直接的方法可以提取变量的名称,但是可以通过以下的方式间接的获得:

使用反射:通过枚举所有模块中的变量来查找特定的变量。。

Function GetVariableName(Variable As Variant) As String
    Dim obj As Object
    For Each obj In VBA.VBE.ActiveCodePane.CodeModule.Globals
        If VBA.VarType(obj) = VBA.VarType(Variable) Then
            If obj = Variable Then
                GetVariableName = obj.Name
                Exit Function
            End If
        End If
    Next obj
End Function

该函数接受一个变量作为参数,然后枚举活动代码窗格的所有全局变量,并在匹配的变量的类型和值时返回变量的名称
另外,
使用Eval命令:在VBA中可以使用Eval命令把字符串转换成变量,再使用VarType命令得到变量的值,最后使用TypeName命令得到变量的名称。
代码示例:

Dim mub As Integer
mub = 123

Debug.Print TypeName(Eval("mub"))

以上代码运行后会在调试窗口中输出“Integer”,也就是变量mub的类型名称