Can I Evaluate An Excel VB Constant That Is In String Format?

后端 未结 3 1994
隐瞒了意图╮
隐瞒了意图╮ 2020-12-18 12:11

Is it possible to Evaluate a String which contains a valid Excel VB Constant\'s Name to return that Constant\'s Value?

eg

    Dim ConstantName as Str         


        
相关标签:
3条回答
  • 2020-12-18 12:20

    Instead of using constants, you could use a dictionary

    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")
    
    0 讨论(0)
  • 2020-12-18 12:24

    Is using the string value necessary?

    Dim anyConstant as Long
    anyConstant = xlValues
    
    msgbox anyConstant
    

    Set anyConstant to any xl constant you please, they are all enumerated Long values.

    The first solution offered is indeed much more fun however.

    0 讨论(0)
  • 2020-12-18 12:33

    Fun!

    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
    

    All code must be in a module called Module1. That can be changed pretty simply by changing the text "Module1" in the routine.

    You'll need to add a reference to Microsoft Visual Basic for Applications Extensibility x.x

    There are a number of ways this could fail. Let me know if you have any problems with it :)

    0 讨论(0)
提交回复
热议问题