Calling Sub by Variable Name

hellsreach

New Member
Joined
Dec 22, 2015
Messages
19
I am trying to can one of several macros by variable name and not sure how.

Sub myMacro()

Dim myArray(2) as Variant

myArray(0) = "A"
myArray(1) = "B"
myArray(2) = "C"

For I = 0 to 2
Call myArray(I) ' -- clearly, this wont work!!!
Next I

End Sub

Private Sub A()
...
End Sub


Private Sub B()
...
End Sub


Private Sub C()
...
End Sub
 

Excel Facts

Why are there 1,048,576 rows in Excel?
The Excel team increased the size of the grid in 2007. There are 2^20 rows and 2^14 columns for a total of 17 billion cells.
You could do this:-
Code:
Sub myMacro()
 Dim myArray(2) As Variant
 Dim I As Long
 myArray(0) = "A"
 myArray(1) = "B"
 myArray(2) = "C"
 For I = 0 To 2
    Select Case True
        Case myArray(I) = "A": Call A
        Case myArray(I) = "B": Call B
        Case myArray(I) = "C": Call C
    End Select
 Next I
 End Sub
 
Upvote 0
Or, you could use the
Code:
Run
command.

Code:
Option Explicit

Sub myMacro()
    Dim i
    Dim myArray()
    myArray = Array("Asub", "Bsub", "Csub")
    For i = 0 To UBound(myArray)
        Application.Run myArray(i)
    Next i
End Sub
Private Sub Asub()
    MsgBox "This is sub Asub"
End Sub
Private Sub Bsub()
    MsgBox "This is sub Bsub"
End Sub
Private Sub Csub()
    MsgBox "this is sub Csub"
End Sub
 
Upvote 0

Forum statistics

Threads
1,224,825
Messages
6,181,191
Members
453,021
Latest member
pingpong7117

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top