Paste from Range Object to Word document - vba

How do I paste without pulling from the clipboard?
(The code examples are excerpts from Googling and recording.)
My VBA code populates a section of my document from a form. Before loading the next form, it copies that section's contents to an object.
The code goes on to further populate the document. When done, the user can choose the "Next Page" control which generates a new page.
I want to paste the object I saved to the beginning of that new page.
My code up to the point of the paste.
Sub waiverCopy()
Dim objRange As Range
'Capture first section of document (waiver with names etc. populated)
Set objRange = ActiveDocument.Range(Start:=0, End:=ActiveDocument.Sections(1).Range.End)
Debug.Print objRange 'DOES PRINT contents in immediate window
' continue populating rest of current page '
Selection.EndKey Unit:=wdStory 'position to end of document (i.e. current page)
Selection.InsertBreak Type:=wdPageBreak 'start new page
' Nothing of the myriad of things I've tried will paste the contents of objRange on new page
End Sub

If you don´t want to use the clipboard, all you are missing is to insert the range object on the current Selection position (Selection.FormattedText = objRange) just after creating the Page Break.
Sub Copy()
Dim objRange As Range
'Capture first section of document (waiver with names etc. populated)
Set objRange = ActiveDocument.Range(Start:=0, End:=ActiveDocument.Sections(1).Range.End - 1)
' continue populating rest of current page '
Selection.EndKey Unit:=wdStory 'position to end of document (i.e. current page)
Selection.InsertBreak Type:=wdPageBreak 'start new page
Selection.FormattedText = objRange
' Don´t forget to clean memory
Set objRange = Nothing
End Sub
Please do not forget to clean memory with Set objRange = Nothing.

Related

Copy table from Word and paste into another Word document

I'm trying to open a Word Document and copy the whole table inside it and then paste it into another already-open document after a specific heading/bookmark (that I have bookmarked in the document). Then finally prompt the user to save the document with the newly pasted table.
Examples seen online are Excel-to-Word or Word-to-Excel; I need Word-to-Word.
I'm able to pull up the first document (I think it successfully copies it, too--I haven't tested it), but when it activates the second document, it stops and gives an error that it doesn't have an object assigned.
The debugger highlights Set WrdRng = Active.Bookmarks("AppendixA").Range.
Sub TEST()
'
' Declare Table Document Var as Object
Dim tb As Object
Dim bk As Bookmark
Dim WrdRng As Range
'
'
'Set up Word Application
Set tb = CreateObject("Word.Application")
tb.Visible = True
'Opens Pre-Saved Document & activates it to use
tb.Documents.Open "C:\ Desktop\Table.dotm"
tb.Activate
Selection.WholeStory
'ActiveDocument.Tables(1).Select
Selection.Font.Name = "Calibri"
Selection.Copy
'Activate Rolling Trend Report Document and Paste
Windows("TEST - Compatibility Mode").Activate
' where the error occurs and the debugger highlights
Set WrdRng = Active.Bookmarks("AppendixA").Range
'Paste to Bookmark
With WrdRng
Selection.InsertAfter
End With
'Save Completed Report to Desktop
ChangeFileOpenDirectory "C: \Desktop\"
ActiveDocument.SaveAs2 FileName:="TEST.docm", _
FileFormat:=wdFormatXMLDocumentMacroEnabled
'
'
'
End Sub
Your code is failing because Set WrdRng = Active.Bookmarks("AppendixA").Range should be Set WrdRng = ActiveDocument.Bookmarks("AppendixA").Range
However, your code is badly written, will also fail in other places and will create an extra instance of Word.
The code below is to run from Word
Sub TEST()
'store a pointer to the document you wnat to insert table into
'assumed to be currently active document
Dim targetDoc As Document
Set targetDoc = ActiveDocument
'Open Pre-Saved Document
Dim tblDoc As Document
Set tblDoc = Documents.Open("C:\ Desktop\Table.dotm")
Dim source As Range
Set source = tblDoc.Content
'exclude the paragraph that comes after the table
source.MoveEnd Unit:=wdCharacter, Count:=-1
source.Font.Name = "Calibri"
Dim appxA As Range
Set appxA = targetDoc.Bookmarks("AppendixA").Range
appxA.Collapse wdCollapseEnd
'transfer the text and close the source document
appxA.FormattedText = source.FormattedText
tblDoc.Close wdDoNotSaveChanges
'it is necessary to pass the full file path to the SaveAs command
ActiveDocument.SaveAs2 FileName:="C: \Desktop\TEST.docm", _
FileFormat:=wdFormatXMLDocumentMacroEnabled
End Sub

