将单元格/表格从Excel复制并粘贴到Word模板(以及正确的位置)

时间:2018-09-20 12:34:08

标签: excel vba word-vba

我有以下代码:

Sub Excel2Word()
Dim BottomEquity As Range, BottomBond As Range
Dim WordApp As Word.Application
Set SB = Worksheets("SalesBrokerage")
Set WordApp = CreateObject("Word.Application")
WordApp.Documents.Open "C:\Customer\Templates\PIntern.dotx"
SB.Range("B3:G" & SB.Cells(SB.Rows.Count, 2).End(xlUp).Offset(1, 0).Row).Select
Selection.PasteExcelTable
HorizontalPosition = 10
VerticalPosition = 15
End Sub

我总是在Selection.PasteExcelTable遇到问题,显然HorizontalPositionVerticalPosition也不正确。

我要粘贴的Word模板如下所示:

                       Our Overview
Equities 
Bonds

我要做的等效操作是在Excel文档中复制所选范围,打开Word模板,将表格粘贴在“ equities”和“ bonds”之间,然后保存文档。

1 个答案:

答案 0 :(得分:0)

无需使用选择,只需复制并粘贴到适当的对象即可。

将搜索第一个Grave Character,并将其替换为您复制的表格。还保存并关闭了word文档。

Sub Excel2Word()
    Dim BottomEquity As Range, BottomBond As Range
    Dim WordApp As New Word.Application

    Set SB = Worksheets("SalesBrokerage")
    'Set WordApp = CreateObject("Word.Application") ' You already have reference, this is not needed.
    WordApp.Documents.Open "C:\Customer\Templates\PIntern.dotx"
    WordApp.Visible = True                          ' Added for testing to see document

    'Copy / Paste
    SB.Range("B3:G" & SB.Cells(SB.Rows.Count, 2).End(xlUp).Offset(1, 0).Row).Copy

    Dim oFindPos As Long
    WordApp.Documents(1).Application.Selection.Find.Execute findtext:="`"
    oFindPos = WordApp.Documents(1).Application.Selection.Start

    WordApp.Documents(1).Range(oFindPos, oFindPos + 1).Paste

    'Save & Close Word Doc
    WordApp.Documents(1).Save
    WordApp.Documents(1).Close
    WordApp.Quit
End Sub