Consulting

Results 1 to 3 of 3

Thread: ContentControls by number not name

  1. #1
    VBAX Newbie
    Joined
    Nov 2017
    Posts
    1
    Location

    ContentControls by number not name

    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!
    Last edited by malcmail; 11-13-2017 at 06:37 AM. Reason: problem solved!

  2. #2
    Moderator VBAX Sage SamT's Avatar
    Joined
    Oct 2006
    Location
    Near Columbia
    Posts
    7,814
    Location
    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.
    I expect the student to do their homework and find all the errrors I leeve in.


    Please take the time to read the Forum FAQ

  3. #3
    Knowledge Base Approver VBAX Guru macropod's Avatar
    Joined
    Jul 2008
    Posts
    4,435
    Location
    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
    Cheers
    Paul Edstein
    [Fmr MS MVP - Word]

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •