Target image captions using a macro in MS Word

46 Views Asked by At

I'm currently working on a little macro for Word using VBA to scan a report and just highlight all the crossreferences. Now hihglighting the TypeFields that are references was quite easy. I can't seem to figure out, how to target the captions of the referenced images. I don't want them to be connected to each other (not yet) but even just finding them seems impossible. I now want to know, if it is even possible to target those little captions or if I am just missing something in the VBA documentation.

I've tried to use the InlineShapes.Caption, which resulted in nothing (InlineShapes works fine though, I can resize and delete images no problem). I've also tried to just select the Captions, but with using Selection I just end up with the images again. I have also tried to extract the caption via InlineShape.Text, no results. As well as InlineShape.Caption.Text, and InlineShape.CaptionLabel.Text, which are all not recognised objects (if I remember correctly, I tried so much)

This is the little code that I came up with, which finds references, and highlights them, as well as delete images.

Sub ReferenceHighlight()
    'Define the range as the whole document
    Dim docRange As Range
    Set docRange = ActiveDocument.Range
    'Define all Fields in the Document
    Dim fld As Word.Field
    'Define an incremental integer
    Dim i As Integer
    i = 1
    'Define all Pictures in the Document
    Dim image As InlineShape
    For Each image In docRange.InlineShapes
        image.Delete
    Next image
    For Each fld In docRange.Fields
        If fld.Type = wdFieldRef Then
             fld.Result.HighlightColorIndex = wdYellow
        End If
    Next fld
End Sub
1

There are 1 best solutions below

0
taller On BEST ANSWER

Pls try.

    For Each fld In docRange.Fields
        If fld.Type = wdFieldRef Then
            fld.Select
            Selection.Expand xlLine
            Selection.Range.HighlightColorIndex = wdYellow
        End If
    Next fld

  • A more efficient way to highlight captions. (@Timothy Rylatt posts the comment before my answer)
Sub HightLightCaption()
    Options.DefaultHighlightColorIndex = wdYellow
    With Selection.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Style = ActiveDocument.Styles("Caption")
        .Text = ""
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchByte = True
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        .Replacement.Highlight = True
        .Execute Replace:=wdReplaceAll
    End With
End Sub