Pasting a table into open Word document at a bookmark

你说的曾经没有我的故事 提交于 2021-01-06 00:15:26

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/33606456/pasting-a-table-into-open-word-document-at-a-bookmark

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!