2

Is there any way to e-mail an opened Excel file as attachment using VBA?

I use the following macro, but a debugger shows up when I run it, because obviously the file is open - so it won't allow it to be sent as attachment.

Sub simpleEmail()
 Dim OutApp As Object, MailItem As Object
 Set OutApp = CreateObject("Outlook.Application")
 Set MailItem = OutApp.CreateItem(0) 'Create Email
 MailItem.To = "email.com"
 MailItem.Subject = "subject"
 MailItem.Body = "body"
 MailItem.attachments.Add "file path"
 MailItem.send 
End Sub

Is there any way around this?

2 Answers 2

3

You can email an open Excel file as an attachment using VBA, but you need to save a copy of the workbook first, because Outlook can't attach a file that's currently open and locked for editing.

Sub SendActiveWorkbookAsEmail()
    Dim outlookApp As Object
    Dim outlookMail As Object
    Dim tempFolderPath As String
    Dim tempFileName As String
    Dim tempFileFullPath As String
    Dim currentWorkbook As Workbook
    Dim waitTime As Date

    On Error GoTo ErrorHandler

    Set currentWorkbook = ThisWorkbook

    tempFolderPath = Environ$("TEMP") & "\"
    tempFileName = "EmailCopy_" & Format(Now, "yyyymmdd_hhnnss") & "_" & currentWorkbook.Name
    tempFileFullPath = tempFolderPath & tempFileName

    ' Save a copy of the workbook
    currentWorkbook.SaveCopyAs tempFileFullPath

    ' Wait 3 seconds to ensure file is saved
    waitTime = Now + TimeValue("0:00:03")
    Do While Now < waitTime
        DoEvents
    Loop

    ' Check if file exists before proceeding
    If Dir(tempFileFullPath) = "" Then
        MsgBox "Temporary file was not created successfully.", vbCritical
        Exit Sub
    End If

    ' Initialize Outlook
    On Error Resume Next
    Set outlookApp = GetObject(, "Outlook.Application")
    If outlookApp Is Nothing Then
        Set outlookApp = CreateObject("Outlook.Application")
    End If
    On Error GoTo ErrorHandler

    ' Create email
    Set outlookMail = outlookApp.CreateItem(0)

    With outlookMail
        .To = "[email protected]"
        .Subject = "Subject of the Email"
        .Body = "Please find the attached Excel file."
        .Attachments.Add tempFileFullPath
        .Display ' Use .Send to send automatically
    End With

    ' Optional: Delete temp file
    On Error Resume Next
    Kill tempFileFullPath
    On Error GoTo 0

Cleanup:
    Set outlookMail = Nothing
    Set outlookApp = Nothing
    Exit Sub

ErrorHandler:
    MsgBox "An error occurred: " & Err.Description, vbExclamation
    Resume Cleanup
End Sub
Sign up to request clarification or add additional context in comments.

5 Comments

If the file is in a Sharepoint library, this might be useful: stackoverflow.com/questions/74108936/…
@Michal - Hi Michal, I used the above macro 'as-is' with just replacing the recipient email to my own. It worked one time but after trying it numerous times after that the email does not show up. The file itself is 11 mb. There is no error, the email just simply does not show up. Any ideas? Thank you.
@kxmoosekx - it could be one of a few things, file size limit, temp file not properly saved, Outlook not initialized correctly. I've added a few lines to the code to hopefully make it a little bit more resilient.
dag, still not working
any other ideas?
0

I adjusted Michal's script from below and this works:

Sub SendEmailWithOpenedWorkbook()
    Dim OutApp As Object
    Dim OutMail As Object
    Dim TempFilePath As String
    Dim TempFileName As String
    Dim TempFileFullPath As String
    
    ' Define temporary file path and name
    TempFilePath = Environ("TEMP") & "\"
    TempFileName = "File_Name" & Format(Now, "YYYYMMDD") & ".xlsx"
    TempFileFullPath = TempFilePath & TempFileName
    
    ' Save a copy of the workbook to the temporary location
    ThisWorkbook.SaveCopyAs TempFileFullPath
    
    ' Create Outlook application and email
    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)
    
    On Error Resume Next
    With OutMail
        .To = "email address" ' Replace with recipient's email
        .CC = ""                     ' Add CC if needed
        .BCC = ""                    ' Add BCC if needed
        .Subject = "Subject of the Email"
        .Body = "Please find the attached Excel file."
        .Attachments.Add TempFileFullPath
        .Send
    End With
    On Error GoTo 0
    
    ' Clean up
    Kill TempFileFullPath ' Delete the temporary file
    Set OutMail = Nothing
    Set OutApp = Nothing
    
End Sub

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.