我可以评估字符串格式的Excel VB常量吗?

时间:2013-01-23 23:56:25

标签: excel-vba constants evaluate vba excel

是否可以评估包含有效Excel VBA常量名称的字符串 返回那个常量值?

例如

    Dim ConstantName as String
    Dim ConstantValue as Long

    ConstantName="xlValues"

    ConstantValue= UnknownFunction(ConstantName)

    'would set ConstantValue=-4163

3 个答案:

答案 0 :(得分:2)

趣!

Option Explicit

Function getConstantValue(constStr As String) As Variant

    Dim oMod As VBIDE.CodeModule
    Dim i As Long, _
        num As Long

    Set oMod = ThisWorkbook.VBProject.VBComponents("Module1").CodeModule

    For i = 1 To oMod.CountOfLines
        If oMod.Lines(i, 1) = "Function tempGetConstValue() As Variant" Then
            num = i + 1
            Exit For
        End If
    Next i

    oMod.InsertLines num, "tempGetConstValue = " & constStr

    getConstantValue = Application.Run("tempGetConstValue")

    oMod.DeleteLines num

End Function

Function tempGetConstValue() As Variant
End Function

所有代码必须位于名为Module1的模块中。通过更改例程中的“Module1”文本,可以非常简单地改变它。

您需要添加对Microsoft Visual Basic for Applications Extensibility x.x

的引用

有很多方法可能会失败。如果您有任何问题,请告诉我:))

答案 1 :(得分:0)

您可以使用字典

,而不是使用常量
Dim dict As Object

Sub InitialiseDict()
    Set dict = CreateObject(Scripting.Dictionary)
    dict("xlValues") = -4163
    dict("const1") = value1
    ... 
    dict("constN") = valueN
End Sub

ConstValue = dict("xlValues")

答案 2 :(得分:-1)

是否使用了必要的字符串值?

Dim anyConstant as Long
anyConstant = xlValues

msgbox anyConstant

将anyConstant设置为您喜欢的任何xl常量,它们都是枚举的Long值。

然而,提供的第一个解决方案确实更有趣。

相关问题