I have a listbox named listBox1 on a user form in Excel VBA and a button named submit also on the form. The listbox is populated from a dynamic range starting on cell A2 of sheet 2. I want to export the contents of this listbox to a named range named dataCells on sheet 1. The code I am using currently is close but somehow exports the listbox data to cell A1 of sheet 1 instead of starting in the first cell of the named range "data cells". What am I doing wrong?
//Code to populate listBox 1
Private Sub Userform1_initialize()
Dim dataItems as Range
Dim item as Range
worksheets("sheet2").Activate
Set dataItems = Range("A2" , Range("A2").end(xlDown))
for each item in dataItems
listbox1.addItem(item)
Next item
End sub
//Code to export the listbox contents to named range in sheet 1
Private Sub Submit_Click()
Dim dataCells as Range
Dim dataCount as Integer
Dim i as integer
worksheets("sheet1").Activate
dataCount = listBox1.ListCount - 1
set dataCells = Range("B2" , Range("B2").offset(0, dataCount))
for i = 0 to listBox1.ListCount - 1
dataCells(0, i) = listBox1.list(i , 0) // exports to A1 of sheet 1??
next i
End sub
dataCells
will be a one-based 2-D array, not zero-based. In the immediate pane in the VBE? Range("B2").Cells(0,0).Address()
gives "$A$1" – Tim Williams