Home > OS >  Outlook VBA - Create an email, allow the user to send, then execute further code
Outlook VBA - Create an email, allow the user to send, then execute further code

Time:08-24

I have an outlook Macro that collects some information from existing emails and a local database, then serves up a templated email with the information. The user can then review the email, make changes if they want to and then send or not sent (quit/cancel). Is there a way, I can keep the macro running and then execute more code if the user sends the email?

I've created some psuedo code below on how I'm hoping it might work:

Function CreateEmailThenExecuteCode()
    Dim newEmail As MailItem
    Set newEmail = Application.CreateItem(olMailItem)
    
    newEmail.Display
    'Allow user to review and send email
    'If they 'send', then execute further code.
    
    If Not Sent Then Exit Function
    
    'Further code
End Function

I know that I can create a new macro that runs every time a user sends an email - but it would be much easier if I can keep the existing macro running, as otherwise I need a way of saving the data from the running macro.

I also know that I can create a custom user form that mimics an email user form - but I would prefer to keep the functionality of the full email user form, especially with access to email address lists etc.

Is it possible?

CodePudding user response:

The Display method doesn't prevent your code from running until you pass true to make the Inspector window modal. The default value is false.

At the same keeping the code running after the Display call doesn't allow users to deal with Outlook UI because the VBA code will be run on the main thread (UI).

You may consider setting up an event handler for the Send event which is fired when the user selects the Send action for an item, or when the Send method is called for the item. So, you will be aware when the item is sent out.

Also you may find the MailItem.Close event helpful. It is fired when the inspector associated with an item is being closed. So, you will also be aware when the item is closed.

  • Related