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

帅比萌擦擦* 提交于 2019-12-24 16:24:24

问题


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


来源:https://stackoverflow.com/questions/34114563/vba-how-to-loop-through-labels-not-on-a-userform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!