Reputation: 367
Anyone got a clue how I can transfer text from one document to another without using the clipboard, but maintaining all formatting in the text (like bold and italics)?
Here's how I'm doing it at the moment (There is a lot of code in between these lines that open up documents in a directory for me, but I'm omitted them for now so I can get to the point):
Dim rng1, rng2, rngFound as Range
Dim FSO as Scripting.FileSystemObject
For Each File1 in FSO.GetFolder(Directory).Files
'...Open first Document and get cursor to Point A to mark the start of the text
Documents.Open(File1.Path)
Set rng1 = Selection.Range
'...Move cursor to point B to mark the end of the text
Set rng2 = Selection.Range
'...Combine the 2 points and capture everything in between into Clipboard
Set rngFound = (rng1.Start, rng2.Start)
rngFound.Copy
ActiveDocument.Close
'...Open up second Document and paste it in
Documents.Open(File2.Path)
Selection.PasteAndFormat (wdFormatSurroundingFormattingWithEmphasis)
ActiveDocument.Save
ActiveDocument.Close
Next
The Problem with doing it this way is that I can't use the clipboard while this is running (this loops in a directory of hundreds of documents so takes a while).
I'd love to find a way of doing this without the clipboard, but in such a way that keeps the formatting from one doc to the next (Important).#
Hope that makes sense, Thanks in advance :)
Upvotes: 1
Views: 872
Reputation: 938
Here's a solution using a temporary file and InsertFile
.
Replace Pgr
in the paths to get some folder that actually exists on your computer.
This is just a proof of concept. It opens "C:\Users\Pgr\AppData\Local\Temp\doc1.docx"
as a source document, gets it's second paragraph only, saves that as a temporary file, then goes back to the Target document (which is where this macro is running from) and uses InsertFile
to put the content there.
Sub CopyThroughTempFile()
Set targetdoc = ActiveDocument
Set sourceDoc = Documents.Open("C:\Users\Pgr\AppData\Local\Temp\doc1.docx")
Set rng2copy = sourceDoc.Paragraphs(2)
rng2copy.Range.Copy
sourceDoc.Range.Paste 'pastes replacing everything in the file
sourceDoc.SaveAs ("C:\Users\Pgr\AppData\Local\Temp\temp.docx")
targetdoc.Activate
Selection.InsertFile ("C:\Users\Pgr\AppData\Local\Temp\temp.docx")
End Sub
I hope this helps (you or someone...).
Upvotes: 2