Alison Harding
Alison Harding

Reputation: 23

Pasting a table into open Word document at a bookmark

I have searched a fair bit on this and other forums but I can't get code to work. I know this is user error - I am learning/self-taught at this.

What I want is to copy a (admittedly large) table in a specific Excel worksheet into an already-open Word document, at a specific point. I have seen this done using a keyword search but I would prefer to use a bookmark (and I've made the bookmark thing work!) purely because it's not visible to the end user. I'm trying to automate the creation of a document as much as possible.

The below code works, but I can only get it to work when the Word document in question is closed. If I try to run this sub when the word doc is open, it just tries to re-open it and of course can't. I can't find a neat bit of code that allows me to paste data into an already-open document.

Also, I can make this work for one value, but not for a range (i.e. the table I want to paste).

Sub ExcelRangeToWord()


Dim objWord As Object
Dim ws As Worksheet

    Set ws = ThisWorkbook.Sheets("Summary")
    Set objWord = CreateObject("Word.Application")

    objWord.Visible = True


'Optimize Code
  Application.ScreenUpdating = False
  Application.EnableEvents = False


  'open the word doc
      objWord.Documents.Open "K:\Exeter Office\Quotebuilder project\testbed\test.docx" 'change as required


'pastes the value of cell I19 at the "heatlosses" bookmark
    With objWord.ActiveDocument
        .Bookmarks("heatlosses").Range.Text = ws.Range("I19").Value
    End With

'Optimize Code
Set objWord = Nothing
  Application.ScreenUpdating = True
  Application.EnableEvents = True

'Clear The Clipboard
  Application.CutCopyMode = False

End Sub

I'm trying to tackle this one step at a time, cos then I have half a chance of understanding things a bit better...

If I try and copy/paste a range, instead of just one value, I was using Currentregion to select all used cells surrounding B19:

With objWord.ActiveDocument
        .Bookmarks("heatlosses").Range.Text = Range("B19").CurrentRegion
    End With

All this does is paste the word "True" into Word.

I am baffled. Please, can anyone offer assistance?

Upvotes: 2

Views: 6346

Answers (1)

user1641172
user1641172

Reputation:

Use the code below to achieve what you require:

Sub CopyToWord()

    Dim wApp, wDoc

    'Get the running word application
    Set wApp = GetObject(, "Word.Application")

    'select the open document you want to paste into
    Set wDoc = wApp.documents("test.docx")

    'copy what you want to paste from excel
    Sheet1.Range("A1").copy    

    'select the word range you want to paste into
    wDoc.bookmarks("heatlosses").Select

    'and paste the clipboard contents
    wApp.Selection.Paste

End Sub

Upvotes: 2

Related Questions