excel,VBA,重复值

时间:2017-07-06 15:05:42

标签: excel vba excel-vba duplicates

我有一个大型电子表格,我被要求编辑。基本上,无论数据来自何处,它都会创建几个重复的个人姓名,国家/地区,开始日期和结束日期。是否可以在相邻单元格中获取开始和停止日期并删除重复数据?

我提供了一个屏幕截图。手动复制,粘贴和删除需要很长时间,因为此电子表格有超过2300行,其中大约50%是需要编辑的重复项。

enter image description here

感谢

2 个答案:

答案 0 :(得分:1)

这里不需要VBA,只需添加一个包含以下公式的新列:

=CONCATENATE(C1,D1)

将列字母替换为开始日期和结束日期的列字母。

然后,您可以在新列上使用Excel删除重复项功能(数据 - >删除重复项)

enter image description here

enter image description here

答案 1 :(得分:0)

使用SQL是合适的。

Sub myQuery()
    Dim strSQL  As String
    Dim strTable As String
    Dim Ws As Worksheet

    strTable = "[" & ActiveSheet.Name & "$]"

    strSQL = "SELECT NAME, COUNTRY, MIN([Start Date]) as [Start Date] , max([End Date]) as [End Date] "
    strSQL = strSQL & " FROM " & strTable & " "
    strSQL = strSQL & " Where not isnull(NAME) "
    strSQL = strSQL & " Group by NAME, COUNTRY "

    Set Ws = Sheets.Add

    exeSQL strSQL, Ws

End Sub

Sub exeSQL(strSQL As String, Ws As Worksheet)

    Dim Rs As Object
    Dim strConn As String
    Dim i As Integer

    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=" & ThisWorkbook.FullName & ";" & _
            "Extended Properties=Excel 12.0;"


    Set Rs = CreateObject("ADODB.Recordset")
    Rs.Open strSQL, strConn

    If Not Rs.EOF Then
         With Ws
            .Range("a1").CurrentRegion.ClearContents
            For i = 0 To Rs.Fields.Count - 1
               .Cells(1, i + 1).Value = Rs.Fields(i).Name
            Next
            .Range("a" & 2).CopyFromRecordset Rs
            .Columns.AutoFit
        End With
    End If
    Rs.Close
    Set Rs = Nothing
End Sub