【问题标题】:How to replace text in Word with Excel table?如何用Excel表格替换Word中的文本?
【发布时间】:2021-04-27 09:16:03
【问题描述】:

我正在尝试使用带有 VBA 的 Word 模板发送电子邮件。在模板的中间,我添加了 > 作为文本。我想将此文本替换为 Excel 文件中的表格。

我收到

运行时错误“13”

说到

.Replacement.Text = Sheet1.Range("A24:F" & lr).SpecialCells(xlCellTypeVisible)
Sub SendMail()

    Dim ol As Outlook.Application
    Dim olm As Outlook.MailItem

    Dim wd As Word.Application
    Dim doc As Word.Document

    Set ol = New Outlook.Application

    Set olm = ol.CreateItem(olMailItem)
    
    Set wd = New Word.Application
    wd.Visible = True
    Set doc = wd.Documents.Open("C:\Users\campoalv\Desktop\US-Dec.docx")

    lr = Sheet1.Range("A" & Application.Rows.Count).End(xlUp).Row

    With wd.Selection.Find
        .Text = "<<Table>>"
        .Replacement.Text = Sheet1.Range("A24:F" & lr).SpecialCells(xlCellTypeVisible)
        .Execute Replace:=wdReplaceAll
    End With
    
    doc.Content.Copy
    
    With olm
        .Display
        .To = ""
        .Subject = "Test"
    
        Set Editor = .GetInspector.WordEditor
        Editor.Content.Paste
        '.Send
    End With

    Set olm = Nothing
    Application.DisplayAlerts = False
    doc.Close SaveChanges:=False
    Set doc = Nothing
    wd.Quit
    Set wd = Nothing
    Application.DisplayAlerts = True
    
End Sub

【问题讨论】:

  • Sheet1.Range("A24:F" &amp; lr).SpecialCells(xlCellTypeVisible) 将返回一个数组。 .Replacement.Text 需要 String。我不认为你想要在这里找到/替换,也许是复制/粘贴。
  • 请问你是怎么做的?
  • 您需要根据(可见)范围值在 Word 中构建表格。也许从这样的事情开始:excel-macro.tutorialhorizon.com/…

标签: excel vba text replace ms-word


【解决方案1】:

您可以将该范围复制到 Word 文档中,它会在其中找到内容 &lt;&lt;Table&gt;&gt;。像这样的...

Sub SendMail()
On Error GoTo Err_
    Dim Word      As Word.Application
    Dim Document  As Word.Document
    
    Set Word = New Word.Application
    Set Document = Word.Documents.Add("C:\Users\campoalv\Desktop\US-Dec.docx")
    
    With Document.Content
        If .Find.Execute("<<Table>>") Then
            Range("A24:F" & Range("A" & Rows.Count).End(xlUp).Row).Copy
            .Paste
        End If
    End With
    
    With New Outlook.Application
        With .CreateItem(olMailItem)
            .To = ""
            .Subject = "Test"
            
            With .GetInspector.WordEditor
                Document.Content.Copy
                .Content.Paste
            End With
            
            .Display
        End With
    End With
    
    Word.Quit 0
    
Exit_:
    Exit Sub
Err_:
    If Not Word Is Nothing Then
        If Not Word.Visible Then Word.Quit 0
    End If

    MsgBox Err.Number & ": " & Err.Description, vbCritical, "Error"
    Resume Exit_
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-13
    • 2019-05-20
    相关资源
    最近更新 更多