如何在插入 excel 表 (VBA) 后在电子邮件正文中添加更多文本

How to add further text in an e-mail body after excel table is inserted (VBA)

提问人:Walentyne 提问时间:11/7/2023 更新时间:11/14/2023 访问量:60

问:

我需要在电子邮件正文中插入一个 excel 表格。 我有一个插入表格的代码,但我还不知道如何在表格后添加文本。有没有办法以某种方式将表格插入电子邮件正文中或在其后添加文本?

这是我当前的代码:

Sub RangeToOutlook_Single()

Dim oLookApp As Outlook.Application
Dim oLookItm As Outlook.MailItem
Dim oLookIns As Outlook.Inspector
Dim wsSmy As Worksheet, wsCP As Worksheet
Dim LastRow As Integer, LastColumn As Integer
Dim StartCell As Range
Dim oWrdDoc As Word.Document
Dim oWrdRng As Word.Range
Dim ExcRng As Range

On Error Resume Next

Set oLookApp = GetObject(, "Outlook.Application")

    If Err.Number = 429 Then
        Err.Clear
        Set oLookApp = New Outlook.Application
    End If
    
Set oLookItm = oLookApp.CreateItem(olMailItem)

Set wsSmy = Workbooks("HRDA Audit_Master.xlsb").Sheets("SUMMARY")
Set wsCP = Workbooks("HRDA Audit_Master.xlsb").Sheets("Control Panel")
Set StartCell = wsSmy.Range("A1")
LastRow = wsSmy.Cells(wsSmy.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = wsSmy.Cells(StartCell.Row, wsSmy.Columns.Count).End(xlToLeft).Column
Set ExcRng = wsSmy.Range("A1:R" & LastRow)

With oLookItm
    .To = Range("S" & LastRow)
    .CC = ""
    .Subject = "HRDA Audit - " & wsCP.Range("B1")
    .Body = "Dear " & wsSmy.Range("T" & LastRow) & "," & vbLf & vbLf & _
    "Here is the first half of the text before the table."
    .Display
    
    Set oLookIns = .GetInspector
    Set oWrdDoc = oLookIns.WordEditor
    Set oWrdRng = oWrdDoc.Application.ActiveDocument.Content
        oWrdRng.Collapse Direction:=wdCollapseEnd

    ExcRng.Copy
    oWrdRng.Paste
End With
       
End Sub

如果我添加例如:.正文 = 。正文和“文本”,它将重新粘贴整个内容,但会丢失表格格式。 有人可以帮我修改上面的代码,这样我就可以在表格周围有文字吗? 提前致谢。

Excel VBA Outlook Excel 表格 电子邮件正文

评论

1赞 CDP1802 11/7/2023
尝试创建段落 看这里oWrdDoc.Paragraphs.Add.Range.Paste : oWrdDoc.Paragraphs.Add.Range.Text = "...text..."
0赞 niton 11/9/2023
仅供参考:认为这是强制性的,在有 .就在它之前.On Error GoTo 0On Error Resume NextSet oLookItm = oLookApp.CreateItem(olMailItem)
0赞 Walentyne 11/10/2023
@CDP1802,谢谢,我设法用 oWrdDoc.Paragraphs.Add.Range.Text = “...文本......”代码行。:)虽然不确定,如何将您的评论标记为答案。
0赞 Walentyne 11/11/2023
@CDP1802,我意识到我需要格式化我输入的文本,我只能通过更改 .正文到 .HTMLBody的。但是,我无法弄清楚如何将 oWrdDoc.Paragraphs.Add.Range.Text 中的文本转换为 HTML,或者如何格式化它。你有什么建议吗?
0赞 CDP1802 11/11/2023
您可以尝试添加一些 html 标签,例如"<p style="font:36pt Arial"><b><i>" & text & "</i></b></p>"

答:

0赞 CDP1802 11/14/2023 #1

尝试

    ExcRng.Copy
    oWrdDoc.Paragraphs.Add.Range.Paste
    
    With oWrdDoc.Paragraphs.Add.Range
        .Text = "Here is some text"
        .Font.Name = "Arial Unicode MS"
        .Font.Size = 24
        .Font.Bold = True
    End With