[英]Delete an entire row if the term in the first and second column are duplicated below but leave one
I'm currently having an issue which I don't think i can resolve.我目前有一个我认为我无法解决的问题。 I have a table in excel with multiple titles such as “Promoter”, “Account”, “#order”, “Date” & “City” with thousands of rows in it.我在 excel 中有一个表,其中包含多个标题,例如“Promoter”、“Account”、“#order”、“Date”和“City”,其中包含数千行。 I just want to know if there is a VBA code to delete specific rows with duplicated values if those were to appear in 2 columns (A and B) Such as if the “Account” and the “Promoter” are the same in many other rows, i just want to delete the duplicates and leave one for accounting purposes.我只想知道是否有 VBA 代码来删除具有重复值的特定行,如果这些行出现在 2 列(A 和 B)中,例如“帐户”和“促销员”在许多其他行中是否相同,我只想删除重复项并留下一个用于会计目的。
Example:例子:
Data数据
0987:Raymond:ORD-27:NY
1256:Hannah :ORD-99:MI
1345:André :ORD-45:WI
1866:Darryl :ORD-02:WA
6419:John. :ORD-22:CA
0987:Raymond:ORD-87:MN
0987:Raymond:ORD-24:CO
Result:
1256:Hannah :ORD-99:MI
1345:André :ORD-45:WI
1866:Darryl :ORD-02:WA
6419:John. :ORD-22:CA
0987:Raymond:ORD-87:MN
Because the “account” (09087) and the “Promoter” (Raymond) are repeated in the rows below even though the order and the state are different, i just want to delete the duplicates that fall in that category (Same account and Promoter) and keep one because the orders belong to the same account.因为即使订单和 state 不同,“帐户”(09087)和“发起人”(Raymond)在下面的行中重复,我只想删除属于该类别的重复项(相同的帐户和发起人)并保留一个,因为订单属于同一个帐户。 There are several “promoters” to consider, that's why I don't know how to proceed.有几个“发起人”需要考虑,这就是为什么我不知道如何进行。
Thank you very much for your help i will appreciate every answer.非常感谢您的帮助,我将感谢您的每一个回答。
The Code编码
Option Explicit
Sub keepUniqueTwoColumns()
Const wsName As String = "Sheet1"
Const First As Long = 2
Const ColLR As String = "A"
Const Col1 As String = "A"
Const Col2 As String = "B"
Const Delimiter As String = "|"
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
Dim Last As Long: Last = ws.Cells(ws.Rows.Count, ColLR).End(xlUp).Row
Dim rg1 As Range: Set rg1 = ws.Cells(First, Col1).Resize(Last - First + 1)
Dim rg2 As Range: Set rg2 = ws.Cells(First, Col2).Resize(Last - First + 1)
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
Dim drg As Range
Dim cel As Range
Dim Key As Variant
Dim i As Long
For Each cel In rg1.Cells
i = i + 1
Key = rg1.Cells(i) & Delimiter & rg2.Cells(i)
If dict.Exists(Key) Then
If drg Is Nothing Then
Set drg = rg1.Cells(i)
Else
Set drg = Union(drg, rg1.Cells(i))
End If
Else
dict.Add Key, Empty
End If
Next cel
Set dict = Nothing
If drg Is Nothing Then
MsgBox "Nothing deleted.", vbExclamation, "Fail"
Else
Dim dCount As Long: dCount = drg.Cells.Count
drg.EntireRow.Delete
MsgBox "Deleted rows: " & dCount, vbInformation, "Success"
End If
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.