0

我正在尝试发送一封电子邮件,更新用户对电子表格的更改。我正在尝试这样做,以便在保存文档时会自动发送一封电子邮件,其中包含更改列表。

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

4

3 回答 3

3

您可以在此处使用此代码,不像 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首先使用+打开 VBA 窗口F11,然后在右侧窗口中选择工作簿,然后从下拉列表中选择工作簿:

工作簿

然后从右侧的下拉菜单中选择 BeforeSave:

保存前

然后将您的代码粘贴到那里:

你应该以此结束:

最后

于 2013-06-06T14:58:39.997 回答
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
于 2013-06-06T14:42:30.660 回答
1

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

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

于 2013-06-06T14:39:45.727 回答