首页 > 解决方案 > 用于查找和删除行的 For 循环

问题描述

所以我有一个存储数据的excel wb。

A列是日期,D列是活动,R列是目的地,F列是名称。如果有相同的行,我需要一个 VBA 代码来检查这 4 列。我必须检查日期,然后检查活动等。对于最后一行,直到第一行。如果它发现重复,它应该删除旧的(这就是为什么我认为它应该从最后一行到第一行)。

我决定在数据库中编写代码

Sub DeleteRows()

Dim Rng As Range
Dim LastRow As Long
Dim i As Long

Application.ScreenUpdating = False

LastRow = Cells(Rows.Count, "B").End(xlUp).Row

For i = 1 To LastRow Step 1
If WorksheetFunction.CountIf(Range(Cells(1, "B"), Cells(i, "B")), Cells(i, 
"B")) < LastRow Then
    Rows(i + 1).Delete
End If
Next i

Application.ScreenUpdating = True

End Sub

现在我想不出办法来完成它。我想保留那些红色的 在此处输入图像描述

标签: excelvba

解决方案


尝试

    Public Sub Delete_duplicate_rows()

        Dim R1 As Long, R2 As Long

        R1 = Range("A" & Rows.Count).End(xlUp).Row

        Do While R1 > 1
            R2 = R1 - 1
            Do While R2 > 1
                If Cells(R1, 1) = Cells(R2, 1) Then
                    If Cells(R1, 4) = Cells(R2, 4) Then
                        If Cells(R1, 6) = Cells(R2, 6) Then
                            If Cells(R1, 13) = Cells(R2, 13) Then
                                Rows(R2).Delete
                                R1 = R1 - 1

                            End If
                        End If
                    End If
                End If
                R2 = R2 - 1
            Loop
            R1 = R1 - 1
        Loop

    End Sub

推荐阅读