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 does 9 mean SUM in SUBTOTAL?
It is because Sum is the 9th alphabetically in Average, Count, CountA, Max, Min, Product, StDev.S, StDev.P, Sum, VAR.S, VAR.P.
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,223,908
Messages
6,175,306
Members
452,633
Latest member
DougMo

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