|
|
- Option Explicit
- ' 代码逻辑完全相同,如果合并其他列,请自行调整添加
- Sub 删除IL重复项合并Q()
- Dim dict As Object
- Dim lastRow As Long, i As Long
- Dim key As Variant
- ' ** 使用Range对象记录需要删除的行,可以一次性删除多行,效率更高
- Dim delRows As Range
- Dim ws As Worksheet
- Dim t As Double, arr
-
- Set ws = ActiveSheet
- Set dict = CreateObject("Scripting.Dictionary")
- t = Timer
- Application.ScreenUpdating = False
- Application.Calculation = xlCalculationManual
-
- ' 获取最后一行
- lastRow = ws.Cells(ws.Rows.Count, "I").End(xlUp).Row
-
- ' ** 正向循环才能记录首行
- For i = 2 To lastRow
- key = ws.Cells(i, "I").Value & "|" & ws.Cells(i, "L").Value
-
- If dict.exists(key) Then
- arr = dict(key)
- ' 按照不同逻辑合并
- arr(1) = arr(1) & "+" & ws.Cells(i, "J").Value
- arr(2) = arr(2) & "+" & ws.Cells(i, "K").Value
- arr(3) = arr(3) & "+" & ws.Cells(i, "L").Value
- arr(4) = ws.Cells(i, "N").Value
- dict(key) = arr
- If delRows Is Nothing Then
- Set delRows = ws.Cells(i, 1)
- Else
- Set delRows = Application.Union(delRows, ws.Cells(i, 1))
- End If
- Else
- ' 记录首行信息 [行号, 合并列内容]
- dict.Add key, Array(i, ws.Cells(i, "J").Value, _
- ws.Cells(i, "K").Value, ws.Cells(i, "L").Value, _
- ws.Cells(i, "N").Value)
- End If
- Next i
-
- ' 更新首行的Q列合并内容
- For Each key In dict
- i = dict(key)(0)
- ws.Cells(i, "J").Value = dict(key)(1)
- ws.Cells(i, "K").Value = dict(key)(2)
- ws.Cells(i, "L").Value = dict(key)(3)
- ws.Cells(i, "N").Value = dict(key)(4)
- Next
- i = delRows.Cells.Count
- ' ** 一次性删除合并行
- delRows.EntireRow.Delete
-
- MsgBox "处理完成!" & vbCrLf & _
- "合并行数:" & i & vbCrLf & _
- "耗时:" & Format(Timer - t, "0.00") & "秒", _
- vbInformation
- Cleanup:
- Application.ScreenUpdating = True
- Application.Calculation = xlCalculationAutomatic
- Set dict = Nothing
- Set delRows = Nothing
- End Sub
复制代码 |
|