2016-07-28 16 views
2

直到現在我還沒有遇到過這個想法,但是可以將另一個宏設置爲當前宏中的變量,以便從VBA代碼調用它?我在有限的知識中做了這樣的嘗試,但它並不奏效。如何從另一個子動態調用子

我所擁有的是一個包含組合框的用戶窗體,它是一個報告列表。然後我將該組合框中的選定值與特定的Sub(按標題)進行匹配。每個報告都有自己的宏,每月更新一次。

我已經編寫了我的第一個宏(基於用戶窗體上的「運行」按鈕)的VBA,以將變量(iVal)設置爲等於工作表中包含匹配的子標題的單元格內的值。我希望我可以使用該變量根據該值調用適當的Sub標題。它不喜歡這個變量。

看到這裏出錯的截圖:https://i.imgsafe.org/a2a199edb8.png

否則,我想我最好的選擇是使用數組循環。我希望避免這種情況,因爲從這個組合框中可能選擇的這個列表幾乎有50種不同的可能性,隨着時間的推移可能會擴大或縮小。顯然,這將是非常耗時的,並且隨着報告和匹配宏列表的變化而進行管理將面臨一個挑戰。

我甚至不知道這是否可能。這是一個新的VBA挑戰,我從來沒有處理過,因此它陷入了'我不知道我不知道'領土。預先感謝任何建設性的反饋。

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 

回答

3

可以使用Application.Run通過名字來稱呼宏

Sub Example() 

    Dim MacroName As String 
    MacroName = "HelloWorld" 
    Application.Run MacroName 

End Sub 

Sub HelloWorld() 

    MsgBox "Hello World!" 

End Sub 
+0

感謝一大堆托馬斯Inzina!我在笑,因爲我記得閱讀有關運行另一個宏的不同方法,因爲我正在研究我的問題(包括Application.Run),並且認爲還有其他問題。驚人! –

+0

解決方案通常隱藏在我們忽略的細節中。 – 2016-07-28 17:17:10

相關問題