用于删除条件重复的VBA代码

时间:2015-07-16 09:55:39

标签: excel vba excel-vba

我在表1列A到L

中有一些数据

我想删除F列中的重复ID,其中L列中没有数据,或者所有重复项中都存在数据,请保留1。

我想将数据返回到表2

示例:

   1                 00:20:21
   2                 00:00:20

应该返回

create view viewname as
SELECT * FROM
(
  SELECT msg.no as MessageNum
       ,msg.jobno as JobNumber
       ,msg.timedate as MessageCreateTime
       ,ROW_NUMBER() OVER(PARTITION BY msg.no ORDER BY msg.timedate DESC) as RNK
       from allmessages
 ) 
WHERE RNK=1

2 个答案:

答案 0 :(得分:0)

它必须是VBA吗?我会这样做:

按列F和L对数据进行排序 在单元格M2中输入以下公式:

=IF(AND(L2=L1,F2=F1),"","X")

然后,要么过滤数据,其中列M等于'X',要么按列M排序,然后您将获得非重复数据,您可以将其复制并粘贴到新位置。

答案 1 :(得分:0)

在这里,我的解决方法是:

Public Sub removeDuplicate()

    Dim row, innerRow, resultRow, index As Integer

    'Create array for no of data row in Sheet1
    Dim finishedRow(10) As String

    row = 1
    resultRow = 1
    index = 1

    With Sheets("Sheet1")

        'Loop until ID cell is blank
        Do While .Range("F" & row) <> ""

            If UBound(Filter(finishedRow, row)) < 0 Then

                'Add row to finished record
                finishedRow(index) = row
                index = index + 1

                'Store first data in result sheet
                Sheets("Sheet2").Range("A" & resultRow) = .Range("F" & row)
                Sheets("Sheet2").Range("B" & resultRow) = .Range("L" & row)

                innerRow = 1

                'Find duplicate data and compare and if need, modify old data
                Do While .Range("F" & innerRow) <> ""

                    'If this row is not finished in checking
                    If UBound(Filter(finishedRow, innerRow)) < 0 Then

                        'If ID are equal
                        If .Range("F" & row) = .Range("F" & innerRow) Then

                            'If new time is greater than old time
                            If .Range("L" & row) < .Range("L" & innerRow) Then

                                'Update time in result record
                                Sheets("Sheet2").Range("B" & resultRow) = .Range("L" & innerRow)

                            End If

                            'Add row to record array
                            finishedRow(index) = innerRow
                            index = index + 1

                        End If

                    End If

                    'Increase inner row
                    innerRow = innerRow + 1

                Loop

                'Increase result row
                resultRow = resultRow + 1

            End If

            'Increase row
            row = row + 1

        Loop

    End With

End Sub