从动态添加的userform控件vba excel中读取值

时间:2015-03-23 14:39:02

标签: excel vba

我有一个excel vba表单,其中动态添加了不同的控件,但是当我尝试读取这些所谓的控件的值时,我找不到它们。我的代码如下所示:



Private Sub CommandButtonAddIndependentParameters_Click()


    Dim theComboBoxIndependentParameterNameNo As MSForms.ComboBox
    Dim theLabelIndependentParameterNo As MSForms.Label

    
    iii = iii + 1


    If iii <= 2 Then
       

        Set theComboBoxIndependentParameterNameNo = FrameMeasurement.Controls.Add("Forms.ComboBox.1", _
            "ComboBoxIndependentParameterNameNo", True)
   
        Set theLabelIndependentParameterNo = FrameMeasurement.Controls.Add("Forms.Label.1", _
            "LabelIndependentParameterNo" & iii + 1, True)
        
        With theComboBoxIndependentParameterNameNo
            .Font.Name = "B Nazanin"
            .Font.Size = 12
            .TextAlign = fmTextAlignRight
            .Height = 24
            .Left = 60
            .Top = 66 + 40 * (iii)
            .Width = 100
            .AddItem (Range("AN2").Value)
            .AddItem (Range("AN3").Value)
            .AddItem (Range("AN4").Value)
        End With
        
        With theLabelIndependentParameterNo
            .Font.Name = "B Nazanin"
            .Font.Size = 12
            .TextAlign = fmTextAlignRight
            .Caption = iii + 1
            .Width = 14
            .Height = 18
            .Left = 161
            .Top = 66 + 40 * (iii)
            .AutoSize = False
       End With
        
    End If

End Sub
&#13;
&#13;
&#13;

然后我尝试使用以下代码读取插入的值:

&#13;
&#13;
Range("A2").Value = ComboBoxIndependentParameterNameNo2.Value
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

当您将其应用于单元格并使用控件本身时,我不相信您在控件旁边的代码中需要.value。试试这个:

Range("A2").Value = theComboBoxIndependentParameterNameNo

&#39;我还找到了别人做过的另一个答案:

Dim oneControl As Object

For Each oneControl In userform.Controls
    If TypeName(oneControl) = "TextBox" Then
        With oneControl
            Range("M9") = .Value
        End With
    End If