很抱歉,如果这不是100%的开发问题(请随意建议其他董事会)。我一直在Excel中运行VBA代码,该代码通过Outlook(Office365程序包)发送电子邮件,而无需打开Outlook应用程序。罗恩·德·布鲁因(Ron de Bruin)最初编写的代码,稍加调整。
该代码可以正常工作并收到邮件。我是通过Task Scheduler启动代码从服务器运行服务器的,很少登录那里或打开Outlook。
让我有些担心的是:尽管收到了电子邮件,但只有在该服务器中启动Outlook客户端后,该邮件帐户已发送邮件文件夹才会更新(不想一直保持打开状态)。我应该担心已发送的邮件没有实时同步吗,如果在没有启动Outlook的情况下在一段时间内发送了很多邮件,会引起问题吗?
代码如下:
Sub email()
Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets(1)
Dim rng As Range
Set rng = ws.Range("Inforange2").SpecialCells(xlCellTypeVisible)
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.To = Range("ADDRESS2")
.CC = "my@email.com"
.BCC = ""
.Subject = Range("Subject") & Range("MONTH")
.HTMLBody = "Header text" & RangetoHTML(rng)
.Send
End With
On Error GoTo 0
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
Function RangetoHTML(rng As Range)
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.readall
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
"align=left x:publishsource=")
TempWB.Close savechanges:=False
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function