简体   繁体   中英

copy a table, specify its location from excel to word using vba

I used this code to copy a table from excel to word

    Sub exceltoword()
Dim rangeToCopy As Range
Set rangeToCopy = Range("A1").CurrentRegion
Dim wordApp As Word.Application
Set wordApp = New Word.Application
wordApp.Visible = True
Dim wordDoc As Word.Document
Set wordDoc = wordApp.Documents.Open("C:\Users\mohammad.taha\AppData\Roaming\Microsoft\Templates\ARABBANK -SALARIES STATEMENT.dotx")
wordDoc.Application.Selection.Find.Text = "H"
wordDoc.Application.Selection.Find.Execute
wordDoc.Application.Selection.MoveDown Unit:=wdLine
rangeToCopy.Copy
wordDoc.Words(1).PasteExcelTable False, False, False
End Sub

but the table gets pasted into the first line of the document, I want to paste the table to a specific location in the middle of the document, how should I modify this code?

Try to use the code below:

Sub exceltoword()
    Dim rangeToCopy As Range
    Set rangeToCopy = Range("A1").CurrentRegion
    Dim wordApp As Word.Application
    Set wordApp = New Word.Application
    wordApp.Visible = True
    Dim wordDoc As Word.Document
    Set wordDoc = wordApp.Documents.Open("C:\Users\mohammad.taha\AppData\Roaming\Microsoft\Templates\ARABBANK -SALARIES STATEMENT.dotx")
    wordDoc.Application.Selection.Find.Execute "H"
    wordApp.Selection.MoveRight Unit:=wdCharacter, Count:=1
    wordApp.Selection.TypeParagraph
    wordApp.Selection.TypeParagraph
    rangeToCopy.Copy
    wordApp.Selection.PasteExcelTable False, False, False
    End Sub

I've added two paragraphs. If in your template it does not look good, you can remove it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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