I am trying to add a line of cells in a sheet to a multicolumn listbox in a userform. The number of columns in the sheet also varies. I keep getting the error 'Type mismatch.' Stepping through my code I found that it occurs at the first .AddItem line. I found out that you cannot add multiple items with .AddItem. Is there another method to do this? I'm very new to vba. Thanks for your help!
Private Sub GenerateButton_Click()
Dim i As Long, counter As Long, counter_RA As Long, x As Integer
Dim LastColRA As Long, LastColCP As Long
LastColRA = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
LastColCP = Sheet2.Cells(1, Columns.Count).End(xlToLeft).Column
'Check to make sure that enough items were selected
For x = 0 To ListBox2.ListCount - 1
If ListBox2.Selected(x) Then
counter_RA = counter_RA + 1
With TabData.DataTable
.AddItem Sheets(Sheet1).Range(Cells(x + 2, 1), Cells(x + 2, LastColRA)).Text
End With
End If
Next x
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) Then
counter = counter + 1
With TabData.DataTable
.AddItem Sheets(Sheet2).Range(Cells(i + 2, 1), Cells(i + 2, LastColCP)).Text
End With
End If
Next i
End Sub
You have a couple of issues there. First, if you use the Text
property of a multiple cell range, it will return Null
unless all the cells contain the same text. Second, as you note, you cannot add an array in one go using AddItem
- you need to add an item then loop to populate the columns, remembering that the indices are 0-based:
With TabData.DataTable
.AddItem
For n = 1 to LastColRA
.List(.ListCount - 1, n - 1) = Sheet1.Cells(x + 2, n).Value
next n
End With
Here's a version that will work with more than 10 columns:
Dim i As Long, counter As Long, counter_RA As Long, x As Long
Dim LastColRA As Long, LastColCP As Long
Dim vList()
LastColRA = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
LastColCP = Sheet2.Cells(1, Columns.Count).End(xlToLeft).Column
'Check to make sure that enough items were selected
For x = 0 To ListBox2.ListCount - 1
If ListBox2.Selected(x) Then
counter_RA = counter_RA + 1
ReDim Preserve vList(1 To LastColRA, 1 To counter_RA)
For i = 1 To LastColRA
vList(i, counter_RA) = Sheet1.Cells(x + 2, i).Value
Next i
End If
Next x
For x = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(x) Then
counter_RA = counter_RA + 1
ReDim Preserve vList(1 To LastColRA, 1 To counter_RA)
For i = 1 To LastColRA
vList(i, counter_RA) = Sheet2.Cells(x + 2, i).Value
Next i
End If
Next x
With TabData.DataTable
.ColumnCount = LastColRA
.Column = vList
End With
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments