滚动查看有不同数量按钮的按钮

时间:2016-05-10 11:40:38

标签: vba ms-word word-vba word-2007 word-2003

我有selected句子。

1)句子可能会有所不同。

2)我的每个单词都有split

以下代码会从Word array创建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

在每种情况下,句子的长度都会改变,而Userforms是预先指定的,这就是我不能使用它们的原因。

以下图片显示了输出应该如何

现在我遇到的问题是在框架中添加一个滚动条,如果需要动态更改。

1 个答案:

答案 0 :(得分:2)

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

创建一个UserForm(我已将其命名为#34; 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): ExampleImg