循环停止太快

时间:2016-02-15 07:46:30

标签: excel vba excel-vba

代码应该通过一系列数据并在两个不同的列中搜索特定变量,并将数据粘贴到另一个表中。我没有得到正确的结果(Christo和Paid)。

以下是代码。

Sub Cop()

    Dim x As Integer
    Dim y As Integer
    Dim z As Integer
    Dim a As Integer
    Dim NumRows As Long

    Sheets("Not_Paid").Select
    If Range("B2") = 1 And Range("B4") = 1 Then
        Sheets("Microinvest").Select
        Range("A1").Select

        ' Set numrows = number of rows of data.
        NumRows = Range(ActiveCell, ActiveCell.End(xlDown)).Rows.Count

        ' Establish "For" loop to loop "numrows" number of times.
        For x = 1 To NumRows
            y = x + 1
            z = x + 7
            a = x - 1
            Sheets("Microinvest").Select
            Range("A" & y).Select
            If ActiveCell.Offset(a, 2) = "Christo" And ActiveCell.Offset(a, 4) = "Paid" Then
                Range("A" & y, "F" & y).Select
                Selection.Copy
                Sheets("Not_Paid").Select
                Range("A" & z).Select
                ActiveSheet.Paste
            End If
        Next
    End If

    Sheets("Not_Paid").Select

End Sub

以下是我正在使用的数据示例:

Data Output

我得到的值Blagoevgrad和NotPaid不应该被拿起来。或者至少那是我印象中的事情。

此外,x变量循环通过84行而不是389,这是我的范围的实际行数。

1 个答案:

答案 0 :(得分:3)

我认为这有效:

Sub Cop()
    Dim nRows As Long, rw As Long, cnt As Long

    cnt = 10 'Start output in row 10 on sheet Not_Paid

    If Worksheets("Not_Paid").Range("B2") = 1 And Worksheets("Not_Paid").Range("B4") = 1 Then

        With Sheets("Microinvest")
            nRows = .Range("A1").End(xlDown).Row

            For rw = 1 To nRows
                If .Range("A" & rw).Offset(0, 2) = "Christo" And .Range("A" & rw).Offset(0, 4) = "Paid" Then
                    .Range("A" & rw & ":F" & rw).Copy Destination:=Worksheets("Not_Paid").Range("B" & cnt)
                    cnt = cnt + 1
                End If
            Next
        End With

    End If
End Sub