Search code examples
excelvbaoutlookexcel-365

Trying to late bind outlook to but getting type mismatch error after create object line


I am trying to late bind the process of opening up an outlook message for reporting a problem or a suggestion for a spreadsheet. I am trying to prefill the TO: and CC: recipients, Subject Line, and the first couple of lines of the the message body. I do not want to send the message as I need the user to populate the message body with their thoughts.

I found some code that was originally set up using early binding. Then I proceeded to mangle it to hopefully suit my needs. Then I butchered it trying to make it work with late binding.

When I step through the code, I get a Run-time error '13': Type mismatch in the second create object line which I am assuming is actually trying to create the message. I tried changing the olMailItem to 0. This results in an activeX error: Run-time error '429': ActiveX component can't create object.

I have Option Explicit set.

Private Sub ReportBug_Click()

Dim objOutlook As Object
Dim objOutlookMsg As Object
Dim objOutlookRecip As Object
Dim olMailItem As Object
Dim Recipients As Object

    Set objOutlook = CreateObject("Outlook.Application")
    Set objOutlookMsg = objOutlook.CreateObject(olMailItem)
    
    With objOutlookMsg
        Set Recipients = objOutlookMsg.Recipients
        'Set TO: recipient
        Set objOutlookRecip = .Recipients.Add("[email protected]")
        objOutlookRecip.Type = 1 '1 for to
        'Set CC: recipient
        Set objOutlookRecip = .Recipients.Add("[email protected]")
        objOutlookRecip.Type = 2 '2 for cc
    
        'Set Subject Line
        .Subject = "Forecasting Sheet Bug / Recommendation from " & Me.Cells(4, 2).Value
        'start message body
        .HTMLBody = "To whom it may concern," & vbCrLf & vbCrLf & "With respect to the forecasting sheet I noted the following:" & vbCrLf
        
        'Resolve each Recipient's name.
        For Each objOutlookRecip In .Recipients
          objOutlookRecip.Resolve
        Next
        
        'objOutlookMsg.Send
        .Display
        
    End With
        
    Set objOutlook = Nothing
End Sub

Some of the previous questions I looked at were:

This one where I learned to switch out olTO and olCC with their numeric values. I could not find a numeric value listed for olMailItem.

And This one which made oMail.CC = "email address here" look like a simpler option

And this one where I snagged the initial starting code for me

And I swear there was another which I can no longer find the link for.

Questions

How do I fix my goofS and get rid of the error?


Solution

  • Change this:

    Set objOutlookMsg = objOutlook.CreateObject(olMailItem)
    

    to this:

    Set objOutlookMsg = objOutlook.CreateItem(0)