2016-02-29 103 views
0

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

我写了下面的代码,将只导出每个列表框的第一列。我已经使用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 

回答

1

可以使用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 
0

一个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