2013-11-15 451 views
0

我想執行一種嵌套的查找請求,用例是我需要在一張工作表上查找一個組,如果找到了該用戶ID值從找到的行中的單獨列中找到,然後在另一張表中搜索該ID。然後它應該執行一系列操作,然後在第一張表中找到組的下一個發生。在vba Excel中查找多個請求(在Find中查找)

我的代碼是

LookupGroup = Split("GroupName1,GroupName2", ",") 
For I = 0 To UBound(LookupGroup) 
    With Worksheets("RawData").Range("C:C") 
     Set C = .Find(LookupGroup(I), LookIn:=xlValues) 
     If Not C Is Nothing Then 
      FirstAddress = C.Address 
      Do 
       LookupId = Sheets("RawData").Cells(C.Row, 7).Value 
       IdExist = False 
       'Check to ensure ID does not exists on Team Members Tab 
       Set IdRange = Sheets("Team Members").Range("A:A").Find(LookupId, LookIn:=xlValues) 
       If IdRange Is Nothing Then 
        IdExist = True 
       End If 
       If Not IdExist Then 
        Highlight = True 'trigger to Set row to bold red font 
        If RecordsFound > 0 Then 
         TotalRecords = TotalRecords + RecordsFound 
        End If 
       End If 
       Set C = .FindNext(C) 
      Loop While Not C Is Nothing And C.Address <> FirstAddress 
     End If 
    End With 
Next I 

這通過正常工作的第一次,但是在到達集C = .FindNext(C)該命令將返回「無」,而不是下一個occurence。

如果我註釋掉第二個發現

Set IdRange = Sheets("Team Members").Range("A:A").Find(LookupId, LookIn:=xlValues) 

然後第一個搜索工作正常,並認爲所有實例

我在做什麼錯?

+1

不能嵌套兩個獨立的'查找()'都是這樣。一種解決方案是首先找到所有「Group」單元,將它們放入數組或集合中,然後遍歷集合並進行團隊成員查找。或者在內循環中使用'Match()'而不是Find –

回答

4

容易採取查找()的邏輯,並把它放在一個單獨的函數...

Sub Tester() 
Dim LookupGroup, rngGrp As Range, rngMember As Range, I 
Dim g As Range, m As Range 

    LookupGroup = Split("GroupName1,GroupName2", ",") 

    For I = 0 To UBound(LookupGroup) 

     Set rngGrp = FindAll(Worksheets("RawData").Range("C:C"), LookupGroup(I)) 

     If Not rngGrp Is Nothing Then 
      For Each g In rngGrp.Cells 

       Set rngMember = FindAll(Sheets("Team Members").Range("A:A"), _ 
             g.EntireRow.Cells(7)) 

       If Not rngMember Is Nothing Then 
        For Each m In rngMember.Cells 
         'do something with m 
        Next m 
       Else 
        'flag not found... 
       End If 
      Next g 
     End If 
    Next I 

End Sub 

'find all matching cells in a given range 
Function FindAll(rngLookIn As Range, LookFor) As Range 

    Dim rv As Range, c As Range, FirstAddress As String 
    With rngLookIn 
     Set c = .Find(LookFor, LookIn:=xlValues, lookat:=xlWhole) 
     If Not c Is Nothing Then 
      FirstAddress = c.Address 
      Set rv = c 
      Do 
       Set c = .FindNext(c) 
       If Not c Is Nothing Then Set rv = Application.Union(rv, c) 
      Loop While Not c Is Nothing And c.Address <> FirstAddress 
     End If 
    End With 
    Set FindAll = rv 
End Function