Search code examples
excelvbaoutlook

Add Outlook mail recipient with VBA


I try to create an Outlook email from Excel using this code. The to address in variable strAddress is not added to mail. The recipients address stays empty. Whats wrong with this code? I'm using the latest Excel and Outlook from M365.

Sub testmail()

   strAddress = "[email protected]"
   strSubject = "Testmail"
   mc_strEmailBody = "Testmail"

   Set objOutlook = CreateObject("Outlook.Application")

   ' Create the message.
   Set objOutlookMsg = objOutlook.CreateItem(olMailItem)

   With objOutlookMsg
      ' Add the To recipient(s) to the message.
      Set objOutlookRecip = .Recipients.Add(strAddress)
      objOutlookRecip.Type = olTo

      ' Set the Subject and Body of the message.
      .Subject = strSubject
      .HTMLBody = mc_strEmailBody

      ' Resolve each Recipient's name.
      For Each objOutlookRecip In .Recipients
         objOutlookRecip.Resolve
         Debug.Print objOutlookRecip
      Next

      .Save
      .Send

   End With
   
   Set objOutlook = Nothing

End Sub


Solution

  • If you add a COM reference for the Outlook object model in VBA you will be able to use constants in the code. Otherwise, you have to declare Outlook related things as Object instead of using real classes and constants.

    You need to add the Microsoft Outlook XX.0 Object Library entry in the list of COM references, see Tools > References. If it doesn't work, you need to remove the existing reference, restart Excel and add the entry anew.