我有一个用户窗体,其中有两个名为“ Combobox1”和“ Combobox2”的组合框。在我的Excel工作表名称“ Sheet1”中,我具有A和B列,它们在“组”中具有某些值。
目标:我想将Combobox2值显示为B列值,但选择时应取决于A列值。我尝试了下面的代码,但不了解我要去哪里。
Private Sub Combobox1_Change()
'interlink dropdown box
Dim index As Integer
index = Combobox1.ListIndex
Select Case index
Case Is = 0
With Combobox2
Me.Combobox2.Clear
Worksheets("Sheet1").Range("B11:B13").Value
End With
Case Is = 1
With Combobox2
Me.Combobox2.Clear
Worksheets("Sheet1").Range("B14:B16").Value
End With
Case Is = 2
With Combobox2
Me.Combobox2.Clear
Worksheets("Sheet1").Range("B17:B19").Value
End With
End Select
End Sub
Private Sub UserForm_Initialize()
Me.Combobox1.AddItem "1"
Me.Combobox1.AddItem "2"
Me.Combobox1.AddItem "3"
End Sub
必需的输出:
答案 0 :(得分:1)
您必须像在UserForm_Initialize中一样添加项目。此外,我建议使用辅助函数来迭代元素(AddItemsToComboBox):
Option Explicit
Private Sub Combobox1_Change()
Dim varCombox2Items As Variant
Select Case ComboBox1.Value
Case "1"
AddItemsToComboBox ComboBox2, Worksheets("Sheet1").Range("B11:B13").Value
Case "2"
AddItemsToComboBox ComboBox2, Worksheets("Sheet1").Range("B14:B16").Value
Case "3"
AddItemsToComboBox ComboBox2, Worksheets("Sheet1").Range("B17:B19").Value
Case Else
AddItemsToComboBox ComboBox2, Array("Ivalid Value in ComboBox1")
End Select
End Sub
Private Sub UserForm_Initialize()
AddItemsToComboBox ComboBox1, Array("1", "2", "3")
End Sub
Private Sub AddItemsToComboBox(cobTarget As MSForms.ComboBox, varItems As Variant, Optional blnClear As Boolean = True)
If blnClear Then
cobTarget.Clear
End If
Dim varItem As Variant: For Each varItem In varItems
cobTarget.AddItem CStr(varItem)
Next varItem
End Sub