我目前正在重新利用在网上找到的这段代码,以便可以在一个电子邮件正文中发送多个数据表。我也希望有一个文本电子邮件正文。当我尝试包含文本主体(.body)时,稍后将其替换为表格(.htmlbody)。我假设如果我也尝试在电子邮件中放置另一个表,它将用第二个表替换第一个表。有没有一种方法可以使用标记或其他东西在Outlook电子邮件中放置多个正文。我以前用Microsoft Word完成过此操作,但不确定如何在Outlook中使用它。
Sub Mail_Selection_Range_Outlook_Body()
Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object
Set rng = Nothing
' Only send the visible cells in the selection.
Set rng = Sheets("Sheet1").Range("B1:F5").SpecialCells(xlCellTypeVisible)
If rng Is Nothing Then
MsgBox "The selection is not a range or the sheet is protected. " & _
vbNewLine & "Please correct and try again.", vbOKOnly
Exit Sub
End If
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
.display
.To = ThisWorkbook.Sheets("Sheet2").Range("A2").Value
.CC = ""
.BCC = ""
.Subject = "This is the Subject line"
.body = "Here is the email body"
.HTMLBody = RangetoHTML(rng)
' In place of the following statement, you can use ".Display" to
' display the e-mail message.
'.Display
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)
' By Ron de Bruin.
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"
'Copy the range and create a new workbook to past the data in
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
'Publish the sheet to a htm file
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
'Read all data from the htm file into RangetoHTML
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=")
'Close TempWB
TempWB.Close savechanges:=False
'Delete the htm file we used in this function
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function
答案 0 :(得分:0)
我对.body
和.HTMLBody
属性的工作方式的理解是,它们都为电子邮件正文分配了一个值,从而替换了已经存在的内容。 .body
期望使用常规文本,而.HTMLBody
期望使用HTML格式的信息。
要使其不替换您要插入.body
的文本,请在分配.HTMLBody
时尝试使用.HTMLBody = .HTMLBody & "<br /><br />" & RangetoHTML(rng)
(当我将HTML签名附加到电子邮件中时,这对我很有用,尽管我使用"<p><BR/><BR/></p>"
作为换行符。)
在添加任何其他信息时,该行也应该起作用,因为该行将采用电子邮件正文中当前的内容,并在换行符后附加新信息,然后将结果字符串重新分配给.HTMLBody
(HTML换行语法由Glitch_Docter's对问题的评论提供)。