保存工作簿时发送电子邮件

我正在尝试发送一封电子邮件,将更新用户对电子表格的更改。 我试图做到这一点,当文档被保存时,会有一个电子邮件自动发送的变化列表。

有谁知道在保存文档时是否可以自动化电子邮件?

你可以在这里使用这个代码,看起来不像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窗口,然后在右边窗口中selectWorbook,然后从下拉菜单中select工作簿:

工作簿

然后从右边的下拉菜单中selectBeforeSave:

BeforeSave

然后粘贴你的代码:

你应该以此结束:

最后

它应该是。 您需要将代码放在Workbook_BeforeSave事件中,以便在保存工作簿时触发它。

Chip Pearson 从VBA发送电子邮件有一篇很好的文章

您需要将代码放在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