Pages

Sunday, September 12, 2010

How to copy RichTextBox contents to Word document

How to insert Rich Text Box Content to Word document using VBA

Let us have a form with a RichTextBox and a Command Button as shown below



The following VBA code will copy the Contents of RichTextBox to the First Paragraph of the ActiveDocument

Private Sub cmdCopyRTFContent_Click()
    
    Dim oRange As Word.Range            ' Word Range
    Dim sPath As String                 ' Temp Path
    
    Set oRange = ActiveDocument.Paragraphs(1).Range
    
    sPath = "c:\shasurdata\Temp.rtf"
    
    Open sPath For Output As 1
        Print #1, RichTextBox1.TextRTF
    Close #1
    
    oRange.ImportFragment sPath
    
End Sub


The program Exports the contents of RichTextBox to a RTF file and then imports to the Word document