Excel VBA导出2列列表框以分离工作表

我试图导出一个2列列表框到一个新的工作表。 我想在新的工作表中显示每一列。 这需要重复两次,因为有3个列表框。 用户将在列表框中select所需的行,然后按下单独的“确认”命令button。

我写了下面的代码,将只导出每个列表框的第一列。 我已经使用RowSource使列表框双列。

任何帮助是极大的赞赏。

Private Sub ConfirmBtn_Click() Dim emptyRow As Long Sheet2.Activate emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1 Cells(emptyRow, 1).Value = SRCLstBox.Value Cells(emptyRow, 3).Value = BERLstBox.Value Cells(emptyRow, 5).Value = SNKLstBox.Value End Sub 

你可以像这样使用List属性:

 With SRCLstBox Cells(emptyRow, 1).Value = .Value Cells(emptyRow, 2).Value = .List(.ListIndex, 1) End With With BERLstBox Cells(emptyRow, 3).Value = .Value Cells(emptyRow, 4).Value = .List(.ListIndex, 1) End With With SNKLstBox Cells(emptyRow, 5).Value = .Value Cells(emptyRow, 6).Value = .List(.ListIndex, 1) End With 

ListBoxValue属性只会给你所选项目第一列的内容。 如果列表中没有项目被选中,那么你将得到NULL作为返回值。

要从ListBox获取所有项目,您将需要使用List( , )方法。 这里是一个小样本Sub给你的想法:

 Public Sub WriteAndReadFromListBox() Dim lngRow As Long ' Adding 21 rows of 'hello world' in two columns Load UserForm1 For lngRow = 0 To 20 UserForm1.ListBox1.AddItem UserForm1.ListBox1.List(lngRow, 0) = "hello" UserForm1.ListBox1.List(lngRow, 1) = "world" Next lngRow ' Selecting the first row allows you to use the ' .Value property and get 'hello' (from the first column) UserForm1.ListBox1.Selected(0) = True Debug.Print UserForm1.ListBox1.Value ' The following lines of code will write the entire content ' of the ListBox to the sheet with the Index 1 For lngRow = 0 To UserForm1.ListBox1.ListCount Sheets(1).Cells(lngRow + 1, 1).Value2 = UserForm1.ListBox1.List(lngRow, 0) Sheets(1).Cells(lngRow + 1, 2).Value2 = UserForm1.ListBox1.List(lngRow, 1) Next lngRow UserForm1.Show End Sub