如果列a中的单元格是唯一的,则更改代码以删除行

时间:2014-02-17 18:41:18

标签: excel-vba vba excel

我需要删除A列中唯一值的所有行

我从这个帖子delete non duplicate data in excel using VBA找到了

1 stuffa
2 stuffb
2 stuffc
2 stuffd
3 stuffe
4 stufff
5 stuffg
5 stuffh

2 stuffb
2 stuffc
2 stuffd
5 stuffg
5 stuffh

由于

我的尝试,它运行但没有任何反应 编辑现在可以使用

Sub DeleteUnique()
Dim ws As Worksheet
Dim i As Long, lRow As Long
Dim delRange As range

'~~> This is your sheet
Set ws = Sheets("Sheet2")

With ws
'~~> Get the last row which has data in Col A
lRow = .range("A" & .Rows.Count).End(xlUp).Row

'~~> Loop through the rows
For i = 2 To lRow
    '~~> For for multiple occurances
    If .Cells(i, 1).Value <> "" Then
    If Application.WorksheetFunction.CountIf(.Columns(1), .Cells(i, 1)) = 1 Then
            '~~> Store thee row in a temp range
            If delRange Is Nothing Then
                Set delRange = .Rows(i)
            Else
                Set delRange = Union(delRange, .Rows(i))
            End If
        End If
    End If
Next
End With

'~~> Delete the range
If Not delRange Is Nothing Then delRange.Delete

End Sub

原文:Siddharth Rout

Option Explicit

Sub mukjizat2()
Dim ws As Worksheet
Dim i As Long, lRow As Long
Dim delRange As Range

'~~> This is your sheet
Set ws = ThisWorkbook.Sheets("process")

With ws
    '~~> Get the last row which has data in Col A
    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    '~~> Loop through the rows
    For i = 2 To lRow
        '~~> For for multiple occurances
        If .Cells(i, 2).Value <> "" And .Cells(i, 3).Value <> "" Then
            If Application.WorksheetFunction.CountIf(.Columns(2), .Cells(i, 2)) = 1 And _
            Application.WorksheetFunction.CountIf(.Columns(3), .Cells(i, 3)) = 1 Then
                '~~> Store thee row in a temp range
                If delRange Is Nothing Then
                    Set delRange = .Rows(i)
                Else
                    Set delRange = Union(delRange, .Rows(i))
                End If
            End If
        End If
    Next
End With

'~~> Delete the range
If Not delRange Is Nothing Then delRange.Delete
End Sub

0 个答案:

没有答案