根据日期自动从excel发送电子邮件

时间:2016-03-21 14:05:06

标签: excel vba excel-vba

所以我的代码会在特定日期将特定电子邮件发送到通讯组列表。范围(“R19”)具有日期值。单击运行按钮时它正在工作。但我不确定它会在日期值发生变化时自动生效。

Sub Send_Monthly()

Set senddate = Worksheets("MONTHLY REMINDER").Range("R19")

If senddate.Value = Date Then

Set oApp = CreateObject("Outlook.Application")
Set oEmail = oApp.CreateItem(olMailItem)

Set colAttach = oEmail.Attachments

oEmail.Close olSave

oEmail.HTMLBody = "<html>Hello World.</htmlcenter>" 
oEmail.Save
oEmail.To = "clients@abc.com"
oEmail.Importance = 2
oEmail.Subject = "REMINDER" & " " & Format(Now, "mmmm yyyy")
oEmail.SentOnBehalfOfName = "support@abc.com"
oEmail.Display

Set oEmail = Nothing
Set colAttach = Nothing
Set oAttach = Nothing
Set oApp = Nothing

End If

End Sub

1 个答案:

答案 0 :(得分:0)

要在特定单元格更改时运行此选项,请将其置于Worksheet_Change事件中。在要运行此工作表的工作表中,输入代码,并进行一些小的调整:

Sub Worksheet_Change(ByVal target As Range)
Dim sendDate As Range
Dim oApp As Object, oEmail As Object, olMailItem As Object
Dim colAttach, olSave, oAttach

Set sendDate = Worksheets("MONTHLY REMINDER").Range("R19")
' I'm assuming you only want this to run if the value changes is `sendDate`
If target.address <> sendDate.address Then Exit Sub

If sendDate.Value = Date Then

Set oApp = CreateObject("Outlook.Application")
Set oEmail = oApp.CreateItem(olMailItem)

Set colAttach = oEmail.Attachments

oEmail.Close olSave

oEmail.HTMLBody = "<html>Hello World.</htmlcenter>"
oEmail.Save
oEmail.To = "clients@abc.com"
oEmail.Importance = 2
oEmail.Subject = "REMINDER" & " " & Format(Now, "mmmm yyyy")
oEmail.SentOnBehalfOfName = "support@abc.com"
oEmail.Display

Set oEmail = Nothing
Set colAttach = Nothing
Set oAttach = Nothing
Set oApp = Nothing

End If

End Sub