Hi,

My requirement I need to edit or replace content in the word document every time and save it to another location.
What I wanted is I want to simplify this through vb.net but stuck in somewhere I am doing mistake in the code itself (I am completly newbie).

I have created a form and I have inserted 2 controls i.e. RichTextBox and Button

If I Enter text in Richtextbox like below format word document is generating undesired results.

example:
add1
add2
add3
add4

result: add1 add2 add3 add4 add5

what I want is in what ever way I am giving input in the textbox the same output should be generated in word doc.

below is my faulty code:

Imports System.Runtime.InteropServices
Imports Microsoft.Office.Interop

Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click



        Dim objWordApp As Word.Application
        objWordApp = New Word.Application
        Dim objDoc As Word.Document
        Dim rng As String

        'Open an existing document.
        objWordApp.Documents.Open("C:\Users\Desktop\Sample.docx")
        objDoc = objWordApp.ActiveDocument

        'Find and replace some text.
        objDoc.Content.Find.Execute(FindText:="<Address>", _
            ReplaceWith:=rng, _
            Replace:=Word.WdReplace.wdReplaceAll)

            'Save and close the document.
            objWordApp.Documents.Item(1).Save()

            objWordApp.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
            objWordApp.Quit()
            objWordApp = Nothing
    End Sub

End Class

Thanks for everyone's help. :)

Dani AI

Generated

If your RichTextBox text is turning into a single line in Word, it is because Word’s Find/Replace does not treat VB newline characters as paragraph marks by default. For plain-text replacement (no RTF formatting), convert your VB newlines to Word paragraph marks (^p) and replace without using the clipboard. Also, avoid Selection; target a Range and use the Replacement object. Example:

' assume: Dim word As Word.Application, Dim doc As Word.Document
Dim replaceText = RichTextBox1.Text.Replace(vbCrLf, vbCr).Replace(vbLf, vbCr).Replace(vbCr, "^p")

With doc.Content.Find
    .ClearFormatting()
    .Replacement.ClearFormatting()
    .Text = "<address>"
    .Replacement.Text = replaceText
    .Wrap = Word.WdFindWrap.wdFindStop
    .MatchWildcards = False
    .Execute(Replace:=Word.WdReplace.wdReplaceAll)
End With

If you must preserve RichTextBox formatting and want to avoid the clipboard, save the RTF to a temp file and insert it at the found range:

Dim tmp = IO.Path.ChangeExtension(IO.Path.GetTempFileName(), ".rtf")
RichTextBox1.SaveFile(tmp, RichTextBoxStreamType.RichText)

Dim rng = doc.Content
If rng.Find.Execute("<address>") Then
    rng.Text = ""
    rng.InsertFile(tmp)
End If

IO.File.Delete(tmp)

Tips: ensure your placeholder is unique, release COM objects with Marshal.FinalReleaseComObject, and do not automate Word from ASP.NET server code (Office automation is unsupported in a service context). For server-side scenarios, consider file-format libraries (e.g., Open XML SDK, or a DOCX/PDF component) instead.

Recommended Answers

All 6 Replies

Still waiting for the solution.

I need Help!

Try using the & VBNewLine after each word or .Crlf that should do the trick for you.

The following has been tested and should work:

Requires the following:

Add reference to "Microsoft Word xx.x Object Library":

  • Click "Project"
  • Select "Add Reference"
  • Click "COM" tab
  • Select "Microsoft Word xx.x Object Library"

Add import statements:

  • Imports System.Runtime.InteropServices
  • Imports Word = Microsoft.Office.Interop.Word

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
        'use early binding
        Dim objWordApp As Word.Application = Nothing
    
        Try
    
            objWordApp = New Word.Application
    
            'Open an existing document.
            objWordApp.Documents.Open("C:\Temp\Sample.docx")
    
            'copy data to clipboard
            RichTextBox1.SelectAll()
            RichTextBox1.Copy()
    
            'find <address>
            objWordApp.Selection.Find.Execute("<address>")
    
            'copy richtext from clipboard
            objWordApp.Selection.PasteSpecial(DataType:= Word.WdPasteDataType.wdPasteRTF)
    
            'clear the clipboard
            Clipboard.Clear()
    
            'Save and close the document.
            objWordApp.Documents.Item(1).Save()
            objWordApp.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges)
    
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
    
            'quit Word
            If Not IsNothing(objWordApp) Then
                objWordApp.Quit()
                objWordApp = Nothing
            End If
    
        End Try
    End Sub
    

*Note: The font properties will be transferred from the RichTextBox as well.

Resources:
Find.Execute Method (Word)

  • ReplaceWith: "...To specify a graphic object or other nontext item as the replacement, move the item to the Clipboard..."

Selection.PasteSpecial Method (Word)

How to: Programmatically Search for and Replace Text in Documents

Transfer formatted RichTextBox into Microsoft Word

Word Object Model Overview (2010)

Word Object Model Reference

Ok. I will do it and try what is the outcome. Thank you @ cgeier

your code worked for me. As I am having basic knowledge of VB I need the code which you done it in very good manner. Thank you very much.

And can you please provide me the code along with above procedure how to save files into PDF.

I want to save above owrd file as PDF.

Thanks a lot

The following will replace "<address>" with the text contained in RichTextBox1 and save the document as a .pdf file. The original file will be unmodified:

        'use early binding
        Dim objWordApp As Word.Application = Nothing

        Try

            objWordApp = New Word.Application

            'Open an existing document.
            objWordApp.Documents.Open("C:\Temp\Sample.docx")


            'copy data to clipboard
            RichTextBox1.SelectAll()
            RichTextBox1.Copy()

            'find <address>
            objWordApp.Selection.Find.Execute("<address>")

            'copy richtext from clipboard
            objWordApp.Selection.PasteSpecial(DataType:=Word.WdPasteDataType.wdPasteRTF)

            'clear the clipboard
            Clipboard.Clear()

            'save as PDF
            objWordApp.ActiveDocument.SaveAs2("C:\Temp\Sample.pdf", Word.WdSaveFormat.wdFormatPDF)

            'Close the document.
            objWordApp.Documents.Close(Word.WdSaveOptions.wdDoNotSaveChanges)

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally

            'quit Word
            If Not IsNothing(objWordApp) Then
                objWordApp.Quit()
                objWordApp = Nothing
            End If

        End Try

Note: You will need to be using a version of Word that allows a file to be save as ".pdf".

Resources:
How do I convert Word files to PDF programmatically

Microsoft Office 2010: Primary Interop Assemblies Redistributable

"...By installing the Compatibility Pack in addition to Microsoft Office 2000, Office XP, or Office 2003, you will be able to open, edit, and save files using the file formats in newer versions of Word, Excel, and PowerPoint . The Compatibility Pack can also be used in conjunction with the Microsoft Office Word Viewer 2003, Excel Viewer 2003, and PowerPoint Viewer 2003 to view files saved in these new formats..."

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.