VBA Userform ComboBox实例化

时间:2017-12-14 14:10:11

标签: excel-vba combobox userform vba excel

我遇到Userform问题,我称之为“ComboTest2”。它只包含两个组合框。如果我将USerform实例化为对象,则以下代码在Userform的第二个组合框不包含所需数据的意义上不起作用。

Sub FillCombo(ByVal row As Long)

    Dim rgCities As Range
    Set rgCities = Worksheets("Tabelle2").Range("B2:D2").Offset(row)
    ComboTest2.ComboBox2.Clear
    ComboTest2.ComboBox2.List = WorksheetFunction.Transpose(rgCities)
    ComboTest2.ComboBox2.ListIndex = 0

End Sub

Sub FillMain()

    Dim ComboForm2 As ComboTest2
    Set ComboForm2 = New ComboTest2
    ComboForm2.Show

End Sub

用户窗体码:

Private Sub CommandButton1_Click()
    Me.Hide

End Sub

Private Sub CommandButton2_Click()
    Me.Hide
End Sub

Private Sub ComboBox1_Change()
    FillCombo ComboBox1.ListIndex
End Sub

Private Sub UserForm_Initialize()

    ComboBox1.List = Worksheets("Tabelle2").Range("A2:A5").Value
    ComboBox1.ListIndex = 0
    FillCombo ComboBox1.ListIndex
End Sub

但如果我使用VBA的“默认实例化”,这意味着我将FillMain Sub更改为:

Sub FillMain2()

    Dim ComboForm2 As ComboTest2
    Set ComboForm2 = New ComboTest2
    'ComboForm2.Show
    ComboTest2.Show

End Sub

然后一切都很好。为什么会这样?

祝你好运

1 个答案:

答案 0 :(得分:1)

这是因为FillCombo是按名称引用userform,因此是指默认实例(实际上是在创建表单的新实例)。如果该代码不在userform中,并且我不确定为什么你会将其放在表单之外,那么你应该将组合框作为参数传递给它。