Vba my for循环只删除了一半的行

时间:2017-10-31 15:03:08

标签: vba excel-vba for-loop delete-row excel

我正在为投注计算做一个宏。我有以下双循环用于删除与if匹配的行,但它只删除了真正匹配的行的一半

Sub calc()

    Dim db As String
    db = Worksheets("PRONO").Range("A1").Value

    Dim alldata As Workbook
    Dim i1 As Worksheet

    Set alldata = Workbooks(db)
    Set i1 = alldata.Worksheets("I1")



    For Each Match In Workbooks("BET EXCEL.xlsm").Worksheets("TEST").Range("A14:" & Range("A14").End(xlDown).Address)

        For Each Data In i1.Range("B2:" & i1.Range("B2").End(xlDown).Address)

            If CDate(Data.Value) > CDate(Match.Value) Then
                MsgBox (Data.Row)
                i1.Rows(Data.Row).Delete

            End If

        Next




    Next


End Sub

为什么呢?

我无法理解

如果有人可以帮助我

1 个答案:

答案 0 :(得分:1)

这很简单。当您删除时,让我们说,第五行,下面的所有行都会上升。那么,排在第六位的是现在的第五位。但是你的循环进入了最近的第六个(前七个),跳过这个曾经是第六个。 使用WITH cte AS ( select * ,SUM(CASE WHEN InOutMode=1 THEN 0 ELSE 1 END) -- SUM(1-InOutMode) OVER(PARTITION BY EmpCode ORDER BY ID) s from test1 ), cte2 AS ( SELECT *, ROW_NUMBER() OVER(PARTITION BY EmpCode, s ORDER BY id) as rn FROM cte ), cte3 AS ( SELECT *, MAX(rn) OVER(PARTITION BY EmpCode, s) AS m FROM cte2 ) DELETE FROM cte3 WHERE rn > 1 AND rn <> m; SELECT * FROM test1; 向上删除行。 (啊,必须先计算lastRow)。