首页 文章

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

提问于
浏览
1

我正在尝试一些相当简单的事情,我不知道我在做什么与其他编写代码的方式有什么不同 .

我使用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" 做一些研究,'s apparently because .add isn' t附件的一部分?但是为什么这么多的例子都有Attachments.Add作为将文件附加到Outlook电子邮件的代码?

我确保Outlook对象库已打开,其余的电子邮件很好地填充 - 只是没有附件 . 调试也将附件显示为问题 .

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

任何有关解决方案的指导都将受到赞赏 .

2 回答

  • 2

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

    见例子

    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)

  • 1

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

相关问题