0
votes

I need a way to get an image's Alt Description (specified in HTML) into the Word DOCX image's Caption. This needs to be done with many images in a document, so a macro would be best.

Assume an HTML doc with an img tag similar to this

<img src="http://www.example.com/path/to/image/picture01.jpg" 
title="picture 01 title" 
alt="this is alt text" 
caption="this is a caption field">

This HTML doc is imported into Word 2010 (via File, Open). The image will show in the doc.

Now, how to get the 'title' attribute (which shows up in the Format Picture's Alt-Text dialog as the Description - see screenshot below) into the image's Caption?

Note that the caption parameter in the image tag is not converted to a Word Caption for that image.

Sample Alt-Text dialog for an image which shows the image's alt value as the Description enter image description here

2

2 Answers

0
votes

Yes, I think you've hit on a good way to make the conversion. Glad you were able to find it!

The code below will loop all the InlineShapes in the document and, if the Alternative Text is not empty, create a caption using that text.

InsertCaption is only available in VBA for InlineShapes. The user can insert captions for Shapes (graphics with text wrap formatting) because Word evaluates the selected graphic and creates a Textbox of the same width and positions it immediately below the graphic. The Shape and textbox are not, however, linked together in any way. So this functionality is not offered in VBA and would require some "creative" programming.

Sub InsertCaptionFromAltText()
    Dim doc as Word.Document
    Dim ils As word.InlineShape
    Dim captionText As String

    Set doc = ActiveDocument
    Set ils = doc.InlineShapes(1)
    For each ils in doc.InlineShapes
      captionText = ils.AlternativeText
      If Len(captionText) > 0 Then
          ils.Range.InsertCaption Label:=wdCaptionFigure, _
                                  Title:=captionText, _
                                  Position:=wdCaptionPositionBelow
      End If
    Next
End Sub
1
votes

Microsoft Word has a Range.InsertCaption method, which will insert field codes to automatically number images. As you were asking to insert Alternative Text, my feeling is you were using the term caption simply as a directive to get the text beneath each image on its own carriage return. So that's what this code does:

Sub GenerateAltTextCaptions()

Dim AltTextCaption As String
Dim ImageRange As Range

Selection.GoTo What:=wdGoToSection, Which:=wdGoToFirst
With ActiveDocument
    For i = 1 To .InlineShapes.Count
        AltTextCaption = .InlineShapes(i).AlternativeText
        Set ImageRange = .InlineShapes(i).Range
        ImageRange.Collapse Direction:=wdCollapseEnd
        ImageRange.InsertAfter vbCr
        ImageRange.InsertAfter AltTextCaption
    Next
End With

End Sub