2017-07-10 18 views
1

我在VBA中相對缺乏經驗,但通常可以完成簡單的任務。我目前遇到.Find函數的問題。我知道excel沒有能力做兩個.finds,但我在爲第二次查找編寫循環時遇到了問題。我到目前爲止的代碼是在這裏:在VBA中編程多個.FindNext

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 

我的代碼,以創建第二.Find一個範圍,然後填寫表格位於不同的工作搜索單詞「結構」。我知道這個問題是與多重。找到,但找不到任何我可以完全理解的幫助。

+1

什麼是錯誤您收到?爲什麼在結構的兩端都有星號? –

+0

包含「結構」的單元格可在其任一側上具有文本。我沒有收到錯誤,但在程序找到rng3之後,它變成了新的搜索項目。所以rng2不再搜索「結構」,並且表格不能跳過沒有rng3的單元格。 –

回答

1

您可能更容易將「查找所有匹配」部分抽象爲單獨的函數。這將簡化您的邏輯,並讓真正的任務更易於管理。

注意:這不會在最後一個「* structure *」單元格後面搜索「* 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 
+0

這很棒!非常感謝。我想我需要做更多的教程!在最後一個「結構」單元格之後會有一個「* Class = *」,但至少這會讓我通過一個更多的障礙。 –