2017-06-19 78 views
0

我在Excel中,在那里我需要动态创建组合框和列表框的形式。所以,这个想法是,每个列表框都链接到组合框。第一个是默认设置的,如果需要添加另一个组合+列表框,用户可以按“添加”按钮。因此,对于“添加”按钮的代码是以下几点:添加OnChange事件VBA窗体控件

Private Sub AddCountry_Click() 
aaa = "a" 
Set comb = Controls.Add("Forms.Combobox.1", "CountryList" & Val(CountryLabel.Caption) + 1) 
With comb 
.Top = CountryList1.Top 
.Width = CountryList1.Width 
.Height = CountryList1.Height 
.Left = (CountryList1.Width + 3) * Val(CountryLabel.Caption) + CountryList1.Left 
.AddItem ("--Choose country--") 
For i = 3 To 20 
.AddItem Worksheets("Countries").Range("B" & i).Value 
Next i 
.Text = "--Choose country--" 
End With 

Set listb = Controls.Add("Forms.Listbox.1", "Countries" & Val(CountryLabel.Caption) + 1) 
With listb 
.Top = Countries1.Top 
.Width = Countries1.Width 
.Height = Countries1.Height 
.Left = (Countries1.Width + 3) * Val(CountryLabel.Caption) + Countries1.Left 
.ColumnCount = 2 
.MultiSelect = 1 
End With 
CountryLabel.Caption = Val(CountryLabel.Caption) + 1 
End Sub 

的想法是,该组合框必须将名称“CountryList”和一个数字,存储在无形标签(其中添加每次+1该按钮被打包),所以它将是CountryList1,CountryList2等。列表框相同。

所以事情是,组合框是由和值(国名)的正确添加。但是我没有得到,如何在它之后使用它们?的事情,我需要的是 - 当一个组合框被改变(用户选择不同的国家),列表框下面必须用一定的值(每个国家不同)。

我认为,这个问题可能是为组合/列表框中定义的名称。那么是否可以添加动态名称(CountryList1,CountryList2等),然后以某种方式添加OnChange Events?提前致谢。

+1

你需要有一个Class模块,带有'ListBox Events'和'ComboBox Events' –

+0

看看这个问题:https://stackoverflow.com/questions/44409871/dynamic-created-user-form- with-2-dependent-combo-boxes/44410821#44410821 - 我在这里解决了它。你已经说过,你需要额外的Class作为@ShaiRado。你跟在我放置的cComboBox类之后。 –

回答

0

下面是组合框的例子。你可以基于它的列表框,因为原理完全相同。

首先创建一个类名为cComboBox,并把这个代码在那里:

Private WithEvents p_ComboBoxEvents As MSForms.ComboBox 
Private Sub p_ComboBoxEvents_Change() 
    'Here you can handle the events. 
End Sub 
Public Property Let Box(value As MSForms.ComboBox) 
    Set p_ComboBoxEvents = value 
End Property 
Public Property Get Box() As MSForms.ComboBox 
    Set Box= p_ComboBoxEvents 
End Property 

其次,在现有的代码,你可以添加此cComboBox,只是把你已经添加了ComboBox:

'Add the custom box! 
Private customBox as cComboBox 
Private Sub AddCountry_Click() 
    aaa = "a" 
    Set comb = Controls.Add("Forms.Combobox.1", "CountryList" & Val(CountryLabel.Caption) + 1) 

    With comb 
     .Top = CountryList1.Top 
     .Width = CountryList1.Width 
     .Height = CountryList1.Height 
     .Left = (CountryList1.Width + 3) * Val(CountryLabel.Caption) + CountryList1.Left 
     .AddItem ("--Choose country--") 
     For i = 3 To 20 
      .AddItem Worksheets("Countries").Range("B" & i).Value 
     Next i 
     .Text = "--Choose country--" 
    End With 

Set customBox = New cComboBox 
customBox.Box = comb 

End Sub 

当然,你可能想要创建这些数组,所以你可以有你想要的,不管他们是如何命名的。但是:你会看到,如果你改变了添加组合框值p_ComboBoxEvents_Change将触发。

+0

?需要'Set'不'Let'你的类属性和'Set'在小组的最后一行。 –

+0

在VBA中,您使用Let关键字编写set属性。由于Let部分已经完成了设置,所以在设置此属性时不需要使用Set。继续,测试它。 –

+0

呵呵,我从来没有这样做,但正如你所说的那样,它工作得很好。感谢指针。 –