我有一个带有选项列表的组合框,通过更改选项,它会在另一个位置创建另一个组合框和另一个选项列表。 问题是:
我尝试了以下代码,但它提供了“找不到方法或数据成员”错误。
...
答案 0 :(得分:2)
您必须确保创建了这些ComboBox,否则您将获得Compile Error。
如果没有这些ComboBoxes(MaintLevel,Workload,Breeding)的明确目的,我认为你希望它们具有相同大小和位置的唯一原因是它们每个只与一个名为的主ComboxBox选择有关。 ComboBox1
但是,您必须为每个和单个组合框创建不同的子组件 - 这是将来代码维护的可怕决定。
我会设计什么:
ThisWorkbook 模块中的代码
Option Explicit
Private Sub Workbook_Open()
CheckComboBoxesInSheet1
End Sub
Private Sub CheckComboBoxesInSheet1()
On Error Resume Next
With ThisWorkbook.Sheets("Sheet1")
If .OLEObjects("Level1Choice") Is Nothing Then
.OLEObjects.Add(ClassType:="Forms.ComboBox.1", Link:=False, _
DisplayAsIcon:=False, Left:=324.75, Top:=10.5, Width:=108, _
Height:=17.25).Name = "Level1Choice"
End If
If .OLEObjects("Level2Choice") Is Nothing Then
.OLEObjects.Add(ClassType:="Forms.ComboBox.1", Link:=False, _
DisplayAsIcon:=False, Left:=324.75, Top:=40.5, Width:=108, _
Height:=17.25).Name = "Level2Choice"
End If
.Activate
End With
End Sub
Sheet1 模块中的代码:
Option Explicit
Private Sub Worksheet_Activate()
InitializeLevel1
End Sub
Private Sub InitializeLevel1()
Dim i As Long
With Me.Level1Choice
.Clear
For i = 1 To 5
.AddItem "Choice " & i
Next
.Value = "Select an option"
End With
End Sub
Private Sub Level1Choice_Change()
Dim bShow As Boolean
bShow = True
With Me.Level2Choice
.Clear
Select Case Me.Level1Choice.ListIndex
Case 0 '=== [ MaintLevel ]===
.AddItem "Low"
.AddItem "Average"
.AddItem "High"
Case 1 '=== [ WorkLoad ]===
.AddItem "Light"
.AddItem "Medium"
.AddItem "Heavy"
Case 2 '=== [ Breeding ]===
.AddItem "No"
.AddItem "Yes"
Case Else
bShow = False
End Select
.Visible = bShow
If bShow Then .Activate
End With
End Sub
Private Sub Level2Choice_Change()
Dim sLevel1Value As String, sLevel2Value As String
sLevel1Value = Me.Level1Choice.Value
sLevel2Value = Me.Level2Choice.Value
Debug.Print sLevel1Value, sLevel2Value
End Sub
希望我能清楚自己的流程。