我有一个名为(" PPSBoarded")的excel表,有15列。我想根据B列中的类似值选择行,然后在VBA表单的列表框中显示它。我尝试了这个,但它不起作用:
Dim FoundCell As Range
Dim LastCell As Range
Dim FirstAddr As String
With Range("B1:B2")
Set LastCell = .Cells(.Cells.Count)
End With
Set FoundCell = Range("B1:B").Find(what:="EK261/GRU", after:=LastCell)
If Not FoundCell Is Nothing Then
FirstAddr = FoundCell.Address
End If
Do Until FoundCell Is Nothing
Debug.Print FoundCell.Address
Set FoundCell = Range("B1:B").FindNext(after:=FoundCell)
If FoundCell.Address = FirstAddr Then
Exit Do
End If
Loop
Me.ListBox1.List = FirstAddr
答案 0 :(得分:0)
您的代码应如下所示:
Dim arrLstBox()
Dim rng, FoundCell, tmpCell As Range
Dim i, j, numRows, lastColumn, lastRow As Long
Dim FirstAddress, searchFor, colWidth As String
Set rng = ActiveSheet.UsedRange
numRow = 0
With rng
lastRow = .Rows.Count
lastColumn = .Columns.Count
End With
Me.ListBox1.ColumnCount = lastColumn
For x = 1 To lastColumn
If x = lastColumn Then
colWidth = colWidth & "1,5cm"
Exit For
End If
colWidth = colWidth & "1,5cm;"
Next x
Me.ListBox1.ColumnWidths = colWidth
searchFor = InputBox("Your word:")
Set FoundCell = rng.Find(what:=searchFor)
If Not FoundCell Is Nothing Then _
FirstAddress = FoundCell.Address
Do Until FoundCell Is Nothing
Set FoundCell = rng.FindNext(after:=FoundCell)
If FoundCell.Address = FirstAddress Then
numRow = numRow + 1
Exit Do
ElseIf FoundCell.Row <> rng.FindNext(after:=FoundCell).Row Then
numRow = numRow + 1
End If
Loop
ReDim arrLstBox(1 To numRow, 1 To lastColumn)
Do Until FoundCell Is Nothing
For i = 1 To numRow
For j = 1 To lastColumn
If Not IsEmpty(Cells(FoundCell.Row, j).Value) Then
arrLstBox(i, j) = Cells(FoundCell.Row, j).Value
End If
Set FoundCell = rng.FindNext(after:=FoundCell)
Next j
If FoundCell.Address = FirstAddress Then _
Exit For
Next i
If FoundCell.Address = FirstAddress Then _
Exit Do
Loop
Me.ListBox1.List = arrLstBox()