创建一个根据应包含的元素而更改的Userform

时间:2015-07-07 06:39:31

标签: excel excel-vba userform vba

以下是用于在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

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

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

我想在Userform上显示所有活动,每个活动都有一个复选框,要么包含在ActivityNew()中,要么不包含但我不知道如何去做。

2 个答案:

答案 0 :(得分:0)

你知道如何操纵UserForms吗?

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

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

在UserForm结束时,你可以添加一个按钮'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

编辑:

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

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

在UserForm代码框中,确保您的sub具有以下名称:

Sub UserForm_Initialize()
    ACTIONS
End Sub

答案 1 :(得分:0)

请参阅下面的简化输出:

An userform that allows activities to be selected

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

以下是代码: 在Userform模块中:

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