VBA: How to loop through labels (not on a userform

2019-08-15 02:57发布

问题:

My Word document has many ActiveX labels. [Not textboxes: my original title was in error.]

I'd like a macro to loop through them to perform an action on each of them (changing the captions), but I don't know how to identify them.

If they were on a userform, I'd say: For each aLabel in UserForm1.Controls

But that doesn't apply in my case.

回答1:

Assuming it is textboxes you're working with, per the title but not the question, the document's Shapes collection may be what you're after:

Sub ShapeLoop()

    Dim shp As Shape

    For Each shp In ThisDocument.Shapes
        ' Test if shp is one you're interesed in, perhaps using shp.Name
        Debug.Print shp.Name
        ' Do Stuff
    Next shp

End Sub

Edit:

Same again for the fields collection

Sub FieldLoop()

    Dim fld As Field

    For Each fld In ThisDocument.Fields
        If TypeName(fld.OLEFormat.Object) = "Label" Then
            Debug.Print fld.OLEFormat.Object.Caption
            fld.OLEFormat.Object.Caption = "New Caption"
        End If
    Next

End Sub