Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
689 views
in Technique[技术] by (71.8m points)

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

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 tried:

enter image description here

If I tried addItem rng(i,j) then everything would be in 1 column.

I also tried .list but it did not work either.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...