PDA

View Full Version : Solved: Iterate Captions



Adamski
05-13-2011, 08:18 AM
How do I loop through all the Table, Figure and\or Equation captions in a Word document?

Thanks

Frosty
05-13-2011, 11:48 AM
Depends on how they are set up. In native word, I believe it sets up a single paragraph with the following properties:
1. Style named "Caption"
2. Text in that paragraph ("Table" or "Equation" or "Figure")
3. And last it uses a Sequence Field, with the same name ("Table" or "Equation" or "Figure").

So there are a number of ways to do it...

You could iterate through all of the .Fields in the document, checking the .Type to see if it's a wdFieldSequence type, then check the .Code of that field and see if it contains one of your key phrases.

Or you could set up a Find which searches for the Caption style and maybe some of the specific text in the caption...

It depends on what you want to do while you're in your loop, whether it's the same for each of the different caption types, and also depends on how much coding you've already done.

So, what do you want to do? The exact answer to your question is probably best described this way, but this may not be the most efficient way of doing it (i.e., a good wildcard replace all may accomplish what you want to do a lot faster).


Public Sub IterateCaptions()
Dim oField As Field
Dim sCode As String
Dim bFoundOne As String

For Each oField In ActiveDocument.Fields
If oField.Type = wdFieldSequence Then
bFoundOne = False
sCode = oField.Code

'see if it's a caption sequence field
If InStr(sCode, "Table") <> 0 Then
bFoundOne = True
End If
'see if it's a caption sequence field
If InStr(sCode, "Equation") <> 0 Then
bFoundOne = True
End If
'see if it's a caption sequence field
If InStr(sCode, "Figure") <> 0 Then
bFoundOne = True
End If
'now what?
If bFoundOne Then
oField.Select
Stop
End If
End If
Next
End Sub

Adamski
05-18-2011, 02:24 AM
Thanks.

I was expectiong a "Captions" collection in the object model due to the insert caption and cross reference features built into word. Guess that just looks at fields then.

Frosty
05-18-2011, 11:21 AM
Would be nice, wouldn't it?

But that's not how MS set it up. If this is the first time you're encountering a limitation that seems like it would have been "so easy" for MS to program it differently, count yourself lucky!

:)