如何dynamic调用另一个Sub的Sub

我从来没有遇到这个想法,直到现在,但是是否有可能将另一个macros设置为当前macros中的一个variables,从VBA代码中调用它? 我以有限的知识做了这样的尝试,而且没有成功。

我所拥有的是一个包含combobox的用户表单,这个combobox是一个报表列表。 然后,我将该combobox的选定值与特定的Sub(按标题)进行匹配。 每个报告都有自己的macros,每月更新。

我编写了我的第一个macros(基于用户窗体上的“运行”button)的VBA,以设置一个variables(iVal)等于工作表的单元格中包含匹配的小标题的值。 我希望我可以使用该variables来调用基于该值的适当的小标题。 它不喜欢这个variables。

在这里查看错误的截图: https : //i.imgsafe.org/a2a199edb8.png

否则,我想我最好的select是使用数组循环。 我希望避免这种情况,因为从这个combobox中可能select的这个列表几乎有50种不同的可能性,随着时间的推移可能会扩大或缩小。 显然,这将是非常耗时的,并且随着报告和匹配macros列表的变化而变得非常困难。

我甚至不知道这是否可能。 这是一个新的VBA挑战,我从来没有处理过,所以它陷入了'我不知道我不知道'领土。 预先感谢任何build设性的反馈意见。

Private Sub Run_Click() 'Runs the Analysis Dim ProjectWB As Workbook Set ProjectWB = ActiveWorkbook Dim iWS As Worksheet Dim sName As String Dim tName As String Dim iName As String Set iWS = Worksheets("Streetwise Ideas") 'Error handling for empty file fields Application.ScreenUpdating = False Unload Me If TextBox1.Value = "" Then MsgBox "Please select a Source file.", vbCritical, "Error No Source file" If vbOK Then UserForm1.Show End If Else If TextBox2.Value = "" Then MsgBox "Please select a Target file.", vbCritical, "Error No Target file" If vbOK Then UserForm1.Show End If Else End If End If 'place value of the selection from the combobox in cell D2 on "Streetwise Ideas" sheet for referencing later in the macro iWS.Activate Range("D2").Select Selection.Value = cbSWIdeas sName = TextBox1.Value tName = TextBox2.Value 'Opens Source workbook file and sets it to variable sWB Dim sWB As Workbook Set sWB = Workbooks.Open(sName) 'Opens Target workbook file and sets it to variable tWB Dim tWB As Workbook Set tWB = Workbooks.Open(tName) 'Calls the correct macro for the combobox selection Dim iVal As String iVal = iWS.Range("E2").Value If iVal <> "" Then Call iVal Else 'do nothing MsgBox ("No Idea Selected.") Exit Sub End If Application.ScreenUpdating = True End Sub 

您可以使用Application.Run按名称调用macros

 Sub Example() Dim MacroName As String MacroName = "HelloWorld" Application.Run MacroName End Sub Sub HelloWorld() MsgBox "Hello World!" End Sub