Search code examples
vb.netms-wordrtfbookmarks

Insert RichText (From RichTextBox, RTF File, OR Clipboard) into Word Document (Bookmarks or Find/Replace)


To summarize what I'm attempting to do, I work for a non-profit organization that sends out acknowledgement letters when someone donates money to us (a thank you, basically). We have multiple different letters that are written every month and sent to IS to "process". I would like to make this as efficient and use as little time as possible for IS, so I've created a program in VB.NET that takes content and pastes it into a template using Word bookmarks, updates a table in SQL so that the letter can be tested with live data, and sends an e-mail to the Production department letting them know to test the letter. It works fully, except...

I cannot for the life of me figure out how to retain RTF (RichText) when I insert the content into the letter template.

I've tried saving the content of the RichTextBox as an RTF file, but I can't figure out how to insert the RTF file contents into my document template and replace the bookmark.

I've tried using the Clipboard.SetText, odoc......Paste method, but it's unreliable as I can't accurately state where I'd like the text to paste. The find/replace function isn't very helpful because all of the bookmarks I'm trying to replace are within text boxes.

I'd show some code, but most of it has been deleted out of frustration for not working. Either way, here's some code I've been working with:

Private Sub testing()
        strTemplateLocation = "\\SERVER\AcknowledgementLetters\TEST\TEMPLATE.dot"
        Dim Selection As Word.Selection
        Dim goWord As Word.Application
        Dim odoc As Word.Document

        goWord = CreateObject("Word.Application")
        goWord.Visible = True
        odoc = goWord.Documents.Add(strTemplateLocation)

        Clipboard.Clear()
        Clipboard.SetText(txtPreD.Rtf, TextDataFormat.Rtf)
        odoc.Content.Find.Execute(FindText:="<fp>", ReplaceWith:=My.Computer.Clipboard.GetText)

        'Code for looping through all MS Word Textboxes, but didn't produce desired results
        For Each oCtl As Shape In odoc.Shapes
            If oCtl.Type = Microsoft.Office.Core.MsoShapeType.msoTextBox Then
                oCtl.TextFrame.TextRange.Text.Replace("<fp>", "Test")
                goWord.Selection.Paste()
            End If
        Next

        'Clipboard.Clear()
        'Clipboard.SetText(txtPostD.Rtf, TextDataFormat.Rtf)
        'odoc.Content.Find.Execute(FindText:="<bp>", ReplaceWith:="")
        'goWord.Selection.Paste()

        MsgBox("Click Ok when finished checking.")

        odoc.SaveAs2("\\SERVER\AcknowledgementLetters\TEST\TEST.docx")
        odoc = Nothing
        goWord.Quit(False)
        odoc = Nothing
        goWord = Nothing
    End Sub

...and here is the default code for setting bookmarks. This works perfectly as long as formatting is not required:


Private Sub SetBookmark(odoc As Object, strBookmark As String, strValue As String)
    Dim bookMarkRange As Object


    If odoc.Bookmarks.Exists(strBookmark) = False Then
        Exit Sub
    End If

    bookMarkRange = odoc.Bookmarks(strBookmark).Range


    If ((Err.Number = 0) And (Not (bookMarkRange Is Nothing))) Then

        bookMarkRange.text = strValue

        odoc.Bookmarks.Add(strBookmark, bookMarkRange)

        bookMarkRange = Nothing
    End If
End Sub

TL;DR - Need formatted text (Example: "TEST") to be inserted into a Word document either as a bookmark or as a replacement text.

Expected results: Replace "fp" (front page) bookmark with "TEST" including bold formatting. Actual results: "fp" is not replaced (when using clipboard and find/replace method), or is replaced as "TEST" with no formatting.


Solution

  • I figured it out! I had to do it a weird way, but it works.

    The following code saves the RichTextBox as an .rtf file:

    RichTextBoxName.SaveFile("temp .rtf file location")
    

    I then used the following code to insert the .rtf file into the bookmark:

    goWord.ActiveDocument.Bookmarks("BookmarkName").Select()
    goWord.Selection.InsertFile(FileName:="temp .rtf file location")
    

    I then deleted the temp files:

    If My.Computer.FileSystem.FileExists("temp .rtf file location") Then
        My.Computer.FileSystem.DeleteFile("\temp .rtf file location")
    End If