在从文档中引用 table 值后,如何在 Word 中使用 VBA 添加其他文本到主题?

How do I add additional text to subject using VBA in Word after referencing a table value from within the document?

我有一个宏可以根据 word 文档创建电子邮件。单击宏后,将保存 word 文档,创建具有预定义主题的电子邮件,添加收件人,创建简短消息,然后等待用户发送。主题和正文甚至会引用 word 文档中 table 中的第一个单元格。

我需要能够在引用 table 中的单元格后在主题中添加文本。但是每次我在引用的单元格(从第 1 行,第 2 列)之后添加一些内容时,什么也没有出现。当我做一些类似于正文的事情时,它看起来像是在引用单元格值后开始了一个新行。

如何停止创建新行以便我可以引用主题中的两个不同项目?我粘贴的代码应该有一个主题“Customers Name [cell value] #Order Number [cell value]”但它只给出“Customers Name [cell value]”。

下面是我使用的代码副本,其中删除了电子邮件地址和内容。

Private Sub CommandButton1_Click()
Dim OL              As Object
Dim EmailItem       As Object
Dim Doc
 
Application.ScreenUpdating = False
Set OL = CreateObject("Outlook.Application")
Set EmailItem = OL.CreateItem(olMailItem)
Set Doc = ActiveDocument
On Error GoTo handler
    Doc.Save
On Error GoTo 0

 
With EmailItem
    .Display
    .Subject = "Customers Name " & Doc.Content.Tables(1).Cell(1, 2) & " #Order Number" & Doc.Content.Tables(1).Cell(1, 4)
    .Body = "Please see the attached Notification for " & Doc.Content.Tables(1).Cell(1, 2) & " order" & _
    "" & vbCrLf & _
    "Let me know if you have any questions." & vbCrLf & _
    "" & vbCrLf & _
    "Thank you," & vbCrLf & vbCrLf & _
    "INSERT SIGNATURE HERE"
'Update Recipient List here:
    .To = "randomemail@email.com"
    .Importance = olImportanceNormal
    .Attachments.Add Doc.FullName
End With
 
Application.ScreenUpdating = True
 
Set Doc = Nothing
Set OL = Nothing
Set EmailItem = Nothing

每个单元格末尾有两个非打印字符。您需要删除它们。

With Doc.Content.Tables(1)
    Customer = Left(.Cell(1, 2).Range.Text, Len(.Cell(1, 2).Range.Text) - 2)
    Order = Left(.Cell(1, 4).Range.Text, Len(.Cell(1, 4).Range.Text) - 2)
End With

单元格标记的结尾就像段落标记的结尾,这会阻止在电子邮件的主题中添加任何其他内容。

在设置 Doc = ActiveDocument 后的代码中添加以下内容:

Dim Rng1 As Word.Range, Rng2 As Word.Range
Set Rng1 = Doc.Content.Tables(1).Cell(1, 2).Range
Rng1.MoveEnd unit:=wdCharacter, Count:=-1
Set Rng2 = Doc.Content.Tables(1).Cell(1, 4).Range
Rng2.MoveEnd unit:=wdCharacter, Count:=-1

然后将主题代码的设置替换为:

.Subject = "Customers Name " & Rng1.Text & " #Order Number" & Rng2.Text