使用数组通过查找循环

时间:2017-12-06 19:02:51

标签: excel excel-vba vba

这是我的代码,它几乎可以工作但只传递数组的第一部分。我认为它是第二个结束,但如果我删除它。它说没有下一个没有,即使因为部分是在循环的开始。有人可以告诉我,我做错了。

Sub findEG()
Dim rng, s, e As Range
Dim rws As Long, w As Long
Dim vWHATs As Variant

lastrow = Worksheets("MOO_filtered").Range("B" & Rows.Count).End(xlUp).Row

vWHATs = Array("LIFES - Sup Life - Sps", "LIFEE - Sup Life - Emp", "LIFEC - Supp Life - Ch", _
               "VLTD  - Vol LTD MOO", "VSTD  - Vol STD MOO")

With Worksheets("MOO Data")   
For w = LBound(vWHATs) To UBound(vWHATs)
Set r = .Range("B:B").Find(vWHATs)

      If Not r Is Nothing Then
        Set e = .Range("B:B").Find("Totals for:", r)
        If Not e Is Nothing Then
            .Range(r, e).EntireRow.Copy Worksheets("MOO_filtered").Range("A" & lastrow) 
        End If

      End If
Next w

End With
End Sub

1 个答案:

答案 0 :(得分:0)

我已经测试了下面的代码,我相信它可以做你想做的事情:

Sub findEG()
Dim rng, s As Range
Dim rws As Long, w As Long
Dim vWHATs As Variant
lastrow = Worksheets("MOO_filtered").Range("B" & Rows.Count).End(xlUp).Row

vWHATs = Array("LIFES - Sup Life - Sps", "LIFEE - Sup Life - Emp", "LIFEC - Supp Life - Ch", _
               "VLTD  - Vol LTD MOO", "VSTD  - Vol STD MOO")

With Worksheets("MOO Data")
For w = LBound(vWHATs) To UBound(vWHATs)
Set r = .Range("B:B").Find(vWHATs(w)) 'included the (w) so the array values go in sequence in the For Loop
      If Not r Is Nothing Then
        Set e = .Range("B:B").Find("Totals for:" & r.Value & "*") ' here are you sure you are looking for the possible string: "Totals for:LIFES - Sup Life - Sps" without the space between the :?
        If Not e Is Nothing Then
            .Rows(r.Row & ":" & e.Row).EntireRow.Copy Worksheets("MOO_filtered").Range("A" & lastrow +1)
        End If

      End If
Next w
End With
End Sub