VBA Excel Populate ListBox with multiple columns

后端 未结 2 1170

This may be a cheap question for some but I\'m totally confused on how to populate my listbox.

Using this line I can populate the listbox as shown below:

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 10:21

    How about this:

    Sub foo()
    Dim rngName As Range
    Dim ws As Worksheet
    Dim i As Integer
    Set ws = Worksheets("Sheet1")
    ListBox1.Clear
    ListBox1.columnCount = 3
    Dim LastRow As Long
    LastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
        For i = 1 To LastRow
            If ws.Cells(i, 1).Value <> vbNullString Then ListBox1.AddItem ws.Cells(i, 1).Value
            If ws.Cells(i, 2).Value <> vbNullString Then ListBox1.List(i - 1, 1) = ws.Cells(i, 2).Value
            If ws.Cells(i, 3).Value <> vbNullString Then ListBox1.List(i - 1, 2) = ws.Cells(i, 3).Value
        Next i
    End Sub
    

提交回复
热议问题