0
votes

I'm creating a Word VBA macro to insert a text frame containing an image and its caption, and then create a cross reference to it in the main document text.

But Word doesn't find the caption if it's in a text frame.

Here's illustrative code:

    Sub ShowMe()
    Dim items() As String
    items = ActiveDocument.GetCrossReferenceItems("Figure")
    MsgBox ("Found " & UBound(items))
    End Sub

If the caption is of a thing (say, a picture, table, or just a para) that's inline in the main document text it finds it. But if the caption is in a text frame or a text box, whether it's a caption para that I create within the text frame, or if I simply click the text frame and do 'Insert caption' (which actually creates a text box below the frame), I get zero.

I've tried creating the cross reference just by building the REF field manually, but it doesn't work reliably. I suspect there's some magic about the cross reference process creating a new hidden bookmark when required.

Any suggestions, please?

1
Why are you putting them in a text box? If you add a caption to a table/chart/picture with text wrapping Word adds a text frame (text frames and text boxes are two different things) to the caption so that it aligns with the image. Captions in text frames can be cross-referenced.Timothy Rylatt
Alternatively, insert both the item and its caption into a table. Depending on your preferences, that table can have one or two rows.macropod
Err, @TimothyRylatt, macropod - these are interesting suggestions, but don't address my issue. Certainly captions in text frames and text boxes (and tables in floating text boxes) can be cross-referenced. But captions in floating text frames or text boxes can be referenced manually using the cross reference dialog, but don't appear in the ActiveDocument.GetCrossReferenceItems list. How do I find them in VBA?CharlesW
Having just checked the suggestions I realized that in Office 365 Word no longer uses a text frame for floating captions but adds a text box instead. Using a text wrapped table as @macropod suggested definitely works. Essentially if your method of inserting captions doesn't work with the object model you adapt, and use a method that does.Timothy Rylatt
Fine, but I get the same problem with the approach @TimothyRylatt suggests. And captions that are in the main body text are unsuitable for my needs.CharlesW

1 Answers

0
votes

The solution I found was to move the caption paragraph out of the frame to the end of the main document using cut and paste, create the cross reference to it, then move it back again.

The code to do it is rather long, mainly since Word tends to be a bit inconsistent in cutting paragraphs. You can find it at https://github.com/charlesweir/WordImagesAndTables in AnchoredFrame.cls, function InsertCrossReferenceBesideAnchor

  • Charles