2017-07-10 16 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 = *”,但至少这会让我通过一个更多的障碍。 –