Reputation: 27
I'm trying to copy text from a table cell into a new document. Everything works fine except that the pasted text has lost the style from the copied text. The style is a new paragraph style with some regular formatting choices, such as font type, font size and text indent. To paste I use...
Documents.Add.Content.PasteAndFormat (wdFormatOriginalFormatting)
I think i know where the problem lies. If I copy the whole table cell and paste, it will keep the formatted text with the correct style for all paragraphs. But it will paste it within a table cell and I just wanted the text without the table.
So I exclude the "table cell end mark (looks like a sun)" when copying. Then it will only paste the text (without the table as I wan't it to do) but the last paragraph loses the style.
If I add an extra paragraph mark (press Enter) when standing in the end of table cell and copy the cell without the "table cell end mark", it works like I wan't it to do...almost. The destination document has no table (yes!) and all paragraphs has the correct style (yes!), but also an unwanted extra paragraph mark in the end. And of course an unwanted extra empty paragraph in the table cell.
Any suggestions how to solve it?
Upvotes: 0
Views: 639
Reputation: 25693
First of all, you should only use Copy/Paste if there's no alternative. For this, the Range.FormattedText property works, so copy/paste isn't needed.
Since you don't give good repro steps, I'm not sure whether the following is exactly right, but it works for the scenario I tested. I created a table in a document. The text I want to re-use in another document is in the second cell of the first row (Cell(1,2)). I created a paragraph style and applied it to the cell. I use the cell Range to pick up this content, and also get the number of characters in the Range.
I then assign the Range.FormattedText to the Content.FormattedText of the new document. As you say, this brings along a Chr(13), so I then remove that character (inumchars-1) from the text. The original style is brought into the target document, there is only the one paragraph mark (and that is formatted with the imported style, as it should be).
Sub CellContentToNewDoc()
Dim rng As word.Range
Dim rngNew As word.Range
Dim newDoc As word.Document
Dim lNumChars As Long
Set rng = ActiveDocument.Tables(1).Cell(1, 2).Range
inumchars = Len(rng)
Set newDoc = Documents.Add
Set rngNew = newDoc.content
rngNew.FormattedText = rng.FormattedText
rngNew.Characters(inumchars - 1).Delete
End Sub
Upvotes: 1