Search code examples
excelvbaoutlook

Outlook mailitem method SaveAs using Excel VBA


I want to save email drafts in a dedicated folder.

In display option (when I turn off SaveAs) it works.

I found this on Microsoft Support.

I receive an error (occurs on SaveAs line):

enter image description here

Sub t1()
            
    Dim appOutlook As Object
    Dim mItem As Object
                                    
    Set appOutlook = CreateObject("Outlook.Application")
    Set mItem = appOutlook.CreateItem(0)
        
    With mItem
        .To = "@"
        .Subject = "test1"
        .HTMLBody = "<html><p>TestTest</p></html>"
        .SaveAs "myCorrectPathHere\test1.msg", OlSaveAsType.olMsg
        '.display
    End With
            
End Sub

Solution

  • I assume that since you're using late-binding you didn't set a reference to Microsoft Outlook xx.x Object library. Which likely means that your Excel IDE has no clue as to what OlSaveAsType is. You should either early bind Outlook or use the numeric value of the OlSaveAsType.olMsg constant, which is 3.

    .SaveAs "myCorrectPathHere\test1.msg", 3
    

    If you're looking to Early Bind your Outlook objects, which is recommended for a variety of reasons, you should go to Tools > References and then check the box next to your

    Microsoft Outlook xx.x Object Library
    

    enter image description here

    Once you've done that, you can then change your code to use early binding, which means no more generic As Object variables or using CreateObject()...

    Sub t1()
    
        Dim appOutlook As Outlook.Application
        Dim mItem As Outlook.MailItem
        
        Set appOutlook = New Outlook.Application
        Set mItem = appOutlook.CreateItem(0)
        
        With mItem
            .To = "@"
            .Subject = "test1"
            .HTMLBody = "<html><p>TestTest</p></html>"
            .SaveAs "myCorrectPathHere\test1.msg", OlSaveAsType.olMSG
            .Display
        End With
    
    End Sub
    

    Edit

    You should get in the habit of using Option Explicit at the top of every code module in the IDE, which requires all variables to be explicitly declared.

    The Outlook COM library that you would have referenced already defines what this is, which is why you aren't required to do so when you set the reference to it.

    But this would have given you a compile error letting you know that OlSaveAsType isn't defined.