Search code examples
vbams-worduserform

MS Word: Replace bookmark Text in a Userform instead of Adding using VBA


VBA Newbie here.

I've just created a userform that allows my team to create a cover letter.

The button below appears in the body of the document in an "Instruction" section. When they click on it, it shows my form which they need to fill out.

Private Sub EditFormButt_Click()
    CoverLetterForm.Show
End Sub

The Form currently has pre-filled placeholder text. I want my team to be able to replace the text. Right now, what happens is, when they click my "OK" Button (code to follow), the placeholder text remains, and their new text is added.

For example:

To: Mr. Paul Daniels Ms. Sarah Jones
21 New Order Street
London
England

Dear Mr. Paul Daniels Ms. Sarah Jones

Ms. Sarah Jones is the Placeholder Text, Mr. Paul Daniels is the updated text.

I need any new entries to replace whatever is in the Placeholder text, but not delete anything that hasn't been updated, as sometimes, they may only want to change the name of recipient but not the person's address. This is also useful if they want to correct any mistakes they may have made in spelling without having to start a totally new document.

Here is my OKButt Code:

Private Sub OKButt_Click()
    Dim bmRecName As Range
    Set bmRecName = ActiveDocument.Bookmarks("bmRecName").Range
    bmRecName.Text = Me.RecName.Value
    Dim bmRecAddress As Range
    Set bmRecAddress = ActiveDocument.Bookmarks("bmRecAddress").Range
    bmRecAddress.Text = Me.RecAddress.Value
    CoverLetterForm.Hide
End Sub

Thanks for your help :)


Solution

  • Simpler:

    Private Sub OKButt_Click()
    Dim bmRng As Range
    With ActiveDocument
      Set bmRng = .Bookmarks("bmRecName").Range
      bmRng.Text = Me.RecName.Value
      .Bookmarks.Add "bmRecName", bmRng
      Set bmRng = .Bookmarks("bmRecAddress").Range
      bmRng.Text = Me.RecAddress.Value
      .Bookmarks.Add "bmRecAddress", bmRng
      CoverLetterForm.Hide
    End With
    End Sub