循环浏览当结果只有1行时查找并跳过

时间:2018-06-04 18:57:22

标签: excel vba excel-vba

之前我已经完成了一些基本的VBA,但我仍然对这门语言很新。这是我第一次发帖,所以我希望我发布得很清楚。

我目前正在工作表的E栏中找到具体标准。我当前的代码工作正常,但它不循环,我只希望它复制行,如果有2行或更多行符合该条件。如果只有1行匹配,那么我想跳过它。

在我的下面的代码中,我知道“E04”出现在2行以上,所以我想将这些行复制到名为“Misc”的第二张表中。但是,如果我的标准是“E01”,结果只有一行,那么我想跳过这个并继续搜索“E02”,依此类推。我现在在代码中的循环是继续搜索我命名的条件(“E04”),但我没有循环继续下一个标准。

这是我目前的代码:

Dim FirstAddress As String, _
    cF As Range, _
    RowsToCopy As String

ActiveSheet.Cells(1, 5).Activate
With ActiveSheet.Columns(5)

    Set cF = .Find(What:="E04", _
                After:=ActiveCell, _
                LookIn:=xlFormulas, _
                LookAt:=xlPart, _
                SearchOrder:=xlByColumns, _
                SearchDirection:=xlNext, _
                MatchCase:=False, _
                SearchFormat:=False)

    If Not cF Is Nothing Then
        FirstAddress = cF.Address
        Do
            cF.EntireRow.Copy
            Sheets("Misc").Range("A" & Sheets("Misc").Range("A" & Rows.Count).End(xlUp).Row + 1).PasteSpecial xlPasteValues
            Set cF = .FindNext(cF)

        Loop While Not cF Is Nothing And cF.Address <> FirstAddress
   End If
End With

另外,这里有一点我的工作表看起来像...... Sample Table

你可以看到我想跳过E01-E03,对E04采取行动,然后跳过E05-E09,然后对E10采取行动。

任何帮助都将非常感谢!我一直在网上寻找答案数小时,但没有发现任何对我有用的东西。

1 个答案:

答案 0 :(得分:1)

一种方法是使用COUNTIF公式来检查该术语在E列中出​​现的次数。我不确定您是否也在询问如何循环。我建议您替换ActiveSheet的实际工作表名称,因为它更强大。

Sub x()

Dim FirstAddress As String, _
    cF As Range, _
    RowsToCopy As String
Dim s As String

s = "EO4"

With ActiveSheet.Columns(5)
    If WorksheetFunction.CountIf(.Cells, s) > 1 Then
        Set cF = .Find(What:=s, _
                    LookIn:=xlFormulas, _
                    LookAt:=xlWhole, _
                    SearchOrder:=xlByColumns, _
                    SearchDirection:=xlNext, _
                    MatchCase:=False, _
                    SearchFormat:=False)
        If Not cF Is Nothing Then
            FirstAddress = cF.Address
            Do
                cF.EntireRow.Copy
                Sheets("Misc").Range("A" & Sheets("Misc").Range("A" & Rows.Count).End(xlUp).Row + 1).PasteSpecial xlPasteValues
                Set cF = .FindNext(cF)
            Loop While Not cF Is Nothing And cF.Address <> FirstAddress
        End If
   End If
End With

End Sub