2016-05-18 848 views
4

我寫了一個宏,點擊一個按鈕後,它會通過Outlook發送一封自動發送的電子郵件。一切都運行順利,除非我無法弄清楚如何將文件附加到電子郵件。在我看過的任何地方,將文件附加到電子郵件的示例代碼都是針對靜態命名文件的,因爲每次發送相同的文件名時都使用相同的路徑。通過VBA從excel發送電子郵件附件

如果它使它更方便,運行此宏的按鈕位於我試圖附加的工作簿內。我不確定打開一個Windows資源管理器窗口是否最簡單,並以這種方式附加文件是最好的。

Dim objOutlook As Outlook.Application 
Dim objOutlookMsg As Outlook.MailItem 
Dim objOutlookRecip As Outlook.recipient 
Dim objOutlookAttach As Outlook.Attachment 
Dim WeekendingDate As Date 

With Worksheets("Macro Buttons") 
    WeekendingDate = Range("N2").Value 
End With 

Set objOutlook = CreateObject("Outlook.Application") 

Set objOutlookMsg = objOutlook.CreateItem(olMailItem) 

With objOutlookMsg 
    Set objOutlookRecip = .Recipients.Add("[email protected]") 
    objOutlookRecip.Type = olTo 
    .Subject = "Blah " & WeekendingDate 
    .Body = "blah blah blah" 

「添加消息附件 [一些代碼]

For Each objOutlookRecip In .Recipients 
     objOutlookRecip.Resolve 
    Next 
    If DisplayMsg Then 
     .Display 
    Else 
     .Save 
    End If 
End With 
Set objOutlook = Nothing 
End Sub 

回答

5

你需要插入的MailItem設置的Attachments.Add代碼:

With objOutlookMsg 
    Set objOutlookRecip = .Recipients.Add("[email protected]") 
    objOutlookRecip.Type = olTo 
    .Subject = "Blah " & WeekendingDate 
    .Body = "blah blah blah" 
'Add attachments to the message [some code] 
    .Attachments.Add "pathToFile" 
    For Each objOutlookRecip In .Recipients 
     objOutlookRecip.Resolve 
    Next 
    If DisplayMsg Then 
     .Display 
    Else 
     .Save 
    End If 
End With 
Set objOutlook = Nothing 

在我自己的一個腳本,我將附件集合傳遞給MailItem以使用Dictionary對象和以下代碼進行連接:

With oMailItem 
     Set .SendUsingAccount = oOutlook.Session.Accounts.Item(iAccount) 
     .To = EmailData("To") 
     .CC = EmailData("CC") 
     .BCC = EmailData("BCC") 
     .Subject = EmailData("Subject") 
     .Body = EmailData("Body") 
     sAttachArray = Split(EmailData("AttachmentPaths"), ";") 
     For Each sAttachment In sAttachArray 
      .Attachments.Add(sAttachment) 
     Next 
     .Recipients.ResolveAll 
     .Display ' debug mode - uncomment this to see email before it's sent out 
    End With 
+0

「路徑到文件」我應該把自己的路徑是動態的嗎?文件名稱正在更改 – Davey

+0

要添加哪個文件作爲附件? – Dave

+0

一個excel文件。我單擊的命令按鈕位於我試圖附加的工作簿內部。 – Davey

相關問題