搜索"工作表"时,Excel VBA将多列拉入列表框



我很难弄清楚如何获得单元格两侧的数据(搜索列B,也需要列a&C中的数据(,以便在预形成搜索时也填充到列表框中。

Dim iSheet As Worksheet
Dim iBook As Workbook
Set iBook = Application.ThisWorkbook
Set iSheet = iBook.Sheets("Bin13In")
Dim A
Dim firstAddress
Me.ListBox1.Clear
With iSheet.Range("B1:B14000")
Set A = .Find(TextBox5.Text, LookIn:=xlValues, LookAt:=xlPart)
If Not A Is Nothing Then
firstAddress = A.Address

Do
Me.ListBox1.AddItem A.Text
Set A = .FindNext(A)
Loop While Not A Is Nothing And A.Address <> firstAddress
Else
MsgBox "Not found"
End If
End With

我尝试了一些不同的东西,但它们似乎都是完全错误的

有几种方法可以用多个列值填充ListBox。

一种方法是将数据写入一个2维数组,并将该数组分配给ListBox的List-属性:

Dim myArr
myArr = iSheet.Range("A2:D10")
Me.ListBox1.List = myArr

然而,在您的情况下,这有点棘手,因为您事先不知道会有多少行。这就导致了需要对每一行使用Redim Preserve的情况。Redim仅适用于数组的最后一个维度,因此您需要将列作为第一个索引,将行作为第二个索引,而列表需要将行作为第一个索引来将列作为第二。要解决此问题,需要在将数组分配给列表时对其进行转置。

ReDim myArr(1 To 3, 1 To 1)
hits = 0
Set A = .Find(TextBox5.Text, LookIn:=xlValues, LookAt:=xlPart)
If Not A Is Nothing Then
firstAddress = A.Address
Do
hits = hits + 1
If UBound(myArr, 2) < hits Then ReDim Preserve myArr(1 To 3, 1 To hits)
myArr(1, hits) = A.Value
myArr(2, hits) = A.Offset(0, -1).value
myArr(3, hits) = A.Offset(0, +1).value
Set A = .FindNext(A)
Loop While Not A Is Nothing And A.Address <> firstAddress
Next
Me.ListBox1.List = Application.Transpose(myArr)

另一种选择是坚持使用代码,并使用带索引的.List属性来编写额外的列值。您只需要知道行和列的索引都以0开头,而不是以1:开头

Do
With Me.ListBox1
.AddItem A.Text
.List(.ListCount - 1, 1) = A.Offset(0, -1)  
.List(.ListCount - 1, 2) = A.Offset(0, 1)
.FindNext(A)
End With
Loop While Not A Is Nothing And A.Address <> firstAddress

最新更新