问题
I use Excel to send emails using text in a textbox as body. This works fine, except that when sending a mail, it only copies the text's font size, but not its color or style. I did lots of research, but didn't find any solution. Is there a code that allows Excel to copy the style of the text in a textbox as well as its content? Here is the code of sending the mail :
Sub SendMail()
Dim OutApp As Outlook.Application
Dim OutMail As Outlook.MailItem
Dim strbody As String
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(olMailItem)
strbody = ThisWorkbook.Sheets("Mail").Shapes("txt").DrawingObject.Text
'I named the textbox "txt" in the worksheet
'On Error Resume Next
With OutMail
.To = "...@...com"
.CC = ""
.BCC = ""
.Subject = Cells(3, 2)
.Body = strbody
.Send
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
I know this is possible in HTML like :strbody = "<BODY style=font-size:11pt;font-family:Calibri>Good Morning;<p>We have completed our main aliasing process for today. All assigned firms are complete. Please feel free to respond with any questions.<p>Thank you.</BODY>"
But since I'm writing the body in a textbox instead of in the code, I'd prefer to find a solution.
Thank you in advance.
回答1:
PasteExcelTable is probably what you're looking for, but it's a little more hidden in the sense that Outlook is actually using a Word Document writer. You need to add the Word Object reference.
You'll have to modify the rest of your code to insert using the writer instead of .HTMLbody or .body.
Also note that for the inspector/write to work it seems that you cannot hide the window, but I did not fully test that.
Sub SendEmail()
Dim OutApp As Outlook.Application
Dim OutMail As Outlook.MailItem
Dim strbody As String
Dim olInsp As Outlook.Inspector
Dim document As Word.document
Dim oRng As Excel.Range
Set OutApp = New Outlook.Application
Set OutMail = OutApp.CreateItem(olMailItem)
With OutMail
.To = "...@...com"
.CC = ""
.BCC = ""
.Subject = Cells(3, 2)
.Display
Set olInsp = .GetInspector
If olInsp.IsWordMail And olInsp.EditorType = olEditorWord Then
Set document = olInsp.WordEditor
Set oRng = Range("A1:B2") ' The range you wish to copy into the document
oRng.Copy ' Loads info to clipboard
' Write the range into the first paragragh of the word document.
document.Paragraphs(1).Range.PasteExcelTable False, False, True
' Example how to write to the end of the email.
Dim p As Word.Paragraph
Set p = document.Paragraphs.Add
p.Range.Text = "test"
End If
End With
Set OutMail = Nothing
Set OutApp = Nothing
End Sub
回答2:
First of all I don't know of any default/built-in way in Excel to do this. What you need is a Excel cell format to HTML converter.
You can only built this on your own or find a suitable script online; similar to this one: Macro to Convert Excel Cell to HTML and preserve font formatting.
来源:https://stackoverflow.com/questions/42899865/vba-change-the-style-of-text-when-sending-a-mail