How can I send an Excel file via email?

梦想的初衷 提交于 2019-12-10 23:56:19

问题


I have to create and send an Excel file every month via email to my boss. I want to use a VBA code to send the file as attachment, but my VBA code doesn't work and asks for debug after confirmation.

My code:

Sub EMail() 
ActiveWorkbook.SendMail Recipients:="user@gmail.com" 
End Sub

回答1:


Here is an example on how to send Active Workbook as attachment

Option Explicit
Sub EmailFile()
    Dim olApp As Object
    Dim olMail As Object
    Dim olSubject As String

'   // Turn off screen updating
    Application.ScreenUpdating = False

    Set olApp = CreateObject("Outlook.Application")
    Set olMail = olApp.CreateItem(olMailItem)

    olSubject = "This Subject Line"

    With olMail
        .Display
    End With

    With olMail
        .To = "0m3r@EMail.com"
        .CC = ""
        .BCC = ""
        .Subject = olSubject
        .HTMLBody = "This Body Text " & .HTMLBody
        .Attachments.Add ActiveWorkbook.FullName
        '.Attachments.Add ("C:\test.txt") ' add other file
'        .Send   'or use .Display
        .Display
    End With

'   // Restore screen updating
    Application.ScreenUpdating = True

    Set olMail = Nothing
    Set olApp = Nothing

End Sub



回答2:


Credit where credit is due... This is straight from the Ron de Bruin website.

Sub Mail_workbook_Outlook_1()
'Working in Excel 2000-2016
'This example send the last saved version of the Activeworkbook
'For Tips see: https://www.rondebruin.nl/win/s1/outlook/tips.htm
    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 = "ron@debruin.nl"
        .CC = ""
        .BCC = ""
        .Subject = "This is the Subject line"
        .Body = "Hi there"
        .Attachments.Add ActiveWorkbook.FullName
        'You can add other files also like this
        '.Attachments.Add ("C:\test.txt")
        .Send   'or use .Display
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub



回答3:


You can use the VBA code snippet as shown in the following sample:

Sub SendEmailWithAttachment() 
 Dim myItem As Outlook.MailItem 
 Dim myAttachments As Outlook.Attachments

 Set myItem = Application.CreateItem(olMailItem) 
 Set myAttachments = myItem.Attachments 
 myAttachments.Add "C:\MyExcelFile.xls", olByValue, 1, "Test"
 myItem.To = "Recipient Address"
 myItem.Send

 'alternatively, you may display the item before sending
 'myItem.Display
End Sub

Hope this may help.



来源:https://stackoverflow.com/questions/35829348/how-can-i-send-an-excel-file-via-email

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!