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

后端 未结 3 2013
隐瞒了意图╮
隐瞒了意图╮ 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: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 :)

提交回复
热议问题