Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Outlook 2010 VBA run a macro whose name was passed as a parameter

Tags:

vba

outlook

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

  1. Call Application.strMacroName
  2. Call strMacroName
  3. strMacroName on its own line
  4. Outlook.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!

like image 674
Jeff1265344 Avatar asked Mar 13 '12 00:03

Jeff1265344


2 Answers

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.

like image 95
Mathieu Guindon Avatar answered Oct 17 '22 02:10

Mathieu Guindon


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.

like image 39
Travis Dawson Avatar answered Oct 17 '22 03:10

Travis Dawson