2012-07-03 81 views
1

正如標題所說,這是可能的和如何?EXCEL VBA將搜索結果存儲在數組中?

我找到.Find函數來搜索列的值,我想要的是,然後可以將所有地址保存在數組中?

的代碼看起來是這樣的:

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只是爲了顯示結果。如果可能的話,這個想法是將結果存儲在一個數組中。

回答

1

是的,你可以做到這一點。看到這個例子

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 
+0

非常感謝你的快速回復! – Andreas

+1

這很容易,考慮到你從我的博客拿起代碼的事實:D –

+0

哦,然後雙倍謝謝你:) – Andreas