excel - 如何在 Excel 中使用 VBA 将附件添加到电子邮件

标签 excel vba outlook attachment

我有以下代码,但它不起作用。我对 VBA 也很陌生。该代码可以填充电子邮件模板,但一旦我添加 .Attachment.Add 它就不起作用。

Sub CreateMail()

Dim objOutlook As Object
Dim objMail As Object
Dim rngTo As Range
Dim rngSubject As Range
Dim rngBody As Range
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)

With ActiveSheet
    Set rngTo = .Range("E2")
    Set rngSubject = .Range("E3")
    Set rngBody = .Range("E4")
    .Attachments.Add "Z:\PHS 340B\Letters of Non-Compliance\..Resources\W9 Form\VPNA W-9 01 09 2017"
End With

With objMail
    .to = rngTo.Value
    .Subject = rngSubject.Value
    .Body = rngBody.Value
    .Display 'Instead of .Display, you can use .Send to send the email _
                or .Save to save a copy in the drafts folder
End With

Set objOutlook = Nothing
Set objMail = Nothing
Set rngTo = Nothing
Set rngSubject = Nothing
Set rngBody = Nothing

End Sub

最佳答案

试试这个:

Sub emailtest()

Dim objOutlook As Object
Dim objMail As Object
Dim rngTo As Range
Dim rngSubject As Range
Dim rngBody As Range
Set objOutlook = CreateObject("Outlook.Application")
Set objMail = objOutlook.CreateItem(0)

With ActiveSheet
Set rngTo = .Range("E2")
Set rngSubject = .Range("E3")
Set rngBody = .Range("E4")
End With

With objMail
.To = rngTo.Value
.Subject = rngSubject.Value
.Body = rngBody.Value
.Attachments.Add "Z:\PHS 340B\Letters of Non-Compliance\..Resources\W9 Form\VPNA W-9 01 09 2017"
.Display 'Instead of .Display, you can use .Send to send the email _
            or .Save to save a copy in the drafts folder
End With

Set objOutlook = Nothing
Set objMail = Nothing
Set rngTo = Nothing
Set rngSubject = Nothing
Set rngBody = Nothing

End Sub

在 Outlook 而非 Excel 中工作时,您需要使用 .Attachments.Add。

关于excel - 如何在 Excel 中使用 VBA 将附件添加到电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48775858/

相关文章:

python - Pandas:ValueError:工作表索引 0 无效,找到 0 个工作表

excel - 将工作表传递给子例程

macos - 思科如何为 Outlook mac 集成 webex 插件

html - outlook 邮件中未采用图像样式高度和宽度

c# - 使用 C# 将 HTML 字符串导出到 ASP.Net 中的 Excel 文件

Excel:在另一个公式中使用单元格的值而不是公式

vba - 在 VBA + Excel 中使用 pscp.exe 将文件从 Windows 传输到 Unix 服务器时,获取 "The server' 的主机 key 未缓存在注册表中

vba - 在表单中调用子程序

html - outlook.com、microsoft exchange 和 hotmail.com 中的空 HTML 邮件

arrays - 你可以直接将excel VBA中的数组内容写入CSV文件吗?