Excel VBA call function with variable name

后端 未结 4 1147
不思量自难忘°
不思量自难忘° 2020-12-28 10:34

I\'m trying to call a function with a variable name that is generated at run time based upon a combo box value. This is straightforward in most languages but I can\'t seem

4条回答
  •  -上瘾入骨i
    2020-12-28 10:55

    With respect to my answer above you might also find this useful to check whether the macro exists

    '=================================================================================
    '- CHECK IF A MODULE & SUBROUTINE EXISTS
    '- VBA constant : vbext_pk_Proc = All procedures other than property procedures.
    '- An error is generated if the Module or Sub() does not exist - so we trap them.
    '---------------------------------------------------------------------------------
    '- VB Editor : Tools/References - add reference TO ......
    '-    .... "Microsoft Visual Basic For Applications Extensibility"
    '----------------------------------------------------------------------------------
    '- Brian Baulsom October 2007
    '==================================================================================
    Sub MacroExists()
        Dim MyModule As Object
        Dim MyModuleName As String
        Dim MySub As String
        Dim MyLine As Long
        '---------------------------------------------------------------------------
        '- test data
        MyModuleName = "TestModule"
        MySub = "Number2"
        '----------------------------------------------------------------------------
        On Error Resume Next
        '- MODULE
        Set MyModule = ActiveWorkbook.VBProject.vbComponents(MyModuleName).CodeModule
        If Err.Number <> 0 Then
        MsgBox ("Module : " & MyModuleName & vbCr & "does not exist.")
        Exit Sub
        End If
        '-----------------------------------------------------------------------------
        '- SUBROUTINE
        '- find first line of subroutine (or error)
        MyLine = MyModule.ProcStartLine(MySub, vbext_pk_Proc)
        If Err.Number <> 0 Then
        MsgBox ("Module exists      : " & MyModuleName & vbCr _
               & "Sub " & MySub & "( )  : does not exist.")
        Else
        MsgBox ("Module : " & MyModuleName & vbCr _
            & "Subroutine   : " & MySub & vbCr _
            & "Line Number : " & MyLine)
        End If
    End Sub
    '-----------------------------------------------------------------------------------
    

提交回复
热议问题