Search code examples
excelvbaoutlook

Attach saved version of active Excel workbook to an email


I have a Excel VBA code attached to a command button that preps an email for the user to send.

The user has to remember to save the active workbook before pressing the button. This leaves too much room for error.

How can the workbook be saved before it is attached?

Sub SendEmail()
    Dim OutApp As Object
    Dim OutMail As Object

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .to = "me"
        .Subject = "Completed Testing Schedule " & Date
        .Attachments.Add ActiveWorkbook.FullName
        .Display
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Solution

  • Sure, before you send the email, you can do:

    Documents.Save NoPrompt:=True, OriginalFormat:=wdOriginalDocumentFormat

    or

    If ActiveDocument.Saved = False Then ActiveDocument.Save

    You may want to add Application.DisplayAlerts = False before that, so you don't see that notice "Do you want to save", then put Application.DisplayAlerts = True after, to turn notifications back on.

    Edit: It's not clear if you're running this from Excel, which I assume you are.