创建命令按钮类 - 对于Word命令按钮

时间:2016-03-10 17:24:40

标签: vba button ms-word command word-vba

我正在尝试批量设置一些命令按钮属性。这是尝试一次性设置命令按钮的各种属性,而不是单独重复每个命令按钮的代码。

该文档有30多个命令按钮。

中 - 我已将代码放在下面:

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

VBA模块中 - 我已将代码放在下面:

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

以上可能来自VBA Express?不幸的是我丢失了链接。

不幸的是我不知道如何解决这个问题。

最终解决方案:蒂姆的代码运作完美。您还需要加载按钮

将以下代码放在ThisDocument

Private Sub Document_Open()

Call SetupButtons


End Sub

1 个答案:

答案 0 :(得分:3)

cMDButtonClass(简化)

Public WithEvents oBtn As CommandButton

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

在常规模块中:

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