Word Automation insert a form field in a document

greenwatch
greenwatch used Ask the Experts™
on
All withing Microsoft Word. I have created a form which is loaded and shown using VB code in the Autonew macro. It has about 20 named fields. I want to insert the values which the user enters in the form fields at specific pointd in the document. I know that I need to use bookmarks. I just need to know what code to use.

So suppose there are form fields Form_Contact, Form_Address and bookmarks in the document Doc_Contact and Doc_Address. How do I get the values which the user enters in the first two fields on the form into the two coresponding positions in the document.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Hi,

If you have a module (or form) in the template project, you can use the following sub to insert text at the bookmarks.

Public Sub InsertAtBookmark(ByVal sBookmark As String, ByVal sText As String)
  Dim rngCurrent As Word.Range
' ----------------------------
  On Error Resume Next
  Dim rngCurrent As Word.Range
' ----------------------------
  On Error Resume Next
  Set rngCurrent = ActiveDocument.Bookmarks(sBookmark).Range
  rngCurrent.InsertAfter (sText)
End Sub

Use it as follows:

InsertAtBookmark("Form_contact", txtContact.text)

That should do it. This piece of code is stripped from a larger routine, so it uses a range object. You can also use a single line, that says: ActiveDocument.Bookmarks(sBookmark).InsertAfter(sText)

Do observe that using ActiveDocument has one drawback. Should the user open a new document (existing or totaly new), the activedocument may not point to the right template. To counter this, catch the document object into a object you use in the form. Then use that object to manipulate the bookmarks.

Grtz.©

D.
Hi,

I made an error in pasting the code. The correct code is:

Public Sub InsertAtBookmark(ByVal sBookmark As String, ByVal sText As String)
 Dim rngCurrent As Word.Range
' ----------------------------
 On Error Resume Next
 Set rngCurrent = ActiveDocument.Bookmarks(sBookmark).Range
 rngCurrent.InsertAfter (sText)
End Sub

Grtz.©

D.

Author

Commented:
When I try .....

ActiveDocument.Bookmarks(sBookmark).InsertAfter(sText)

I get a message "Compile Error - Method or data memebr not found" and the word .InsertAfter is highlighted.


Hi,

Indeed, I stand corrected. Let me explain what happens:

The bookmarks collection is a collection of range objects. The InsertAfter function is a method of the range object. So, if you change the line to:

ActiveDocument.Bookmarks(sBookmark).Range.InsertAfter(sText)

It should work fine. Sorry for that second mistake. I'll go home now and eat.

Grtz.©

D.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial