Search code examples
vbams-wordword-contentcontrol

Get Index of Specific Content Control based on ID or Title


I would like to retrieve the word content control's index via VBA given a specific title without having to loop through all content controls looking for the title.

I know the title of the content control that I would like to select therefore I can set the ID of that specific content control to a variable for instance

a = ActiveDocument.SelectContentControlsByTitle("123").Item(1).ID

Now, I would like to know what the index of this item is among the other content controls in the document (over 450 content controls in the file template) such that I can refer to the content control index as a variable.

In lay terms I would like something along the lines of "b=getIndexOfA(a)" such that I can perform later process such as:

for i=b to ActiveDocument.ContentControls.Count
    .....
next i

I am running Word 2016 on Windows 10.


Solution

  • The following approach works for just about object in the document body that's part of the text (as opposed to a floating image). Get a Range for the object, then set its starting point to the beginning of the document. Count all the objects of that type within the range:

    Dim lIndexCC as Long
    Dim cc as Word.ContentControl
    Dim rng as Word.Range
    
    Set cc = ActiveDocument.SelectContentControlsByTitle("123").Item(1)
    Set rng = cc.Range
    rng.Start = ActiveDocument.Content.Start
    lIndexCC = rng.ContentControls.Count
    Debug.Print lIndexCC