1

我有selected一个句子。

1)句子可以变化。

2)我有split句子的每个单词。

下面的代码创建了一个Word arrayfrom列表Selection

Sub Seperate_Words()

    Dim WrdArray() As String

    WrdArray() = Split(Selection)

    For i = LBound(WrdArray) To UBound(WrdArray)
        strg = strg & vbNewLine & WrdArray(i)
    Next i

    MsgBox strg

End Sub

现在我想Search button在每个单词前面添加一个。

在每种情况下,句子的长度都会发生变化,并且用户表单是预先指定的,这就是我不能使用它们的原因。

下图显示了输出应该如何

现在我面临的问题是在框架中添加一个滚动条,如果需要,它会动态变化。

4

1 回答 1

2

我找到了一个非常有趣的解决方案:

创建一个用户表单(我已将我的命名为“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): 示例图片

于 2016-05-10T12:43:44.487 回答