我正在尝试发送一封电子邮件,更新用户对电子表单的更改。我试图这样做,以便在保存文档时,将自动发送一个包含更改列表的电子邮件。
有人知道在保存文档时是否可以自动发送电子邮件?
答案 0 :(得分:2)
你可以在这里使用这段代码不像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,然后从下拉列表中查看工作簿:
然后从右侧的Drop down选择BeforeSave:
然后将代码粘贴到那里:
你应该以此结束:
答案 1 :(得分:1)
应该是。您需要将代码放在Workbook_BeforeSave事件中,以便在保存工作簿时触发它。
Chip Pearson在Sending E-mail from VBA
上有一篇很好的文章答案 2 :(得分:1)
您需要将代码放入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