PDA

View Full Version : [SOLVED:] ContentControls by number not name



malcmail
11-13-2017, 06:17 AM
Been using VBA for longer than I care to remember but always in Excel. Branching out into Word and got a bit of a headache.

I have a document with a series of ContentControls (rich text). The VBA needs to populate the content of these based on user input. I have one version so that a userform simply cycles through 5 questions and pops these in. Due to a change in structure it is now a number of forms. Getting the info in is no problem but actually getting it into the text itself is the problem.

WHat I ideally need to do is rather than reference the CC by name is to do them by number in the document. But I cannot work out how to do it. So far I've got...


ActiveDocument.ContentControls.Item(answer_loop).Range.Text = fmSingle.Controls("txt_" & answer).Value
....within a loop (which counts from, say, 5 to 8) to try and allocate the input to the correct CC. What am I doing wrong / have I missed?

TIA

Turns out it was a counting issue rather than the code ie idiot error!

SamT
11-13-2017, 07:55 AM
I like to use Collections or Arrays to hold the Objects.

Collections allow For Each Structures and for indexing by name, and has no limits on the number of Items. Arrays allow 'Counting', but are limited in size or require ReDimming.

I always try to get all my names in different places to be identical except for prefixes and suffixes. This allows structures like

For Each frmCtrl in Form.ioControls
Doc.Controls("ctrl" & Mid(FrmCtrl.Name, 3)) = frmCtrl.Text
Next


This way, If I add or delete Items from the Doc, I only have to add or remove that control from the Forms ioControls Collection. It requires a little more work up front, but is a joy when the inevitable changes come down from on high.

macropod
11-13-2017, 02:35 PM
Try something along the lines of:

Dim i As Long
For i = 5 To 8
ActiveDocument.ContentControls.Item(i).Range.Text = fmSingle.Controls("txt_" & i).Value
Next