Code to move Outlook email to local folder not triggering on ItemSend event.

GP 1 Reputation point
2024-04-25T13:52:41.2966667+00:00

The following code is intended to trigger on sending an email, which would then check an Outlook folder and move any emails within to a local folder. I see no indication of the code being triggered, i.e.- emails remain in folder, no msgbox prompt.

As an event handler it is not listed in macros to manually step through.

This code was a collaboration with Perplexity.ai, and I am unaware of any errors the ai may have introduced.

What am I missing, and how do I trace/debug this?

Debugging steps:

  • Using 365.
  • Restarted Outlook
  • Currently all this code resides in "ThisOutlookSession".
  • Tools > References > Microsoft Office 16.0 Object Library is checked.
  • Breakpoints in myOlApp_ItemSend (not breaking)
  • MsgBox not firing
  • No other add-ins to conflict with
Public WithEvents myOlApp As Outlook.Application

Private Sub Application_Startup()
Set myOlApp = Application
End Sub

Private Sub myOlApp_ItemSend(ByVal Item As Object, Cancel As Boolean)

Dim prompt As String

prompt = "Are you sure you want to send " & Item.Subject & "?"

If MsgBox(prompt, vbYesNo + vbQuestion, "Sample") = vbNo Then
Cancel = True
End If

' This procedure moves emails to a local folder
Dim olApp As Outlook.Application
Dim olNS As Outlook.NameSpace
Dim olFolder As Outlook.MAPIFolder
Dim olItem As Outlook.MailItem
Dim strSaveFolder As String
Dim strFileName As String

' Set the Outlook application object
Set olApp = Outlook.Application
Set olNS = olApp.GetNamespace("MAPI")

' Set the Outlook folder to monitor (subfolder of Inbox)
Set olFolder = olNS.GetDefaultFolder(olFolderInbox).Folders("D&D").Folders("Sly Flourish")

' Set the local folder to save the emails
strSaveFolder = "C:\Users\ge\Documents%%Personal\Gaming\D&D\Campaigns and Ideas\Sly Flourish Campain Lessons"

' Loop through all emails in the subfolder
For Each olItem In olFolder.Items

' Generate the file name
strFileName = strSaveFolder & olItem.Subject & ".msg"

' Move the email to the local folder
olItem.SaveAs strFileName, olMSG

' Delete the email from the Outlook subfolder
olItem.Delete
Next olItem

' Display a message to the user
MsgBox "Emails moved to: " & strSaveFolder

' Clean up
Set olItem = Nothing
Set olFolder = Nothing
Set olNS = Nothing
Set olApp = Nothing
End Sub
Outlook
Outlook
A family of Microsoft email and calendar products.
4,156 questions
Office Development
Office Development
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Development: The process of researching, productizing, and refining new or existing technologies.
4,063 questions
0 comments No comments
{count} votes

Your answer

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