I need to copy rtf-formatted text from one word document into another (into table cell) by vbscript from 3rd party application. Following code works well if pasting into the word document, but OUTSIDE of table. Inside the table it loses its formatting. Here is the workflow. I have multiple rtf files. I need to open them one by one and copy its content into the second-final document, each rtf file into separate table cell. I tried following options but none of them worked.
Do you have any idea why I cannot paste RTF into the table cells?
Set objWord = CreateObject("Word.Application") objWord.Visible = True Set objDocument = objWord.Documents.Add() Set objSelection = objWord.Selection Set objTempWord = CreateObject("Word.Application") objTempWord.Visible = True Set objTempDocument = objTempWord.Documents.Open("C:\Users\odivis\Desktop\temp_rtf.rtf") Set objTempSelection = objTempWord.Selection Set objRange = objSelection.Range objDocument.Tables.Add objRange, 2, 2 Set objTable = objDocument.Tables(1) objTempSelection.WholeStory objTempSelection.Copy objTable.Cell(1, 1).Range.PasteAndFormat(16) ' 16 = wdFormatOriginalFormatting 'objTable.Cell(1, 1).Range.PasteSpecial , , , , 1 ' THIS ONE WORKS THE SAME AS PREVIOUS LINE - NO RTF FORMATTING RETAINED 'objTable.Cell(1, 1).Range.InsertFile "C:\temp_rtf.rtf", , false 'objSelection.EndKey 6 'objSelection.TypeParagraph() 'objSelection.Paste objTable.AutoFormat(16)
I also tried to insert RTF file directly into the final word document, but with no luck. Please see slightly modified previous code (only different lines used)
Set objWord = CreateObject("Word.Application") objWord.Visible = True Set objDocument = objWord.Documents.Add() Set objSelection = objWord.Selection 'Set objTempWord = CreateObject("Word.Application") 'objTempWord.Visible = True 'Set objTempDocument = objTempWord.Documents.Open("C:\Users\odivis\Desktop\temp_rtf.rtf") 'Set objTempSelection = objTempWord.Selection Set objRange = objSelection.Range objDocument.Tables.Add objRange, 2, 2 Set objTable = objDocument.Tables(1) 'objTempSelection.WholeStory 'objTempSelection.Copy 'objTable.Cell(1, 1).Range.PasteAndFormat(16) ' 16 = wdFormatOriginalFormatting 'objTable.Cell(1, 1).Range.PasteSpecial , , , , 1 ' THIS ONE WORKS THE SAME - NO RTF FORMATTING RETAINED objTable.Cell(1, 1).Range.InsertFile "C:\temp_rtf.rtf", , false 'objSelection.EndKey 6 'objSelection.TypeParagraph() 'objSelection.Paste objTable.AutoFormat(16)
And here is my sample rtf file:
{\rtf1\ansi\ansicpg1250\deff0\deflang1029{\fonttbl{\f0\fnil Times New Roman;}{\f1\fnil\fcharset238{\*\fname Times New Roman;}Times New Roman CE;}{\f2\fnil\fcharset0 Times New Roman;}} {\colortbl ;\red255\green0\blue0;} {\*\generator Msftedit 5.41.21.2510;}\viewkind4\uc1\pard\cf1\f0\fs20 testing string\par \b on multiple\cf0\f1\par rows\lang1033\b0\f2\par }
I will welcome any advice in VBA or VBS (preferred).
Thanks in advance,
Ondrej