努力使用Excel VBA将文件附加到Outlook电子邮件

时间:2017-05-23 20:47:41

标签: excel vba excel-vba outlook

我尝试了一些相当简单的事情,但我无法说出我所做的事情与其他编写的代码的做法有何不同。

我使用Outlook从Excel发送一封非常简单的电子邮件:

Sub SendEmail()

    Dim OutApp As Object
    Dim OutMail As Object


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

With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With
    With OutMail
        .To = Range("ETF_CAB_Recon_Initial_Email_To")
        .CC = Range("ETF_CAB_Recon_Initial_Email_CC")
        .BCC = ""
        .Subject = Range("ETF_CAB_Recon_Initial_Email_Subject")
        .HTMLBody = Range("ETF_CAB_Recon_Initial_Email_Body")
        .Attachments.Add Range("ETF_CAB_Recon_Initial_Email_Attachment")
        .Display  
    End With


    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

但是,我的文件附件变得脾气暴躁。

错误消息:"Object doesn't support this property or method"做一些研究,显然是因为.add不是附件的一部分?但是为什么这么多的例子都有Attachments.Add作为将文件附加到Outlook电子邮件的代码?

我确保Outlook对象库已启用,其余电子邮件填写得很好 - 只是没有附件。调试也将附件显示为问题。

我尝试了几种不同的方法来定义位置。

对于解决方案的任何指导将不胜感激。

2 个答案:

答案 0 :(得分:2)

Attachments.Add只接受字符串(文件名)或其中一个Outlook项目(例如MailItem)的实例。您正在传递Range对象。

答案 1 :(得分:1)

尝试完全限定您的工作簿并将字符串变量分配到您的范围

参见示例

Option Explicit
Sub SendEmail()
    Dim OutApp As Object
    Dim OutMail As Object
    Dim Sht As Object
    Dim RecipTo As String
    Dim RecipCC As String
    Dim Subject As String
    Dim Atmt As String

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

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

    Set Sht = ThisWorkbook.Worksheets("Sheet1")

    With Sht
        RecipTo = Sht.Range("A1").Value
        RecipCC = Sht.Range("B1").Value
        Subject = Sht.Range("C1").Value
        Atmt = Sht.Range("D1").Value ' Attachment Path

        With OutMail
            .To = RecipTo
            .CC = RecipCC
            .BCC = ""
            .Subject = Subject
            .HTMLBody = Sht.Range("E1")
            .Attachments.Add Atmt
            .Display
        End With

    End With

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

请参阅此处的另一个示例https://stackoverflow.com/a/38303646/4539709

Attachments Object (Outlook)

相关问题