vbaoutlookcom-automation

Call a macro from ThisOutlookSession


I have a problem with my macros on outlook.

I am currently trying via a batch to call outlook and pass it as a parameter the name of a macro that I get via an environment variable I've set in my batch. However I do get the name of my macro, but the process stops at the time of the Call function. Could someone tell me the right way to proceed?

VBA ThisOutlookSession

Private Sub Application_Startup()
    Dim strMacroName As String
    strMacroName = CreateObject("WScript.Shell").Environment("process").Item("MacroName")
    'MsgBox strMacroName
    'MsgBox VarType(strMacroName)
    If strMacroName <> "" Then Call strMacroName
    End Sub

VBA Modules

Option Explicit
Sub macro1()
MsgBox "macro1"
End Sub
Sub macro2()
MsgBox "macro2"
End Sub

Batch

Set WorkingPath=C:\Temp\Outlook
Set MacroName=%1
start OUTLOOK.EXE
Set MacroName=
Set WorkingPath=

the result

enter image description here


Solution

  • There are several aspects here... The first point is possible security issues when dealing with the Outlook. You can read more about that in the Security Behavior of the Outlook Object Model article.

    Another point is that you can call VBA macros declared in the ThisOutlookSession module in the following way (for example, from any other Office application):

    Sub test()
      Dim OutApp As Object
      Set OutApp = CreateObject("Outlook.Application")
      OutApp.Session.Logon
      OutApp.HelloWorld
    End Sub
    

    Where the HelloWorld sub is declared in the ThisOutlookSession module in following way:

    Option Explicit
    Public Sub HelloWorld()
      MsgBox "Hello world !!"
    End Sub
    

    Note, you may call any module from the ThisOutlookSession module. There is no need to get access to other modules directly.