I'm writing a macro that creates tickets on a database based on alerts received from a Nagios server as an email. However, I cannot let the macro run in an infinite loop while checking for mails because it is just too resource heavy and makes my desktop hang. I need to find a way to trigger the macro only when a new mail is received.
I looked for something along the lines of NewMail events on the MSDN website, but I can't find anything coherent. Can anyone show me just a bit of sample code to show how to trigger macros from new mail events?
First off, access “Outlook Options” by following the operations shown in Step 1, in which you can shift to “Quick Access Toolbar” tab. Next, select “Macros” from the “Choose commands from”. Then, in the macro list, choose a macro. After that, click “Add >>” button in center.
Select the macro you want to run, by placing your cursor anywhere within the macro, and press F5, or on the menu, go to Run > Run Macro.
If you are using VBA to create macros, there are two ways you can automate Outlook. You can implement a macro that creates a new instance of the Outlook Application object. The CreateNewDefaultOutlookTask() method above shows how to call New Outlook. Application to create a new Application object instance.
This code will add an event listener to the default local Inbox, then take some action on incoming emails. You need to add that action in the code below.
Private WithEvents Items As Outlook.Items Private Sub Application_Startup() Dim olApp As Outlook.Application Dim objNS As Outlook.NameSpace Set olApp = Outlook.Application Set objNS = olApp.GetNamespace("MAPI") ' default local Inbox Set Items = objNS.GetDefaultFolder(olFolderInbox).Items End Sub Private Sub Items_ItemAdd(ByVal item As Object) On Error Goto ErrorHandler Dim Msg As Outlook.MailItem If TypeName(item) = "MailItem" Then Set Msg = item ' ****************** ' do something here ' ****************** End If ProgramExit: Exit Sub ErrorHandler: MsgBox Err.Number & " - " & Err.Description Resume ProgramExit End Sub
After pasting the code in ThisOutlookSession
module, you must restart Outlook.
Try something like this inside ThisOutlookSession
:
Private Sub Application_NewMail() Call Your_main_macro End Sub
My outlook vba just fired when I received an email and had that application event open.
Edit: I just tested a hello world msg box and it ran after being called in the application_newmail
event when an email was received.
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