如何决定列VBA上的重复值

时间:2017-11-15 14:46:02

标签: vba duplicates

如果我有下表:

Name  | IP      | OS
------+---------+---------
host1 | 1.1.1.1 | Windows
host1 | N/A     | N/A
host1 | 1.1.1.1 | N/A
host1 | N/A     | Windows

如何删除重复项,并保留更多值的行?

输出应该是这样的:

Name  | IP      | OS
------+---------+---------
host1 | 1.1.1.1 | Windows

我试过了ActiveSheet.Range("A:A").RemoveDuplicates Columns:=1但它删除了所有重复的host1,结果就是这个

Name  | IP      | OS
------+---------+---------
host1 | 1.1.1.1 | Windows
      | N/A     | N/A
      | 1.1.1.1 | N/A
      | N/A     | Windows

2 个答案:

答案 0 :(得分:0)

这是我到目前为止所得到的。假设您的数据类似于

原始数据

Name    IP      OS      Country
host1   1.1.1.1 Windows N/A
host1   1.1.1.1 Windows Taiwan
host1   1.1.1.1 N/A     N/A
host1   N/A     N/A     Taiwan
host2   N/A     Apple   N/A
host2   N/A     Apple   Taiwan
host2   N/A     N/A     Taiwan
host2   1.1.1.1 N/A     N/A
host2   1.1.1.1 Apple   Taiwan

输出

Name    IP      OS      Country
host1   1.1.1.1 Windows Taiwan
host2   1.1.1.1 Apple   Taiwan

代码

Private Sub test()
    With ActiveSheet
        Dim i, startRow, endRow As Long
        Dim NACount, LessNACount As Integer
        'Set a large enough number
        LessNACount = 1000
        Dim cell As Range

        'Assuming Row 1 is title
        startRow = 2

        Dim DeleteRange, SameNARange As Range
        'Setting it a dummy range
        Set DeleteRange = .Rows(.Rows.Count)

        For i = 2 To .Range("A" & .Rows.Count).End(xlUp).Row
            NACount = WorksheetFunction.CountIf(.Rows(i), "N/A")
            'Cells with N/A are more than the least row
            If NACount > LessNACount Then
                Set DeleteRange = Union(DeleteRange, .Rows(i))
            'Cells with N/A are equal than the least row
            ElseIf NACount = LessNACount Then
                Set SameNARange = Union(SameNARange, .Rows(i))
            'Cells with N/A are less than the least row, so it becomes the new least row
            Else
                'We have found at least a row, abandon them
                If Not SameNARange Is Nothing Then
                    Set DeleteRange = Union(DeleteRange, SameNARange)
                End If
                Set SameNARange = .Rows(i)
                LessNACount = NACount
            End If

            'host1 is done, goes into host2
            If .Range("A" & i).Value <> .Range("A" & i + 1).Value Then
                LessNACount = 1000
                Set SameNARange = Nothing
            End If
        Next i

        DeleteRange.Delete
    End With
End Sub

答案 1 :(得分:0)

在datapull的SQL中,您可以执行以下操作:

SELECT Name, MAX(IIF( ip <> "N/A", ip)) AS ip, MAX(IIF( os <> "N/A", os)) AS os
FROM table
GROUP BY Name