Index Value of FormField

G

Greg Maxey

Last week I thought that I had figured out a way to get the index value of a
formfield using VBA. Today I noticed that it fails if I have two or more
formfields in a table row. For some reason if I have a row of formfields in
a table, all of the formfields in the same row return the same value. Can
anyone explain why this isn't working:

Sub GetIndex()

Dim oDoc As Document
Set oDoc = ActiveDocument
oDoc.Variables("Index").Value = _
oDoc.Range(0, Selection.Bookmarks(1).Range.End).Bookmarks.Count
MsgBox oDoc.Variables("Index").Value
End Sub
 
D

Doug Robbins

Hi Greg,

I haven't found a work aroung yet, but the problem is caused by the way in
which Word handles Selections/Ranges that include information in a table and
information before a table.

Place a couple of paragraph returns in a document, then a table and then try
and select the paragraph returns and the first cell of the table. You
cannot do it, the whole row is selected. As a result, the count that is
being returned, includes all of the bookmarks in the row.

--
Please respond to the Newsgroup for the benefit of others who may be
interested. Questions sent directly to me will only be answered on a paid
consulting basis.

Hope this helps,
Doug Robbins - Word MVP
 
T

Tony Jollans

There are (at least) two issues here.

Firstly, whatever happens when selecting via the GUI, this is clearly a bug,
Range(0, 100).Bookmarks, say, does NOT contain a bookmark which starts at 110
and it is wrong that such a bookmark is included in the Count.

Knowing that this is what happens, however, at least means that code can be
written to handle the situation. HOWEVER, your basic logic is flawed because
Bookmarks(3), say, is not necessarily the third bookmark from the start of
the document; they just aren't numbered that way.

Enjoy,
Tony
 
T

Tony Jollans

Apologies, before someone else corrects me! Bookmarks in a Document aren't
numbered sequentially, but bookmarks in a Range are, so here's an amendment
to your code to work round Word's peculiarity:

Dim oDoc As Document
Set oDoc = ActiveDocument
oDoc.Variables("Index").Value = _
oDoc.Range(0, Selection.Bookmarks(1).Range.End).Bookmarks.Count
Dim i As Long
For i = oDoc.Variables("Index").Value To 1 Step -1
If oDoc.Range(0, Selection.Bookmarks(1).Range.End).Bookmarks(i).Start >
Selection.End Then
oDoc.Variables("Index").Value = oDoc.Variables("Index").Value - 1
Else
Exit For
End If
Next
MsgBox oDoc.Variables("Index").Value
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top