如何使用 Excel VBA 将导出的 pdf 文件附加到 Outlook 邮件?

How to attach exported pdf file to Outlook mail using Excel VBA?

我的代码找不到要附加到电子邮件的导出文件。

我确定我在 myattachments.add 行中做错了什么。

每个客户端的文件名和文件目录总是不同的,这就是为什么我在每个引用中专门为文件名指定了一个单元格。

我要将此 Excel 文件复制到每个客户端文件夹,并从那里 运行 复制代码。

Sub sendremindermail()
ChDir ThisWorkbook.Path & "\"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=Range("'Costing'!C1"), Openafterpublish:=True

Dim outlookapp As Object
Dim outlookmailitem As Object
Dim myattachments As Object

Set outlookapp = CreateObject("outlook.application")
Set outlookmailitem = outlookapp.createitem(0)
Set myattachments = outlookmailitem.Attachments

With outlookmailitem
.To = Range("'Costing'!C8")
myattachments.Add ThisWorkbook.Path & Range("'Costing'!C1") & ".pdf" ' it cant find the pdf in the same directory
'.send
.Display
End With

Set outlookmailitem = Nothing
Set outlookapp = Nothing

End Sub

我是 VBA 的新手 Excel。

您可以参考下面的代码:

Sub Mail_Workbook_1()
' Works in Excel 2000, Excel 2002, Excel 2003, Excel 2007, Excel 2010, Outlook 2000, Outlook 2002, Outlook 2003, Outlook 2007, Outlook 2010.
' This example sends the last saved version of the Activeworkbook object .
    Dim OutApp As Object
    Dim OutMail As Object

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

    On Error Resume Next
   ' Change the mail address and subject in the macro before you run it.
    With OutMail
        .To = "ron@debruin.nl"
        .CC = ""
        .BCC = ""
        .Subject = "This is the Subject line"
        .Body = "Hello World!"
        .Attachments.Add ActiveWorkbook.FullName
        ' You can add other files by uncommenting the following line.
        '.Attachments.Add ("C:\test.txt")
        ' In place of the following statement, you can use ".Display" to
        ' display the mail.
        .Send   
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

更多信息,请参考这个link:

OfficeTalk: Using the Excel Object Model to Send Workbooks and Ranges through E-Mail with Outlook (Part 1 of 2)

我建议 Outlook VBA 不知道 Excel VBA 的范围。

您可以像这样从 Range 传递信息:

Sub sendremindermail()

Dim fName As String
Dim pathFileName As String

ChDir ThisWorkbook.Path & "\"

fName = Range("'Costing'!C8")

'ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=Range("'Costing'!C1"), Openafterpublish:=True
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=fName ', Openafterpublish:=True

Dim outlookapp As Object
Dim outlookmailitem As Object
Dim myattachments As Object

Set outlookapp = CreateObject("outlook.application")
Set outlookmailitem = outlookapp.createitem(0)
Set myattachments = outlookmailitem.Attachments

With outlookmailitem
    .To = fName
    pathFileName = ThisWorkbook.Path & "\" & fName & ".pdf"
    Debug.Print "With fName not Range: " & pathFileName
    myattachments.Add pathFileName
    '.send
    .Display
End With

Set outlookmailitem = Nothing
Set outlookapp = Nothing

End Sub