如何通过电子邮件发送Excel文件?

时间:2016-03-06 16:24:38

标签: excel vba email email-attachments

我必须每个月通过电子邮件创建并发送一个Excel文件给我的老板。 我想使用VBA代码将文件作为附件发送,但我的VBA代码不起作用,并在确认后要求调试。

我的代码:

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

3 个答案:

答案 0 :(得分:2)

信用到期的信用......这可以直接来自Ron de Bruin网站。

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

答案 1 :(得分:0)

您可以使用VBA代码段,如以下示例所示:

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

希望这可能会有所帮助。

答案 2 :(得分:0)

以下是有关如何将Active Workbook作为附件发送的示例

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