I am in Outlook 2010 in Windows 7 writing in VBA and want to pass the name of a macro (or sub routine) as a string variable to another sub routine and have that routine run the macro. In Word you can do this with Application.Run MacroName:=strMacroName Where strMacroName is a string variable with the name of the macro. That approach does not work in Outlook 2010. How can I accomplish the same thing? I tried
Call Application.strMacroName
Call strMacroName
strMacroName
on its own lineOutlook.Application.strMacroName
None of those things worked.
I just upgraded to Outlook 2010 and so can no longer use keyboard shortcuts to run custom code for handling email. So to restore some version of that functionality I have created code to present a dialog box with my most common macros. The code is fairly clean to modify as time goes along and pass along the name of the macro I want to run but I used to be able to run that routine in one command (Application.Run MacroName:=strMacroName
).
Now I have to include a long switch statement to accomplish the same thing. Not nearly as simple.
Thanks!
CallByName
seems the only way to go.
With this code in ThisOutlookSession
:
Public Sub TestFoo()
Dim testClass As New TestClass1
CallByName testClass, "TestMethod1", VbMethod
End Sub
And this code in TestClass1
:
Public Sub TestMethod1()
MsgBox "huzzah!"
End Sub
Calling ThisOutlookSession.TestFoo
gives you the expected message box.
As far as I can tell, the only way to run a named macro programmatically in Outlook (without using custom Classes, as the other answer here does) is to create a temporary CommandBarButton, execute it, and immediately delete it. This works in Outlook 2013 even with the Ribbon:
Public Sub runProc(procToRun As String)
With Application.ActiveExplorer.CommandBars.Add("Custom", temporary:=True)
With .Controls.Add(msoControlButton, 1, , , True)
.OnAction = procToRun
.Execute
.Delete
End With
.Delete
End With
End Sub
I know this is an old question, but I was unable to find this exact answer myself in late 2017, so hopefully it will help someone else. Please note that this will NOT run macros that are in ThisOutlookSession...your macro needs to be in a code module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With