VBA in Word: How to count number of paragraphs in clipboard content

I am trying to write a VBA script to help me with some repetitive operations in a larger Word document. As part of this I need to know how many paragraphs are in a piece of text copied from another word document into the clipboard. (The steps that follow in my intended procedure depend on the paragraph counts.)
I tried this (see below), but got stuck with my approach, as easily visible from my comments in the script:
Sub InsertMultiPara()
'Declarations
Dim MyData As MSForms.DataObject
Dim intNumPara As Integer
Dim strClip As Variant
'Fill them
Set MyData = New MSForms.DataObject
MyData.GetFromClipboard
strClip = MyData.GetText
'Continuing my ideas... various experiments
'OFF intNumPara = MyData.Paragraphs.Count
'Error: "Object dosn'nt support this property or method"
'OFF intNumPara = strClip.Paragraphs.Count
'Error: "Object required"
'Paste the Clipboard content
Selection.PasteSpecial Link:=False, DataType:=wdPasteText, Placement:=wdInLine, DisplayAsIcon:=False
'Expand selection to everything just pasted:
Selection.MoveUp Unit:=wdParagraph, Count:=intNumPara, Extend:=wdExtend
'Do some other stuff with that range
Application.Run MacroName:="Normal.MyMacros.Something-nice-and-useful"
End Sub
But, as you see in the comments underneath the 'OFF commented lines: this does not work as I thought it would.
So, actually simple question: how can I implement a pragraph count on stuff that sits in the clipboard (and definitely has paragraphs, as they are there when the clipboard content is pasted).
Inspired by Cindy Meister's comment (above) I then found the following solution (which includes first creating a new Word document object, then pasting the clipboard content into it, then reading out its paragraph number):
Sub InsertAndProcessMultipleParagraphs()
'Declarations
Dim MyData As MSForms.DataObject
Dim intNumPara As Integer
Dim objDoc
'Fill them objects
Set MyData = New MSForms.DataObject
MyData.GetFromClipboard
Set objDoc = Application.Documents.Add
objDoc.ActiveWindow.Visible = False
'Put clipboard contents into the new document object
Documents(objDoc).Activate
Selection.PasteSpecial Link:=False, DataType:=wdPasteText, Placement:=wdInLine, DisplayAsIcon:=False
'Read out paragraph number in that document
intNumPara = Documents(objDoc).Paragraphs.Count
'Close that document (without nasty questions)
Documents(objDoc).Close SaveChanges:=wdDoNotSaveChanges
'By some miracle we should now be back in Word's original target window...
'Tests show that in practice this is the case.
'Paste the Clipboard content into target document at current cursor position
Selection.PasteSpecial Link:=False, DataType:=wdPasteText, Placement:=wdInLine, DisplayAsIcon:=False
'Expand selection to cover all the paragraphs inserted
Selection.MoveUp Unit:=wdParagraph, Count:=intNumPara, Extend:=wdExtend
'Do somethign nice and useful with these paragraphs
Application.Run MacroName:="Normal.MyMacros.Do-someting-nice-and-useful"
End Sub
I feel, however, a bit disappointed that I have to swing such large and heavy mallet as creating an entire new document object in Word just to count those paragraphs. Creating a doc, switching over to it, pasting stuff there, counting paragraphs, closing the doc... that's a lot of operations for a very basic thing. Isn't there any more lightweight object available that could take the clipboard content and whose paragraph number I then could read out?
Perhaps I will try also the other method: count paragraph marks (carriage returns or so) in the string that can be retrieved from the MyData object...
In order to count the paragraphs of content in the Clipboard, using the Word object model, it's first necessary to place that content in a Word document. The Clipboard is not part of Word and doesn't "understand" Word's syntax.
While this can be done use Selection and Activate it's more efficient and less "annoying" to work with the Word objects, instead. In this case, declare a Document object and set the document being added to it. Then it's possible to always use this object variable - no need to activate it, no need to use Documents(index) to address that document.
Also, I'd tend to put these steps in a separate procedure that returns the number of paragraphs. Generally, this makes code easier to read and to maintain.
For example:
Function InsertAndProcessMultipleParagraphs() As Long
'Declarations
Dim MyData As MSForms.DataObject
Dim intNumPara As Integer
Dim objDoc as Word.Document
Dim rng as Word.Range
'Fill them objects
'?Probably not needed for this approach?
' Set MyData = New MSForms.DataObject
' MyData.GetFromClipboard
Set objDoc = Application.Documents.Add
objDoc.ActiveWindow.Visible = False
'Put clipboard contents into the new document object
Set rng = objDoc.Content
rng.PasteSpecial Link:=False, DataType:=wdPasteText, Placement:=wdInLine, DisplayAsIcon:=False
'Read out paragraph number in that document
intNumPara = objDoc.Paragraphs.Count
'Close that document (without nasty questions)
objDoc.Close SaveChanges:=wdDoNotSaveChanges
InsertAndProcessMultipleParagraphs = intNumPara
End Function
Sub MacroThatUsesTheInfo
Dim intNumPara as Long
intNumPara = InsertAndProcessMultipleParagraphs
'Paste the Clipboard content into target document at current cursor position
Selection.PasteSpecial Link:=False, DataType:=wdPasteText, Placement:=wdInLine, DisplayAsIcon:=False
'Expand selection to cover all the paragraphs inserted
Selection.MoveUp Unit:=wdParagraph, Count:=intNumPara, Extend:=wdExtend
'Do something nice and useful with these paragraphs
Application.Run MacroName:="Normal.MyMacros.Do-someting-nice-and-useful"
End Sub

