How to populate data from a range (multiple rows and columns) to listbox with VBA

前端 未结 3 1063
长情又很酷
长情又很酷 2021-01-14 09:23

I am having trouble with how to put the data from the range with multiple columns and rows to a listbox.

Assume I have a range rng which multiple columns and rows I

3条回答
  •  执笔经年
    2021-01-14 10:02

    Is this what you are trying?

    Option Explicit
    
    Private Sub CommandButton1_Click()
        Dim ws As Worksheet
        Dim rng As Range
        Dim i As Long, j As Long, rw As Long
        Dim Myarray() As String
    
        '~~> Change your sheetname here
        Set ws = Sheets("Sheet1")
    
        '~~> Set you relevant range here
        Set rng = ws.Range("A1:E5")
    
        With Me.ListBox1
            .Clear
            .ColumnHeads = False
            .ColumnCount = rng.Columns.Count
    
            ReDim Myarray(rng.Rows.Count, rng.Columns.Count)
    
            rw = 0
    
            For i = 1 To rng.Rows.Count
                For j = 0 To rng.Columns.Count
                    Myarray(rw, j) = rng.Cells(i, j + 1)
                Next
                rw = rw + 1
            Next
    
            .List = Myarray
    
            '~~> Set the widths of the column here. Ex: For 5 Columns
            '~~> Change as Applicable        
            .ColumnWidths = "50;50;50;50;50"
            .TopIndex = 0
        End With
    End Sub
    

    SNAPSHOT

    enter image description here

提交回复
热议问题