excel - 在 Excel 中使用 VBA 在 HTML 表格正文电子邮件中创建列
问题描述
我创建了一个表格,该表格将以 HTML 格式放置在 Outlook 电子邮件的正文中。我正在努力将值放入适当的列中。我一直在玩“td”标签,但没有成功。所有值现在彼此相邻,它们之间没有空格,因此不是正确的表格格式。请帮忙!
我的代码:
Public Sub HypMail4()
Dim OutApp As Object
Dim OutMail As Object
Dim strbody As String
Set Out App = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
strbody = ""
strbody = strbody & _
"<html>" & "<table>" & "<font color = ""red""><b>" & Range("A1") &
Range("B1") & Range("C1") & Range("D1") & Range("E1") & "</font></b>" & "
</th>" & _
"<tr>" & Range("A2") & Range("B2") & Range("C2") & Range("D2") & Range("E2")
& "</tr>"
strbody = strbody & _
"<tr>" & Range("A3") & Range("B3") & Range("C3") & Range("D3") & Range("E3")
& "</tr>"
strbody = strbody & _
"<tr>" & Range("A4") & Range("B4") & Range("C4") & Range("D4") & Range("E4")
& "</tr>" & "</table>" & "</html>"
On Error Resume Next
With OutMail
.To = "zzz@example.com"
.CC = ""
.BCC = ""
.Subject = "Test"
.HTMLBody = strbody
.Send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
解决方案
通过确实包含 td 标签,我设法自己回答了我的问题。然而,主要问题是我定义 strbody 太多次,这弄乱了表格格式(因此 td 标签不起作用) - 请参阅下面的代码:
Public Sub Test()
Dim OutApp As Object
Dim OutMail As Object
Dim strbody As String
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
strbody = "<html>" & "<table>" & "<tr>" & "<td>" & Range("A1") & "</td>" & "<td>" & Range("B1") & "</td>" & "<td>" & Range("C1") & "</td>" & "</tr>" & _
"<tr>" & "<td>" & Range("A2") & "</td>" & "<td>" & Range("B2") & "</td>" & "<td>" & Range("C2") & "</td>" & "</tr>" & _
"<tr>" & "<td>" & Range("A3") & "</td>" & "<td>" & Range("B3") & "</td>" & "<td>" & Range("C3") & "</td>" & "</tr>" & _
"<tr>" & "<td>" & Range("A4") & "</td>" & "<td>" & Range("B4") & "</td>" & "<td>" & Range("C4") & "</td>" & "</tr>" & "</table>" & "</html>"
With OutMail
.To = "zzz.com@zzz.com"
.CC = ""
.BCC = ""
.Subject = "Test"
.HTMLBody = strbody
.Send
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub