提问人: 提问时间:3/8/2014 最后编辑:Martijn Pieters 更新时间:6/23/2020 访问量:49026
如何将活动的 Excel 工作簿附加到电子邮件
How to attach active Excel workbook to an email
问:
我整个上午都在尝试让这个VBA脚本将我的活动excel文档附加到自动生成的Outlook邮件中。如果我将文件路径声明为字符串并附加它,一切正常。除了我想附加当前 excel 文档的完整文件路径而不是使用静态字符串值。
这是我的代码:
Private Sub CommandButton1_Click()
Dim OutApp As Object
Dim OutMail As Object
Dim strbody As String
Dim sAttach As String
Dim sTo As String
Dim sCC As String
'For To field
Set emailRng = Worksheets("Pre-Clearance Email").Range("E11:J14")
For Each cl In emailRng
sTo = sTo & ";" & cl.Value
Next
sTo = Mid(sTo, 2)
'For CC field
Set emailRngCC = Worksheets("Pre-Clearance Email").Range("E16:J19")
For Each cl In emailRngCC
sCC = sCC & ";" & cl.Value
Next
sCC = Mid(sCC, 2)
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
'variable declarations for email body and attachment
strbody = "<BODY style=font-size:11pt;font-family:Calibri>Good Morning;<p>Please see the attached aliases for validation. Please let me know if you have any questions.<p>Thank you.</BODY>"
sAttach = "K:\CRM Support\Data\Systematic Trade Recon (1).xlsm"
'the below code adds a users default signature to the email
With OutMail
.Display
End With
signature = OutMail.HTMLBody
With OutMail
.to = sTo
.CC = sCC
.Subject = "STR Pre-Clearance"
.HTMLBody = strbody & signature
.Attachments.Add (ActiveDocument.FullName)
'.Attachments.Add sAttach
.Display 'Instead of .Display, you can use .Send to send the email _
or .Save to save a copy in the drafts folder
End With
编译器在这一行给了我一个错误:
.Attachments.Add (ActiveDocument.FullName)
我已经做了一些研究,并试图自己解决问题,但我只是无法弄清楚如何使此脚本将活动文件附加到此Outlook邮件。正如你从我的代码中看到的,我的备份选项是只使用一个字符串变量和一个静态地址来附加文件,但我宁愿让这个脚本比这更通用。
这是我找到的一个网站,它给了我这个想法: 这里
答:
10赞
user2993456
3/14/2014
#1
好吧,经过一番努力,我能够完美地附加工作簿。以下是我在原始代码中对 OutMail 对象所做的修订:
With OutMail
.to = sTo
.CC = sCC
.Subject = "STR Pre-Clearance"
.HTMLBody = strbody & signature
.Attachments.Add (ActiveDocument.FullName) 'this is the correction I made
.Display
我想我会回答我自己的问题,这样它就不会在没有技术答案的情况下徘徊。也许它将来会帮助某人。
6赞
user6654783
7/29/2016
#2
修复实际上应该是:
With OutMail
.To = sTo
.CC = CC
.Subject = "STR Pre-Clearance"
.HTMLBody = strbody & signature
.Attachments.Add (ActiveWorkbook.FullName) 'should be workbook not document
.Display 'or .Send
评论
0赞
user6654783
7/29/2016
对不起,我刚刚看到分享它可能是 ActiveWorkbook.FullName 的评论
评论
ActiveWorkbook.Path & "\" & ActiveWorkbook.Name
.Attachments.Add (ActiveWorkbook.FullName)
对我有用。它看起来像是尝试链接整个目录,这太大了。>_< 感谢您的提示,我现在意识到我应该使用 .ActiveWorkbook.Path
ActiveWorkbook
ActiveWorkbook.FullName
ActiveWorkbook.Path & "\" & ActiveWorkbook.Name