我找到了一个非常有趣的解决方案:
创建一个用户表单(我已将我的命名为“frmSearchForm”)
在上面创建一个框架(我的是“framTest”)
创建一个 Classmodule 并将其命名为“clsUserFormEvents”
将此代码添加到其中:
Public WithEvents mButtonGroup As msforms.CommandButton
Private Sub mButtonGroup_Click()
'This is where you add your routine to do something when the button is pressed
MsgBox mButtonGroup.Caption & " has been pressed" 'Just Example Code
End Sub
然后在 ThisDocument 模块中,添加以下代码:
Dim mcolEvents As New Collection
Sub createButtonsOnForm()
Dim Cmd As msforms.CommandButton
'create instance of class
Dim cBtnEvents As clsUserFormEvents
'array for selection
Dim wordArr() As String
'get selection into array
wordArr = Split(Selection, " ")
Dim i As Integer
'counter for the top position of buttons
Dim topcounter As Integer
topcounter = 10
'loop through array
For i = LBound(wordArr) To UBound(wordArr) Step 1
'create button
Set Cmd = frmSearchForm.framTest.Controls.Add("Forms.CommandButton.1", "Test")
'Adjust properties of it
With Cmd
.Caption = wordArr(i)
.Left = 100
.Top = topcounter
.Width = 50
.Height = 20
End With
'Instantiate Class
Set cBtnEvents = New clsUserFormEvents
'Add cmd to event in class
Set cBtnEvents.mButtonGroup = Cmd
'Add buttonevent to collection so it won't get deleted in next iteration of the loop
mcolEvents.Add cBtnEvents
'increase the top position
topcounter = topcounter + 25
Next i
'show userform
frmSearchForm.Show
End Sub
然后,如果您运行此子程序,则选择将拆分为数组,为每个元素创建一个按钮(选择部分作为标题),如果您按下按钮,则调用类内的方法,您可以在其中使用mButtonGroup.Caption
属性获取按钮的值。
例子:
我已经选择了“Test1”和“Test2”这两个词,现在当我运行 Sub 时,表单会打开 2 个按钮(Test1 和 Test2):
