希望我正确理解了您的问题并且您正在使用 ActiveX 控件,如果您希望它是通用的,我会建议:
创建一个类模块,将其命名为MyButtonClass并粘贴以下代码:
Option Explicit
Dim WithEvents btControl As MSForms.CommandButton
Private controlName As String
Public Sub btControl_Click()
Dim MySheet As Worksheet
Set MySheet = Sheets("Sheet1")
If Left(btControl.Name, 7) = "btn_PTE" Then
Dim btl As Variant
btControl.BackColor = &H80000010
'Check if another button has the same caption
For Each btl In btCollectionElement
If TypeName(btl) = "CommandButton" And btl.Caption = btControl.Caption Then Exit Sub
Next btl
'Fill caption of the first button with empty caption
For Each btl In btCollectionElement
If TypeName(btl) = "CommandButton" And btl.Caption = "" Then
btl.Caption = btControl.Caption
Exit For
End If
Next btl
End If
End Sub
Public Sub Attach(newBT As MSForms.CommandButton, newName As String)
Set btControl = newBT
controlName = newName
End Sub
Private Sub Class_Initialize()
controlName = ""
End Sub
然后将以下内容粘贴到常规代码模块中:
Option Explicit
Public groupClickCount As Integer
Public btCollection As Collection
Public btCollectionElement As Collection
Public Sub SetUpControlsOnce()
Dim MySheet As Worksheet
Set MySheet = Sheets("Sheet1")
Dim thisBT As MyButtonClass
Dim btl As OLEObject
Dim btControl As MSForms.CommandButton
If btCollection Is Nothing Then
Set btCollection = New Collection
End If
If btCollectionElement Is Nothing Then
Set btCollectionElement = New Collection
End If
For Each btl In MySheet.OLEObjects
If TypeName(btl.Object) = "CommandButton" And Left(btl.Name, 11) = "btn_Element" Then
'--- this is an ActiveX CheckBox
Set thisBT = New MyButtonClass
thisBT.Attach btl.Object, btl.Name
btCollection.Add thisBT
btCollectionElement.Add btl.Object
End If
Next btl
End Sub
Sub Clear_all_Element_Buttons_Captions()
Dim btl As Variant
For Each btl In btCollectionElement
If TypeName(btl) = "CommandButton" Then
btl.Caption = ""
End If
Next btl
End Sub
您还可以将以下内容添加到 ThisWorkbook 模块,以确保设置宏在打开时运行:
Private Sub Workbook_Open()
Call SetUpControlsOnce
End Sub
请注意,代码使用按钮名称来区分按钮类型(编辑其他按钮标题的按钮和不编辑按钮标题的按钮),但可能还有其他方法可以做到这一点。如果您发现正确命名所有按钮需要很长时间,您总是可以编写一个宏来创建按钮并为您重命名(我建议您查看 record macro 工具获得一些见解)。
确保将 Sheet1 更改为工作表的适当名称(在模块和类模块中)。
对于您问题的 文本框 部分,您可以在 btControl_Click 宏中使用类似的内容:
Dim Counter as integer
'Fill caption of the first button with empty caption
For Each btl In btCollectionElement
Counter = Counter + 1
If TypeName(btl) = "CommandButton" And btl.Caption = "" Then
btl.Caption = btControl.Caption
MySheet.Item("Textbox " & Counter).TextFrame2.TextRange = "1"
Exit For
End If
Next btl