在VBA中编写多个.FindNext

我在VBA方面相对缺乏经验,但通常可以完成简单的任务。 我目前有一个与.Find函数的问题。 我知道excel没有能力做两个.finds,但我有问题编码循环第二次查找。 我到目前为止的代码在这里:

Dim j As Integer Dim Total As Integer Total = Application.CountIf(Sheets("Output").Range("A:A"), "*Structure*") Dim class As String class = "CLASS =" Dim str As String str = "Structure" With Sheets("output") Set rng1 = .Range("A:A").Find(str, lookat:=xlPart) row1 = rng1.Row Set rng2 = .Range("A:A").FindNext(rng1) row2 = rng2.Row For j = 6 To Total + 5 If Application.WorksheetFunction.CountIf(Sheets("output").Range("A" & row1 & ":A" & row2), "*" & class & "*") > 0 Then Set rng3 = .Range("A" & row1 & ":A" & row2).Find(class, lookat:=xlPart) Sheets("sheet2").Cells(7, j).Value = Mid(rng3, 9, 3) Else Sheets("sheet2").Cells(7, j).Value = "" End If row1 = row2 Set rng2 = .Range("A:A").FindNext(rng2) row2 = rng2.Row Next j End With 

我有代码search单词“结构”为了创build第二个范围。find然后填写在不同的工作表上的表。 我知道这个问题是与多重。find,但找不到任何我可以完全理解的帮助。

您可能会发现将“查找所有匹配”部分抽象为单独的函数更容易。 这将简化您的逻辑,并使真正的任务更容易pipe理。

注意:这不会在最后一个“* structure *”单元之后search“* CLASS = *” – 目前尚不清楚您是否需要这样做。

 Sub Tester() Dim found As Collection, i As Long, f As Range, v With ActiveSheet 'start by finding all of the "structure" cells... Set found = FindAll(.Range("A:A"), "*Structure*") 'then loop over them... For i = 1 To found.Count - 1 v = "" Set f = .Range("A" & found(i).Row & ":A" & _ found(i + 1).Row).Find("*CLASS =*") If Not f Is Nothing Then v = Mid(f, 9, 3) Sheets("Sheet2").Cells(7, 5 + i).Value = v Next i End With End Sub 

FindAll函数:

 Public Function FindAll(rng As Range, val As String) As Collection Dim rv As New Collection, f As Range Dim addr As String Set f = rng.Find(what:=val, after:=rng.Cells(rng.Cells.Count), _ LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, _ SearchDirection:=xlNext, MatchCase:=False) If Not f Is Nothing Then addr = f.Address() Do Until f Is Nothing rv.Add f Set f = rng.FindNext(after:=f) If f.Address() = addr Then Exit Do Loop Set FindAll = rv End Function