将数据从两列列表框中提取到工作表

时间:2013-08-23 11:11:20

标签: vba excel-vba listbox excel

我有一个双列的列表框,我手动将条目添加到使用

.AddItem (potato)
.List(.ListCount - 1, 1) = bananaTbx.Text

当用户关闭用户窗体时,所有数据都会丢失,所以我想要保存&退出按钮将数据保存到工作表。但是,它无法保存到特定单元格,因为列表的大小是动态的,它们将不断添加到工作表中的主列表中。

我尝试做这样的事情来提取数据:

Dim i As Integer

'loop through each row number in the list
For i = 0 To Userform1.Listbox1.ListCount - 1
    'create sequence 1,1,2,2,3,3,4,4 ... to reference the current list row
    j = Application.WorksheetFunction.RoundDown(i + 0.5, 0)
    'create sequence 0,1,0,1,0,1,0,1 ... to reference current column in list
    If Len(CStr(i / 2)) > 1 Then
        k = 0
    Else
        k = 1
        Sheets("Data").Range("A1" & ":" & "A" & i).Value = Userform1.ListBox1.List(j, k)
    End If

错误:

1004 Object defined error

我该如何正确地或以更有效的方式做到这一点?

1 个答案:

答案 0 :(得分:0)

我创建了一个简单的用户窗体来演示如何从Userform上的多列列表框中提取值/数据

首先创建一个带有少量控件的简单用户窗体

userform

向您的项目添加新的Module1并将下面的代码添加到其中

Sub TestUserForm()
    UserForm1.Show
    Unload UserForm1
End Sub
项目浏览器中的

(VBE)右键单击UserForm1并点击View Code

复制并粘贴以下代码

Private Sub CommandButton1_Click()

    With ListBox1
        .AddItem TextBox1.Value
        .List(.ListCount - 1, 1) = TextBox2.Value
    End With

End Sub

Private Sub CommandButton2_Click()

    Dim ws As Worksheet
    ' create a results sheets if you do not already have one
    Set ws = Sheets("Results")

    Dim nextAvailableRow As Long
    Dim i As Long
    For i = 0 To ListBox1.ListCount - 1
        nextAvailableRow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1
        ws.Range("A" & nextAvailableRow) = ListBox1.Column(0, i)
        ws.Range("B" & nextAvailableRow) = ListBox1.Column(1, i)
    Next i

    Me.Hide
End Sub

创建新电子表格并将其命名为Results

运行TestUserForm

将示例数据添加到列表中,然后点击Save按钮

result