【问题标题】:Creating a Command Button Class - For Word Command Buttons创建命令按钮类 - 对于 Word 命令按钮
【发布时间】:2016-03-10 17:24:39
【问题描述】:

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

该文档有 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?不幸的是,我丢失了链接。

很遗憾,我不知道如何解决这个问题。

最终解决方案:Tim 的代码运行良好。您还需要加载按钮

将以下代码放入ThisDocument

Private Sub Document_Open()

Call SetupButtons


End Sub

【问题讨论】:

  • 嗨 Deduplicator - 这是 VBA for word - 还是我弄错了?
  • 这些是 MSForms 类型库中的 ActiveX 控件吗?为了“一般”地解决它们,您需要 InlineShapes 集合。测试“类型”属性。如果这是正确的,那么您可以通过 InlineShape.OLEObject.Object 获得控制对象。我目前正在使用移动设备,所以直到明天才能给你更具体的信息......
  • 非常感谢 Cindy,你说得对,它们是 Active X - 命令按钮 - 我期待你的建议 - 再次感谢!

标签: vba button command ms-word


【解决方案1】:

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   

【讨论】:

  • 嗨蒂姆,谢谢你的代码。我已经设置了代码。当我按下命令按钮时 - 没有消息弹出 - 我不知道为什么?
  • Tim 感谢您的帮助,这段代码完美地完成了这项工作。还要感谢 Cindy 的初始输入 :)
猜你喜欢
  • 2020-09-11
  • 1970-01-01
  • 1970-01-01
  • 2011-07-09
  • 1970-01-01
  • 1970-01-01
  • 2019-07-31
  • 2016-09-10
  • 2013-01-01
相关资源
最近更新 更多