Populate Listbox from Array

ccordner

Active Member
Joined
Apr 28, 2010
Messages
355
I'm not very experienced at working with arrays in vba and this is probably very simple.

I want to populate a listbox with an array of unknown size (three columns, not sure how many rows) from the sheet "SAP Codes" starting from row 2.

The code I have below doesn't seem to work.


Dim arrSAPCodes() As String

Private Sub UserForm_Initialize()

'Populate SAP Codes
arrSAPCodes = .Range(.Range("A2"), .Range("C" & Rows.Count).End(xlUp))
lstSAPCodes = SAPCodes

End Sub

I'm sure it's something obvious

Incidentally, when I have done this, how do I refer to an individual item of the array? For example, if the first column contains unique code and I have a unique code, how do I find the corresponding entry in the second column?
 

Excel Facts

Workdays for a market open Mon, Wed, Friday?
Yes! Use "0101011" for the weekend argument in NETWORKDAYS.INTL or WORKDAY.INTL. The 7 digits start on Monday. 1 means it is a weekend.
You don't really need to handle an array to load a multi-column listbox:
Here's a non-Array version:
Code:
Private Sub UserForm_Initialize()
    Sheets(1).Activate
    lastrow = Range("C" & Rows.Count).End(xlUp).Row
    With ListBox1
    .ColumnCount = 3
    .ColumnWidths = "35;35;35" 'points
    .BoundColumn = 1    'if it's bound to a cell, column 1  is returned
    .ControlSource = "Sheet1!E2"
    .RowSource = "A2:C" & lastrow 'The array of cells that provide values
    End With
End Sub

And to get the values back out of the click event:
Code:
Private Sub ListBox1_Click()
    With ListBox1
        MsgBox .ListIndex & vbCrLf & _
        .List(.ListIndex, 0) & vbCrLf & _
        .List(.ListIndex, 1) & vbCrLf & _
        .List(.ListIndex, 2)
    End With
End Sub
 
Upvote 0

Forum statistics

Threads
1,224,520
Messages
6,179,267
Members
452,902
Latest member
Knuddeluff

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top