EXCEL VBA将search结果存储在数组中?
正如标题所说,这是可能的和如何?
我已经find了一个.Find
函数来search一个列,我想要的值是否可以保存在一个数组中的所有地址?
代码如下所示:
Set wsRaw = Worksheets("raw_list") Set oRange = wsRaw.Columns(PhaseCol) SearchString = "control" Set aCell = oRange.Find(What:=SearchString, LookIn:=xlValues, _ LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ MatchCase:=False, SearchFormat:=False) If Not aCell Is Nothing Then Set bCell = aCell FoundAt = aCell.Address Do While ExitLoop = False Set aCell = oRange.FindNext(After:=aCell) If Not aCell Is Nothing Then If aCell.Address = bCell.Address Then Exit Do FoundAt = FoundAt & ", " & aCell.Address Else ExitLoop = True End If Loop Else MsgBox SearchString & " not Found" End If MsgBox "The Search String has been found these locations: " & FoundAt Exit Sub
至于现在我有一个MsgBox
只是为了显示结果。 这个想法是如果可能的话将结果存储在一个数组中。
是的,你可以这么做。 看到这个例子
Dim MyResults() As String Dim n As Long n = 1 ' '~~> rest of the code ' If Not aCell Is Nothing Then Set bCell = aCell ReDim Preserve MyResults(n) MyResults(n) = aCell.Address n = n + 1 Do While ExitLoop = False Set aCell = oRange.FindNext(After:=aCell) If Not aCell Is Nothing Then If aCell.Address = bCell.Address Then Exit Do ReDim Preserve MyResults(n) MyResults(n) = aCell.Address n = n + 1 Else ExitLoop = True End If Loop Else MsgBox SearchString & " not Found" End If
然后,您可以稍后循环显示结果
For i = LBound(MyResults) To UBound(MyResults) Debug.Print MyResults(i) Next i