我有一个包含大约 200 个按钮的 VBA Excel 应用程序。我希望他们都更改一个名为“名称”的文本框,并按下按钮的标题。我确实模糊了图像中的一些东西,因为这些盒子都是真实的人的名字。如何在不创建 200 多个函数的情况下做到这一点?
举个例子,假设我有 3 个按钮。这三个值是 foo1
、foo2
和 foo3
。当我单击任何按钮时,假设我单击 foo2
,我希望文本框将值更新为 foo2
。我知道如何执行此操作,但如何在无需手动为所有 3 个按钮编写函数的情况下执行此操作。文本框值将始终是按钮值。现在想象一下它有 200 多个按钮。
谢谢!
最佳答案
这是我的处理方法。首先添加一个类模块并将其命名为buttonClass
:
Option Explicit
Public WithEvents aCommandButton As msforms.CommandButton
Private Sub aCommandButton_Click()
MsgBox aCommandButton.Name & " was clicked"
End Sub
然后在您的用户表单启动事件中,使用类似于以下的代码:
Dim myButtons() As buttonClass
Private Sub UserForm_Initialize()
Dim ctl As Object, pointer As Long
ReDim myButtons(1 To Me.Controls.Count)
For Each ctl In Me.Controls
If TypeName(ctl) = "CommandButton" Then
pointer = pointer + 1
Set myButtons(pointer) = New buttonClass
Set myButtons(pointer).aCommandButton = ctl
End If
Next ctl
ReDim Preserve myButtons(1 To pointer)
End Sub
这将连接所有命令按钮以在单击时显示其名称。您可以将 ButtonClass 中的逻辑调整得更漂亮。或者您可以调整初始化事件中的逻辑以包含某些按钮(扩展“If”部分)。
希望有帮助!
关于vba - 200 个按钮全部更改一个文本框 - VBA Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45467809/