Creating email body in VBA using Word Editor - Error 91

Good afternoon, All.

I have created VBA code below with the help of an online tutorial however despited having exactly the same code, my route doesn't run.

Sub sendcomplexemail()

    Dim olapp As Outlook.Application
    Dim olemail As Outlook.MailItem
    Dim olInsp As Outlook.Inspector
    Dim wddoc As Word.Document
   

    Set olapp = New Outlook.Application
    Set olemail = olapp.CreateItem(olMailItem)
   
    With olemail
       
        .BodyFormat = olFormatRichText
        .Display
        .To = *** Email address is removed for privacy ***

        .Subject = "Movies Report"

   

        Set olInsp = .GetInspector
        Set wddoc = olInsp.WordEditor
       
        wddoc.Range.InsertBefore "Good Morning"
End With
End Sub   

The code does creates the email but stops at the body :(. I then get error message = "Run-Time error '91': Object Variable or with block variable not set".

I understand I am missing something but I dont know what to do to fix it.

Thank you very much for your help in advance.

Best Regards,

Vanessa Simmonds
























Answer
Answer

The macro you quoted would work from Outlook, with some minor modifications to the sequence of commands. From Excel VBA it needs more changes.  Unless you are going to make references to Outlook and Word object libraries you should setup the macro for late binding to Outlook and Word. This means setting the Outlook and Word variables as objects and using the number equivalents of specific Word and Outlook references. Some change in the sequence of events is also called for.

e.g. using your macro as the basis

Sub sendcomplexemail()

Dim olapp As Object
Dim olemail As Object
Dim olInsp As Object
Dim wddoc As Object

    On Error Resume Next
    Set olapp = GetObject(, "Outlook.Application")
    If Err <> 0 Then Set olapp = CreateObject("Outlook.Application")
    On Error GoTo 0
    Set olemail = olapp.CreateItem(0)
    With olemail
        .BodyFormat = 3
        .To = "*** Email address is removed for privacy ***"
        .Subject = "Movies Report"
        Set olInsp = .GetInspector
        Set wddoc = olInsp.WordEditor
        wddoc.Range.InsertBefore "Good Morning"
        .Display
    End With
End Sub

Graham Mayor (Microsoft Word MVP 2002-2019)
For more Word tips and downloads visit my web site
https://www.gmayor.com/Word_pages.htm

1 person found this reply helpful

·

Was this reply helpful?

Sorry this didn't help.

Great! Thanks for your feedback.

How satisfied are you with this reply?

Thanks for your feedback, it helps us improve the site.

How satisfied are you with this reply?

Thanks for your feedback.

 
 

Question Info


Last updated March 7, 2020 Views 6,557 Applies to: