【发布时间】:2015-11-17 22:32:06
【问题描述】:
我有一个用户表单,可以搜索工作表上的信息。它应该在名为“lbSrchMatchingResults”的列表框中显示匹配搜索条件的行;不幸的是,它只显示每个匹配行的第一列。我的解决方案基于 CPearson (http://www.cpearson.com/excel/findall.aspx) 和 Jon Acampora (http://www.excelcampus.com/tools/find-all-vba-form-for-excel/) 提供的代码。下面列出了负责填充列表框的子例程:
Private Sub FindAllMatches()
'Find all matches on activesheet
Dim SearchRange As Range
Dim FindWhat As Variant
Dim FoundCells As Range
Dim FoundCell As Range
Dim arrResults() As Variant
Dim lFound As Long
Dim lSearchCol As Long
Dim lLastRow As Long
Dim rw As Range, c As Long '<<<< added
'Do search if text in find box is longer than 1 character.
If Len(FSearchAssets.tbSrchSearchString.Value) > 1 Then
Set SearchRange = ActiveSheet.UsedRange.Cells
FindWhat = FSearchAssets.tbSrchSearchString.Value
'Calls the FindAll function
Set FoundCells = FindAll(SearchRange:=SearchRange, _
FindWhat:=FindWhat, _
LookIn:=xlValues, _
LookAt:=xlPart, _
SearchOrder:=xlByColumns, _
MatchCase:=False, _
BeginsWith:=vbNullString, _
EndsWith:=vbNullString, _
BeginEndCompare:=vbTextCompare)
If FoundCells Is Nothing Then
ReDim arrResults(1 To 1, 1 To 2)
arrResults(1, 1) = "No Results"
Else
'Add results of FindAll to an array
ReDim arrResults(1 To FoundCells.Count, 1 To 14)
lFound = 1
For Each FoundCell In FoundCells
'add the matching value and address
'arrResults(lFound, 1) = FoundCell.Value
'arrResults(lFound, 2) = FoundCell.Address
Set rw = FoundCell.EntireRow 'get the full row for the found cell
'add the first 13 values from that row to the listbox
For c = 1 To 13
'arrResults(lFound, 2 + c) = rw.Cells(c).Value
arrResults(lFound, c) = rw.Cells(c).Value
Next c
lFound = lFound + 1
Next FoundCell
End If
'Populate the listbox with the array
Me.lbSrchMatchingResults.List = arrResults
Else
Me.lbSrchMatchingResults.Clear
End If
End Sub
【问题讨论】:
-
FoundCells只包含一个单元格。 -
我已经验证它可以容纳多个单元格。如果您在工作表上插入包含多列示例代码的代码,您会看到它将包含多个单元格。
-
For Each FoundCell In FoundCells我的意思是前者。 -
你建议我如何解决我的问题?
-
用循环而不是数组逐行转储?其他人可能会建议更好的架构。
标签: vba excel listbox listboxitem