excel - 如何找到同一列中每个重复项的最后一行索引?

标签 excel vba

我正在尝试创建一个程序,以便它可以找到位于同一列中的每个重复项的最后一行索引并存储它们的值。例如,在图片中,John、trump、alice 和 sarah 姓名的最后一行索引应该分别给我 13、17、23、26。目前,我的代码只能识别重复项,所以我该怎么做才能找到每个重复项的最后一行索引,不仅适用于我展示的图片,而且适用于所有情况?

enter image description here

Sub Testing()

    Dim mycell As Range, RANG As Range

    With Sheets(1)

        ' Build a range (RANG) between cell F2 and the last cell in column F
        Set RANG = Range(.Cells(2, "A"), .Cells(.Rows.Count, "A").End(xlUp))

    End With

    ' For each cell (mycell) in this range (RANG)
    For Each mycell In RANG

        ' If the count of mycell in RANG is greater than 1, then set the value of the cell 1 across to the right of mycell (i.e. column G) as "Duplicate Found"
        If Application.WorksheetFunction.CountIf(RANG, mycell.Value) > 1 Then

        'how do i find the last row index of each duplicate here?

    Next mycell

End Sub

最佳答案

可以通过多种方式完成。在下面的代码(测试)中使用了字典对象。请添加工具 -> 引用 -> Microsoft Scripting Runtime。

Sub Testing()
    Dim mycell As Range, RANG As Range, Dict As Dictionary, Mname As String, Rng As Range
    Set Dict = New Dictionary
    With Sheets(1)
        ' Build a range (RANG) between cell F2 and the last cell in column F
        Set RANG = Range(.Cells(2, "A"), .Cells(.Rows.Count, "A").End(xlUp))
    End With


    ' For each cell (mycell) in this range (RANG)
    For Each mycell In RANG
        Mname = mycell.Value
        ' If the count of mycell in RANG is greater than 1, then set the value of the cell 1 across to the right of mycell (i.e. column G) as "Duplicate Found"
        If Application.WorksheetFunction.CountIf(RANG, mycell.Value) > 1 Then


        If Dict.Count > 0 And Dict.Exists(Mname) Then
        Dict(Mname) = mycell.Row()
        Else
        Dict.Add Mname, mycell.Row()
        End If

        End If
    Next mycell


    'Display result in debug window (Modify to your requirement)
    Startrow = 2
    For Each Key In Dict.Keys
    Set Rng = Sheets(1).Range("A" & Startrow & ":A" & Dict(Key))
    Startrow = Dict(Key) + 1
    ' Now may copy etc the range Rng
    Debug.Print Key, Dict(Key), Rng.Address
    Next



End Sub

修改代码以提供范围对象(从评论中理解)

关于excel - 如何找到同一列中每个重复项的最后一行索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60860839/

相关文章:

excel - 错误处理-将#NUM转换为零

java - Excel POI API 更改单元格值

excel - 在Excel宏中选择范围

excel - 在 Excel 中过滤大型列表的最佳方法是什么?

excel - 我正在使用宏来进行邮件合并,如何在单词输出中保留中文数字?

excel - 从过滤表的一列复制/粘贴/计算可见单元格

Excel公式: If cell contains substring "this" AND does not contain substring "that"

arrays - Excel VBA : two dimensional array with variable and time stamp

excel - 遍历工作表/EXCEL VBA 中的所有(即使分组)形状

vba - 可以使用 IDTExtensibility2 为 VBA IDE 创建 64 位插件吗?