如何将动态组合框中的数据保存到excel单元格

时间:2014-06-02 09:16:03

标签: excel vba excel-vba

我创建了一个动态添加组合框的表单。现在我想将这些数据保存回具有更新值的excel单元格。 这是我将combobx添加到表单

的代码
Private Sub UserForm_Initialize()
Dim i As Integer
For i = 1 To 30
UserForm1.Show vbModeless
Dim theLabel As Object
Dim labelCounter As Long
    Set theLabel = UserForm1.Controls.Add("Forms.Label.1", Cells(i, 1).Value, True)
    With theLabel
        .Caption = Cells(i, 1).Value
        .Left = 5
        .Width = 200
        .Top = 20 * i
    End With
    Dim DesiredControl As Control

Set DesiredControl = UserForm1.Controls.Add("Forms.Combobox.1", Visible)
DesiredControl.Left = 350
DesiredControl.RowSource = "Interface!xfd2:xfd150"
DesiredControl.Top = 20 * i
DesiredControl.Width = 175
DesiredControl.Height = 19
'DesiredControl.AutoComplete = enable
Next i
End Sub

到目前为止,每件事都很好

现在我想将每个组合框值保存到excel单元格。 因为我试过它

Private Sub CommandButton1_Click()
Dim irow As Long
Dim ws As Worksheet
Set ws = Worksheets("Interface")
Sheets("Interface").Range("B1").value = UserForm1.ComboBox.1.Value

End Sub

但我没有取得成功。请纠正我。

注意每个组合框在表单中动态添加。

2 个答案:

答案 0 :(得分:0)

试试这个:

Private Sub CommandButton1_Click()
Dim irow As Long
Dim ws As Worksheet
Set ws = Worksheets("Interface")
Sheets("Interface").Range("B1").value = UserForm1.ComboBox.ListIndex

End Sub

答案 1 :(得分:0)

添加控件时可以命名控件:

Set DesiredControl = UserForm2.Controls.Add("Forms.Combobox.1", "Combo" & i, Visible)

然后使用控件集合引用它:

Sheets("Interface").Range("B1").Value = UserForm1.Controls("Combo1").Value

例如。