简体   繁体   English

如何将表格从 Excel 复制/粘贴到 Word 文档

[英]How to copy/paste tables from Excel to a Word document

I want to copy/paste tables from an Excel sheet toward a .docx.我想将表格从 Excel 工作表复制/粘贴到 .docx。 I have a word #tableauxvdd which I want to replace by my tables.我有一个单词#tableauxvdd,我想用我的表格替换它。

So I wrote this code所以我写了这段代码

     With word_fichier.Range
         With .Find
             .ClearFormatting
             .Replacement.ClearFormatting
             .Text = "#tableauxvdd"
             .Replacement.Text = "#tableauxvdd"
             .Forward = True
             .Wrap = wdFindStop
             .Format = False
             .MatchWildcards = True
             .Execute Replace:=wdReplaceNone
         End With
             If .Find.Found = True Then
                For i = 1 To nombre_de_vdd
                    Set tblRangeVdd = ThisWorkbook.Worksheets("Info vdd " & i).Range("A1:C6")
                    tblRangeVdd.Copy
                    .PasteExcelTable _
                        LinkedToExcel:=False, _
                        WordFormatting:=False, _
                        RTF:=False
                Next
             End If
     End With

But its not working.但它不起作用。 Here is the tables I need to copy/paste这是我需要复制/粘贴的表格表

And this is the result这就是结果在此处输入图像描述

And this is what i need :这就是我需要的: 在此处输入图像描述

Whenever you write code to automate Word you need to think through what steps you would take if you were performing the task in the UI.每当您编写代码来自动化 Word 时,您都需要考虑如果您在 UI 中执行任务会采取哪些步骤。

In a Word document, tables are always separated by a paragraph, so your code needs to do the same.在 Word 文档中,表格总是由段落分隔,因此您的代码也需要这样做。

For example:例如:

If .Find.Found = True Then
    For i = 1 To nombre_de_vdd
        Set tblRangeVdd = ThisWorkbook.Worksheets("Info vdd " & i).Range("A1:C6")
        tblRangeVdd.Copy
        .PasteExcelTable _
            LinkedToExcel:=False, _
            WordFormatting:=False, _
            RTF:=False
        .InsertParagraphAfter
    Next
End If

You'll also need to add the tables in reverse order, for example:您还需要以相反的顺序添加表格,例如:

If .Find.Found = True Then
    Dim tblRangeVdd As word.Range
    Set tblRangeVdd = .Duplicate
    With tblRangeVdd
        .Collapse wdCollapseEnd
        For i = nombre_de_vdd To 1 Step -1
            ThisWorkbook.Worksheets("Info vdd " & i).Range("A1:C6").Copy
            .PasteExcelTable _
                LinkedToExcel:=False, _
                WordFormatting:=False, _
                RTF:=False
            .InsertParagraphAfter
        Next
    End With
End If

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM