0

I'm current trying to write a macro (VBA in Word) that will compile information from a collection of documents into a single document.

I order to do this I have a list of ~20 checkboxes that will determine which documents I want to include in the compilation. My issue is that when writing the macro, I can't figure out a way of checking the state of each checkbox on my list without re-writing the same block of code 20 times, only changing the name of the checkbox. eg CB1 to CB2, CB3 CB4 etc. each time.

This is the block of code in question. It does work if I rewrite it multiple times for the changing check box number but I would prefer it in a loop so the code is more compact and robust:

If ThisDocument.CB1.Value = True Then

Documents.Open(directory).Activate
Selection.WholeStory
Selection.Copy
Documents(NewFile).Activate
Selection.Paste
Documents("file.docx").Close

End If

Ideally I would like to have the check box named something like CBn, where n is a variable that I can redefine at the end of each loop.

1 Answer 1

0

There's no option for directly referring to a control by its name - you can wrap that up in a function though:

Sub Tester()
    Dim x As Long, cb As Object
    For x = 1 To 3
        'find the checkbox
        Set cb = ControlByName("CB" & x, ThisDocument)
        'check we got something back
        If Not cb Is Nothing Then
            Debug.Print "CB" & x & " is " & cb.Value
        End If
    Next x
End Sub

Function ControlByName(sName, doc As Document) As Object
    Dim obj
    For Each obj In doc.InlineShapes
        If obj.OLEFormat.Object.Name = sName Then
            Set ControlByName = obj.OLEFormat.Object
            Exit Function
        End If
    Next obj
End Function
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.