How to use macro to highlight inserted content in a word doc?

I want to highlight all the inserted/added content(from the tracked changes) in a word file. How am I suppose to use macro to find all the inserted/added content? For example, in the below screenshot:
the words blue yellow And amusing pink and hello should all be highlighted after running the macro. And the macro should also be able to work smoothly when running a relatively big Word file with all different tracked changes. Below is the macro content to highlight the content to be yellow, but I don't know how to find the inserted content as I'm not familiar with Macro. = =
The Sub Macro1()
'
' Macro1 Macro
'
'
Options.DefaultHighlightColorIndex = wdYellow
Selection.Range.HighlightColorIndex = wdYellow
End Sub
Thank you very much in advance!
You can try using the Revisions Object (Word)
Sub HighlightInsertedRevision()
Dim myRevision As Revision
Dim currentDoc As Word.Document
Set currentDoc = Application.ActiveDocument
'Set the selection range
currentDoc.ActiveWindow.Selection.HomeKey Unit:=wdStory
'Optimise for loop
Application.ScreenUpdating = False
'Loop all revisions in current document
For Each myRevision In currentDoc.Revisions
With myRevision
'Check if revision type is inserted revision
If .Type = wdRevisionInsert Then
.Range.HighlightColorIndex = wdYellow
End If
End With
Next
Application.ScreenUpdating = True
End Sub
More Information on MSDN: Revisions Object (Word)

How to temporarily open a Word document and use it to copy-paste a range?

I have formatted cells that I wish to copy and paste into an html form.
If I copy the contents to a Word document and paste them from there to an html form, it works.
If I copy the contents directly from the spreadsheet into the html form, the formatting is lost.
If the range is in the clipboard after copying from a Word document, I can paste it to the html form.
I need a way to copy the range to clipboard and retain the formatting. Since from Word it works, that's where I'm starting... but if there is another way...
I'm thinking of either an embed word file, or a hidden one.
Copy cell, paste there, select all and copy from there. Afterwards, close/discard it.
EDIT: Managed to get some code... but it worked, then stopped, then worked again... no idea why...
Sub TempDoc()
Dim WDApp As Word.Application
Dim WDDoc As Word.Document
Application.ScreenUpdating = False
Set WDObj = Sheets("Text2Form").OLEObjects("WDOC")
WDObj.Activate
WDObj.Object.Application.Visible = False
Set WDApp = GetObject(, "Word.Application")
Set WDDoc = WDApp.ActiveDocument
WDApp.Visible = False
Worksheets("Text2Form").Cells(12, 4).Copy
WDApp.Selection.Goto What:=wdGoToLine, Which:=wdGoToLast
WDApp.Selection.PasteSpecial xlPasteValues
WDApp.ActiveDocument.Content.InsertAfter vbNewLine
Worksheets("Text2Form").Cells(14, 4).Copy
WDApp.Selection.Goto What:=wdGoToLine, Which:=wdGoToLast
WDApp.Selection.PasteSpecial xlPasteValues
WDDoc.Content.Copy
WDDoc.Content.Delete
WDApp.Quit
Application.ScreenUpdating = True
End Sub
Have you tried right-clicking on the cell you wish to paste into, and clicking "Paste Special"?

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?
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