创建一个根据应包含的元素而变化的用户窗体

Creating a Userform that changes depending on the elements it should contain

以下是用于在 Excel 中创建图表的部分代码:

    elements = 0
    For j = 1 To x - 1
        ans = MsgBox(Activity(j), vbYesNo, "Do you wish for this Element to appear in the Gantt Chart?")
        If ans = vbYes Then
            elements = elements + 1
            ActivityNew(elements) = Activity(j)
        End If
    Next j

我的想法是,我在数组 Activity() 中有一个 x-1 活动列表,只有其中一些需要显示在图表上。这些存储在 ActivityNew() 中,变量 elements 计算该数组的数量。

目前,我使用 VbYesNo 消息框循环遍历 Activity() 中的所有活动,并要求用户决定应在图表中显示哪些活动。

我想在用户窗体上显示所有活动,每个活动都带有一个复选框以包含或不包含在 ActivityNew() 中,但我不知道该怎么做。

你知道如何操作用户窗体吗?

您可以使用此代码创建一个元素:

Set TheTickBox = UserForm.Controls.Add("Forms.TickBox.1", Visible = True)

With TheTickBox
    .Left       'Beginning of the tickbox compared to the left side of the UserForm
    .Width
    .Top        'Beginning of the tickbox compared to the top of the UserForm
    .Height
    .Caption    'Change the displayed text
End With

所以你可以使用这样的东西:

For j = 0 to x - 1
    Set TheTickBox = UserForm.Controls.Add("Forms.TickBox.1", Visible = True)
    With TheTickBox
        .Left = 10
        .Width = The_Width_You_Want
        .Top = 10 + j*The_Height_You_Want        
        .Height = The_Height_You_Want
        .Caption = activity(j)
    End With
Next j

在用户窗体的末尾,您可以添加一个按钮 'Validate' 遍历所有复选框,并检查您为它们提供的值:

Sub ButtonValidate_Click()
elements = 0

For each Ctrl in UserForm.Controls

    If Ctrl.Value = True Then
        ActivityNew(elements) = Ctrl.Caption
        elements = elements + 1
    End If

Next Ctrl

End Sub

编辑:

要创建用户窗体,只需在右键单击项目时单击 'Add UserForm'(在 VBA 编辑器中)。 我一开始给你的代码行必须写在用户窗体代码框中(右键单击你的用户窗体 -> 代码)和正常代码区域中的以下内容:

Sub UserForm()
    UserForm.Show     'Here I suppose UserForm is the name of your UserForm
End Sub

并在用户表单代码框中确保您的子名称为:

Sub UserForm_Initialize()
    ACTIONS
End Sub

请参考下面的简化输出:

要有输出: 1. 您需要将用户表单的 属性 列表框 MulitSelect 设置为 1。

代码如下: 在用户表单模块中:

Private Sub ButtonOK_Click()
    Dim Msg As String
    Dim i As LoadPictureConstants
    Msg = ""
    For i = 0 To ListBox1.ListCount - 1
        If ListBox1.Selected(i) Then _
        Msg = Msg & ListBox1.List(i) & vbCrLf
    Next i
    MsgBox "You selected: " & vbCrLf & Msg
    Unload Me
End Sub

Private Sub UserForm_Initialize()
    Dim i As Long
    Me.Caption = "Select Activities"

    Call BuildActivityArray
    For i = 1 To 5
        Me.ListBox1.AddItem Activity(i)
    Next

End Sub

在标准代码模块中:

Sub ShowForm()
    UserForm1.Show
End Sub