Search code examples
excelvbams-wordcopybookmarks

Copy paste a table from excel to a bookmarked location in Word using VBA


I am trying to Copy and table from a sheet in excel and paste it into a word document, in a specific place, using VBA

I have tried the code below:

Sub Copypastetabe()

Dim strPath As String

'Set path via this excel workbook

strPath = ThisWorkbook.Path & "\" & "Morning Snapshot1" & ".docx"

Dim objWord As Object

Dim docWord As Object

'copy the date table to go to word doc

Sheets("Sheet4").Range("A1:F6").Copy

'define and open word doc

Set objWord = CreateObject("Word.Application")

objWord.Visible = True

Set docWord = objWord.Documents.Open(fileName:=strPath, ReadOnly:=False)

'Select bookmark in word doc

docWord.Bookmarks(BondYields).Select

Selection.Paste

End Sub

I get the error

Runtime error 5941 "The requested Member of the collection does not exist"

The bookmark exists in this word document under this name, so i'm a bit stuck

Please can anyone help?


Solution

  • 'Select bookmark in word doc
    
    docWord.Bookmarks(BondYields).Select
    
    Selection.Paste
    

    Should be:

    'Select bookmark in word doc
    
    docWord.Bookmarks(“BondYields”).Select
    
    objWord.Selection.Paste
    

    Or better still:

    ‘Paste into bookmark in Word doc
    
    docWord.Bookmarks("BondYields").Range.Paste