2014-10-09 144 views
0

我有一些在运行时添加的控件,但我想填充一个组合框,它是在运行时根据从其他动态控件(它很难听懂)收到的答案创建的!填充动态组合框

我会尝试通过我的代码解释!在运行时下列控件添加到我的用户窗体:

Set cLabel = Me.Controls.Add("Forms.Label.1") 
With cLabel 
    .Caption = "Do you study maths?" 
    .Font.Size = 8 
    .Font.Bold = False 
    .Font.Name = "Tahoma" 
    .Left = 38 
    .Top = mathslbl 
    .Width = 220 
End With 

Set cManagedOptionButtonYes= Me.Controls.Add("Forms.OptionButton.1") 
With cManagedOptionButtonYes 
    .Caption = "Yes" 
    .Name = "fibreRingYes" & i 
    .GroupName = "fibreRing" & i 
    .Left = 160 
    .Top = mathsYes 
    .Width = 100 
    .Height = 15.75 
End With 

ReDim Preserve TextListBox(1 To i) 
Set TextListBox(i).mathsGroupYes = cManagedOptionButtonYes 

Set cStudentDropdown = Me.Controls.Add("Forms.Combobox.1") 
With cStudentDropdown 
    .Name = "StudenDropdown1" & (i) 
    .Left = 50 
    .Top = studentCombobox 
    .Width = 130 
    .Height = 18 
End With 

ReDim Preserve TextListBox(1 To i) 
Set TextListBox(i).studentdropdown1Group = cStudentDropdown 

所以运行以下控件在创建过程中,这些控件询问用户是否学生学习数学或不和依赖的答案给出了组合框将被填充。下面是试图填充基于用户的组合框问题的答案代码:

Private Sub cManagedOptionButtonYes_Click() 
    Dim rng As Range 
    Dim cell As Range 
    Dim c As Range 

    With cStudentDropdown 
     Sheets("Students").Activate 
     For Each c In Sheets("Students").Range("C14:C86") 
      .AddItem c.Value 
     Next 
    End With 
End Sub 

当代码试图执行我收到以下错误Object variable or with block variable not set,我想不通为什么这个亿韩元”为我工作!

+0

哪条线给你的错误? – 2014-10-09 10:34:45

+0

在此期间,您可能想要查看[THIS](http://stackoverflow.com/questions/10224511/assign-code-to-a-button-created-dynamically-using-vba-on-excel) – 2014-10-09 10:40:33

+0

'.addItem c.value'给我的问题 – user3538102 2014-10-09 11:54:41

回答

0

假设这是在用户窗体的代码页:

Private Sub cManagedOptionButtonYes_Click() 
'Dim rng As Range 
'Dim cell As Range 
Dim c As Range 

With Me.cStudentDropdown 'Me. is not necessary, but i like to use it in order to have a dropdown menu with all functions and controls created on the form 
    'Sheets("Students").Activate 
    .clear 
    For Each c In Sheets("Students").Range("C14:C86") 
     '.AddItem c.Value 'should work (whatever its format i think)..., so try this : 
     'make sure no cell in the looping range returns a error result such as #N/A something like that 
     .additem 
     .list(.listcount-1) = c.value 'or try c.value2 
    Next 
End With 
End Sub 

`