wp44
wp44

Reputation: 265

Creating a Command Button Class - For Word Command Buttons

I am trying to set some command buttons properties out in bulk . That is trying to set various properties of the command buttons in one go rather than repeat the code for each command button individually.

The document has 30+ command buttons.

In the Class - I have put the code below:

Option Explicit

Public WithEvents cMDButtonGroup As CommandButton

Private Sub cMDButtonGroup_Click()
With cMDButtonGroup

    If   .Caption = "Press" Then

    '  Add some other button properties

    Else

        .Caption = " Complete"


    End If
End With

In a VBA Module - I have put the code below:

Option Explicit
Dim Buttons() As New cMDButtonClass

Sub Buttons()
Dim ButtonCount As Integer
Dim ctl As Control

'   Create the Button objects
ButtonCount = 0
For Each ctl In ActiveDocument.Controls   ' This may be wrong
    If TypeName(ctl) = "CommandButton" Then

            ButtonCount = ButtonCount + 1
            ReDim Preserve Buttons(1 To ButtonCount)
            Set Buttons(ButtonCount).ButtonGroup = ctl
        End If
    End If
Next ctl

End Sub

The above may have been sourced from VBA Express? Unfortunately I have lost the link.

Unfortunately I do not know how to proceed to fix this.

Final Solution: Tim's Code works perfectly. You also need to load the buttons

Put the below code in ThisDocument

Private Sub Document_Open()

Call SetupButtons


End Sub

Upvotes: 0

Views: 1408

Answers (1)

Tim Williams
Tim Williams

Reputation: 166725

cMDButtonClass (simplified)

Public WithEvents oBtn As CommandButton

Private Sub oBtn_Click()
    MsgBox "clicked: " & oBtn.Caption
End Sub

In a regular module:

Dim colButtons As New Collection '< simpler to manage than an array

Sub SetupButtons()
    Dim ButtonCount As Integer
    Dim ctl, c
    Dim oB As cMDButtonClass

    'Following Cindy's comment...
    For Each ctl In ActiveDocument.InlineShapes
        If Not ctl.OLEFormat Is Nothing Then
            Set c = ctl.OLEFormat.Object
            If TypeName(c) = "CommandButton" Then
                Set oB = New cMDButtonClass
                Set oB.oBtn = c
                colButtons.Add oB
            End If
        End If
    Next ctl

End Sub   

Upvotes: 3

Related Questions