How do I create a macro that runs a VBA script in Outlook?

Ware-Furlow, Joey 20 Reputation points
2026-06-29T15:19:38.7266667+00:00

I wrote code to save Excel attachments from my Outlook to a folder in OneDrive. The application name is Application_NewMailEx. How do I write a macro in Outlook?

Microsoft 365 and Office | Development | Other
0 comments No comments

Answer accepted by question author

Marcin Policht 96,670 Reputation points MVP Volunteer Moderator
2026-06-29T16:42:26.86+00:00

In Outlook, press Alt + F11 to open the VBA editor. In the left pane, expand “Microsoft Outlook Objects” and double-click “ThisOutlookSession.” Paste your macro code there if you are using the Application_NewMailEx event, because that event must live inside ThisOutlookSession to run automatically when mail arrives.

Your macro structure should look something like this:

Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)
your code
End Sub

If your code saves Excel attachments to OneDrive, you would typically use the Attachment.SaveAsFile method and point it to your OneDrive folder path, for example: C:\Users\YourName\OneDrive\Attachments\

After pasting the code, save the project and restart Outlook. Then go to File > Options > Trust Center > Trust Center Settings > Macro Settings and enable notifications or allow signed macros. Also make sure “Programmatic Access” is not blocking automation.

Finally, test by sending yourself an email with an Excel attachment. The macro only runs when new mail arrives in Outlook, not on existing messages already in the Inbox.


If the above response helps answer your question, remember to "Accept Answer" so that others in the community facing similar issues can easily find the solution. Your contribution is highly appreciated.

hth

Marcin

Was this answer helpful?

1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.