Run Macros From Drop Down
- Copy the first code into the sheet module of the worksheet containing the drop down, e.g.
Sheet1
(the name in parentheses in the VBE Project Explorer
).
- Adjust the values in the constants section.
- Put your codes into the same module, e.g.
Module1
. Otherwise you will have to modify the code.
- In this example the drop down list is in cell
A1
of worksheet Sheet1
and contains the list (values) Sub1
, Sub2
, Sub3
.
Sheet Module e.g. Sheet1
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Const CellAddress As String = "A1"
Const ModuleName As String = "Module1"
If Target.Cells.CountLarge = 1 Then
If Not Intersect(Range(CellAddress), Target) Is Nothing Then
Application.EnableEvents = False
On Error GoTo clearError
Application.Run ModuleName & "." & Target.Value
Application.EnableEvents = True
End If
End If
Exit Sub
clearError:
MsgBox "Run-time error '" & Err.Number & "': " & Err.Description
Resume Next
End Sub
Standard Module e.g. Module1
(Example)
Option Explicit
Sub Sub1()
MsgBox "Running 'Sub1'"
End Sub
Sub Sub2()
MsgBox "Running 'Sub2'"
End Sub
Sub Sub3()
MsgBox "Running 'Sub3'"
End Sub
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…