我遇到了如何将包含多列和多行的数据放入列表框的问题。
假设我有一个范围rng,其中包含多个列和行 我试过了:
如果我尝试了addItem rng(i,j),那么一切都将在1列中。
我也试过.list但它也没有用。
答案 0 :(得分:5)
这是你在尝试的吗?
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
<强>快照强>
答案 1 :(得分:1)
您可以使用foreach将项目添加到列表框
ActiveSheet.Shapes("lstSample").Select
Dim currRange As Range
With Selection
For Each currRange In Range("yourRange")
.AddItem currRange.Value
Next
End With
每个人都会遍历你范围内的每一行和每一行。
答案 2 :(得分:1)
我假设您要填充3列
Dim currRange As Range
Dim i As Integer
With Selection
For Each currRange In Range("yourRange")
i = i + 1
If i = 1 Then .AddItem cell.Value
If i = 2 Then .List(.ListCount - 1, 1) = "1"
If i = 3 Then
.List(.ListCount - 1, 2) = cell.Offset(0, 2).Value
i = 0
End If
Next
End With
我假设你有3列。