vbaemailoutlooksubject

Check subject after tabbing to body of mail


Once I tab to the email's body I want to check the subject.
If equal to a specific text then open a template.

I wrote the part about the template.
The difficult part is using the inspectors to check the subject while writing the mail.

Code in thisOutlookSession

Private Sub subject()
 
Dim subject As String
Dim item As Outlook.MailItem
Dim inspector As Outlook.inspector
Dim template As Outlook.MailItem

Set inspector = Outlook.ActiveInspector
Set item = inspector.CurrentItem
subject = item.subject

Debug.Print subject

If subject = "test" Then
    Set template = Application.CreateItemFromTemplate("C:test\test.oft")
    Display.template
Else
End If

End Sub

Solution

  • Please, try the next way:

    1. Create three variables on top of ThisOutlookSession:
       Private WithEvents m_Inspectors As Outlook.Inspectors
       Private WithEvents m_Inspector As Outlook.Inspector
       Private WithEvents myItem As Outlook.MailItem
    
    1. Copy the next Startup event code in ThisOutlookSession module:
     Private Sub Application_Startup()
         Set m_Inspectors = Application.Inspectors
     End Sub
    

    Or copy only the line Set m_Inspectors = Application.Inspectors inside it, if already used for other purposes.

    1. Then, copy the next events code in the same module:
     Private Sub m_Inspectors_NewInspector(ByVal Inspector As Outlook.Inspector)
        If TypeOf Inspector.CurrentItem Is Outlook.MailItem Then
           'Handle emails only:
           Set m_Inspector = Inspector
        End If
    End Sub
    
     Private Sub m_Inspector_Activate()
        If TypeOf m_Inspector.CurrentItem Is MailItem Then 
           Set myItem = m_Inspector.CurrentItem '!!!
        End If
     End Sub
    
    1. And the PropertyChange event to be triggered when pressing enter after writing the subject (or clicking somewhere else: body, To, CC etc.):
     Private Sub myItem_PropertyChange(ByVal Name As String)
        Const specSubject As String = "mySubject..." 'use here the subject you need to open the template!
        Const templFullName As String = "C:test\test.oft"
        If Name = "Subject" Then
             If myItem.Subject = specSubject Then
                    'do whatever you need...
                    myItem.Close False 'probably you want closing the new Email. If not, comment this line...
                    With Application.CreateItemFromTemplate(templFullName)
                        .Display
                    End With
             End If
        End If
     End Sub
    

    Now, manually press New Email button and play with the new mail window Subject...