How do I code ListBox RowSource property using worksheet and table name in Excel VBA?

106 Views Asked by At

I know I can fill in the information in the Properties window, but I would like to learn how to code the property.

After browsing the internet, this is the code I tried (Chart_of_Accts is a table in the "Chart of Accounts" worksheet):

Private Sub ListBox1_Click()
    ListBox1.RowSource = _
      Worksheets("Chart of Accounts").Range("Chart_of_Accts").Address(0, 0, , 1)
End Sub

I'm fairly new to VBA. I've tried different iterations of the same line of code (e.g., using cell names instead of the name of the table), without success. If there is more than one way of coding for this, I would appreciate to know other options as well.

EDIT:

Here's a screenshot after inserting new code suggested in answer (listbox still comes up empty):

Excel screenshot

1

There are 1 best solutions below

10
taller On BEST ANSWER
  • Use UserForm_Initialize to load items for ListBox
  • Range("Chart_of_Accts") is the data body range (w/o header row) in the table (ListObject). It is same as ListObjects("Chart_of_Accts").DataBodyRange. I prefer to use the latter one.
  • Use ColumnCount and ColumnHeads property in UserForm_Initialize event

Microsoft documentation:

ColumnCount property

ColumnHeads property

Initialize event

Private Sub UserForm_Initialize()
    Dim tabRange As Range
    Set tabRange = Worksheets("Chart of Accounts").ListObjects("Chart_of_Accts").DataBodyRange
    With Me.ListBox1
        .ColumnCount = tabRange.Columns.Count
        .ColumnHeads = True
        .RowSource = tabRange.Address(, , , True)
    End With
End Sub

enter image description here