Link to home
Start Free TrialLog in
Avatar of greenwatch
greenwatch

asked on

Word Automation insert a form field in a document

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.
Avatar of daffyduck14mil
daffyduck14mil

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.
Avatar of greenwatch

ASKER

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.


ASKER CERTIFIED SOLUTION
Avatar of daffyduck14mil
daffyduck14mil

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial