简体   繁体   English

具有变量名称的Excel VBA调用函数

[英]Excel VBA call function with variable name

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 to figure it out in Excel VBA, I suspect this is because I don't really understand how the compiler works. 这在大多数语言中都很简单,但我似乎无法在Excel VBA中弄明白,我怀疑这是因为我并不真正理解编译器的工作原理。 I've found several posts that are close but don't quite seem to do the trick. 我发现有几个帖子很接近,但似乎并没有这么做。 The code below is wrong but should give an idea of what I want. 下面的代码是错误的,但应该知道我想要什么。

Thanks 谢谢

Sub main()
    'run formatting macros for each institution on format button click

     Dim fn As String
     Dim x As Boolean

     'create format function name from CB value        
     fn = "format_" & CBinst.Value

     'run function that returns bool
     x = Eval(fn)

     ...

End Sub

CallByName is what you'll need to accomplish the task. CallByName是您完成任务所需的。

example: Code in Sheet1 示例:Sheet1中的代码

Option Explicit
Public Function Sum(ByVal x As Integer, ByVal y As Integer) As Long
    Sum = x + y
End Function

Code is Module1 (bas module) 代码是Module1(bas模块)

Option Explicit

Sub testSum()
Dim methodToCall As String
methodToCall = "Sum"

MsgBox CallByName(Sheet1, methodToCall, VbMethod, 1, 2)
End Sub

Running the method testSum calls the method Sum using the name of the method given in a string variable, passing 2 parameters (1 and 2). 运行方法testSum使用字符串变量中给出的方法名称调用方法Sum ,传递2个参数(1和2)。 The return value of the call to function is returned as output of CallByName . 函数调用的返回值作为CallByName输出返回。

The above will work but not with a large number of names 以上内容可行,但不会有大量名称

Use Application.Run(MacroName, Parameters) 使用Application.Run(MacroName,Parameters)

You have to may sure that there is a macro but it is better than the above as there is no select statement. 你必须确定有一个宏,但它比上面更好,因为没有select语句。

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
'-----------------------------------------------------------------------------------

You should write a function that accepts the CB value as a parameter and then uses a select case to call the appropriate formatting function. 您应该编写一个接受CB值作为参数的函数,然后使用select case调用相应的格式化函数。

Something similar to this 类似的东西

Function SelectFormatting(Name as String) As Boolean
Select Case CBinst.Value
Case "Text1":
   SelectFormatting = Text1FormattingFunction()
Case "Text2":
   .
   .
   .
End Select
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM