【发布时间】:2017-06-07 20:08:25
【问题描述】:
我正在尝试创建一个动态 User_form,其中所有 Controls 都是在运行时创建的。
我有 2 个组合框数组,第一个组合框数组是 "Catgeory" (CatCBArr),第二个组合框数组是 "Item" (ItemCBArr)。
我希望,一旦我从“Category”的第一个 Combo-Box 中选择了一个值,比如CatCBArr(0),那么只会显示ItemCBArr(0) 中的相关项目。
问题:我不知道如何根据第一个 Combo-box (CatCBArr(0)) 中选择的值来修改第二个 Combo-box (ItemCBArr(0))
User_Form 代码(相关部分)
Option Explicit
Dim ItemsNumofRows As Long
Dim QtyTB As MSForms.TextBox
Dim CatCB As MSForms.ComboBox
Dim ItemCB As MSForms.ComboBox
Dim Key As Variant
' dynamic Form controls (related to new Classes)
Dim CatCBArr() As New cComboBox
Dim ItemCBArr() As New cComboBox
Dim QtyTBArr() As New cTextBox
Private Sub UserForm_Initialize()
' reset flags
ItemsNumofRows = 5
TasksNamesUpd = False
TasksColUpd = False
ItemsRows_ControlsInit '<-- upload all Controls at run-time
Check_FormHeight
End Sub
'======================================================
Private Sub ItemsRows_ControlsInit()
For ItemRow = 0 To ItemsNumofRows
' add Category Combo-boxes
Set CatCB = Me.Controls.Add("Forms.ComboBox.1", "Cb" & ItemRow, True)
With CatCB
' loop through Dictionay items (view category)
For Each Key In Dict.Keys
.AddItem Key
Next Key
.SpecialEffect = fmSpecialEffectSunken
.Left = 40
.Width = 100
.Height = 18
.Top = 54 + 20 * ItemRow
ReDim Preserve CatCBArr(0 To ItemRow)
Set CatCBArr(ItemRow).ComboBoxEvents = CatCB
End With
' add Item Combo-boxes
Set ItemCB = Me.Controls.Add("Forms.ComboBox.1", "Cb_" & ItemRow, True)
With ItemCB
.SpecialEffect = fmSpecialEffectSunken
.Left = 160
.Width = 100
.Height = 18
.Top = 54 + 20 * ItemRow
ReDim Preserve ItemCBArr(0 To ItemRow)
Set ItemCBArr(ItemRow).ComboBoxEvents = ItemCB
End With
Next ItemRow
End Sub
cComboBox 类代码
Public WithEvents ComboBoxEvents As MSForms.ComboBox
Private Sub ComboBoxEvents_Change()
Dim CBIndex As Long
' get for ID number (row number), from third character in String Name.
' e.g "Cb1" will result 1)
CBIndex = CInt(Mid(ComboBoxEvents.Name, 3))
' ??? How do I get the Value, and update the second combo-box Items
Select Case ComboBoxEvents.Value
End Select
End Sub
GUI User_Form屏幕截图
【问题讨论】:
-
ComboBoxEvents.Value返回值。您可以对该值进行选择案例,然后使用第二个组合框.addItem方法添加您需要的项目。要清除正手第二个中的项目,请使用.clear -
啊,我看到您还在用户表单中使用
Dim声明了组合框。使用Public代替第二个数组(Dim 的行为与私有相同)在这种情况下,您可以通过User_form.ItemCBArr(0)从您的班级访问组合框