保存工作簿时发送电子邮件
Posted
技术标签:
【中文标题】保存工作簿时发送电子邮件【英文标题】:Send an email when workbook is saved 【发布时间】:2013-06-06 14:34:55 【问题描述】:我正在尝试发送一封电子邮件,向用户更新电子表格的更改。我正在尝试这样做,以便在保存文档时会自动发送一封电子邮件,其中包含更改列表。
有谁知道是否可以在保存文档时自动发送电子邮件?
【问题讨论】:
【参考方案1】:你可以在这里使用这段代码,不像Chip Pearson那么花哨但容易理解,这个方法也依赖于使用outlook:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim Outlook As Object, EMail As Object
Set Outlook = CreateObject("Outlook.Application")
Set EMail = Outlook.CreateItem(0)
With EMail
.To = "EmailAddress1@Server.com; Email2@aol.com"
.CC = ""
.BCC = ""
.Subject = "Put your subject here"
.Body = "Add you E-Mail Message Here"
.Attachments.Add ActiveWorkbook.FullName ' To add active Workbook as attachment
.Attachments.Add "C:\Test.xlsx" ' To add other files just use path, Excel files, pictures, documents pdf's ect.
.Display 'or use .Send to skip preview
End With
Set EMail = Nothing
Set Outlook = Nothing
End Sub
要设置这里是完整的指南:
首先使用ALT
+ F11
打开VBA窗口,然后在右侧窗口中选择Worbook,然后从下拉列表中选择workbook:
然后从右侧的下拉菜单中选择 BeforeSave:
然后将您的代码粘贴到那里:
你应该这样结束:
【讨论】:
最后一张截图有问题吗 - 代码应该是空白的区域? @ChrisSpicer 是的,现在已修复。谢谢【参考方案2】:应该是的。您需要将代码放在 Workbook_BeforeSave 事件中,以便在保存工作簿时触发。
Chip Pearson 在Sending E-mail from VBA 上有一篇好文章
【讨论】:
【参考方案3】:您需要将代码放在 ThisWorkbook 代码部分。 Workbook_BeforeSave
事件在保存工作簿之前触发。希望下面的代码能让您了解如何实现它。
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
' Identify here list of changes
' You can pass as a string to SendMail
Dim strChanges As String
strChanges = "test"
SendMail strChanges
End Sub
Sub SendMail(msg As String)
Dim iMsg As Object
Dim iConf As Object
Dim Flds As Variant
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
iConf.Load -1
Set Flds = iConf.Fields
'Configure the below details
With Flds
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "test-002"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
.Update
End With
With iMsg
Set .Configuration = iConf
.To = "test@gmail.com"
.From = "test@gmail.com"
.Subject = "msg" & " " & Date & " " & Time
.TextBody = msg
.Send
End With
Set iMsg = Nothing
Set iConf = Nothing
End Sub
【讨论】:
您提供的代码给了我一个“编译错误:成员已经存在于该对象模块派生的对象模块中”。它突出了第二部分“Sub SendMail(msg As String)”中的第一行代码 @DavidVanderVieren 将SendMail
过程移至标准模块。以上是关于保存工作簿时发送电子邮件的主要内容,如果未能解决你的问题,请参考以下文章
打开 openpyxl 保存的工作簿时 Excel 有不可读的内容