Excel – 一个macros按大列(15K行)列和总和分组

我有一个2列的Excel表,可以有高达15K行。 我需要总结价值,按第一和第二列分组。 目前,我正在使用followinnmacros,代码是复制数据在一张新的工作表,sorting和删除重复的同时添加计数,如果find一个匹配。 到目前为止,我已经testing了500行的项目,这需要花费几分钟的时间,如果有更多的行,我担心所花费的时间(因为可能会多达15K行)。

Sub consolidateData() Dim lRow As Long Dim ItemRow1, ItemRow2 As String Dim lengthRow1, lengthRow2 As String Columns("A:C").Select Selection.Copy Sheets("Sheet3").Select Range("A1").Select ActiveSheet.Paste Cells.Select Selection.Sort _ Key1:=Range("A2"), Order1:=xlAscending, _ Key2:=Range("C2"), Order2:=xlDescending, _ Header:=xlYes, OrderCustom:=1, _ MatchCase:=False, Orientation:=xlTopToBottom, _ DataOption1:=xlSortNormal lRow = 2 Do While (Cells(lRow, 1) <> "") ItemRow1 = Cells(lRow, "A") ItemRow2 = Cells(lRow + 1, "A") lengthRow1 = Cells(lRow, "C") lengthRow2 = Cells(lRow + 1, "C") If ((ItemRow1 = ItemRow2) And (lengthRow1 = lengthRow2)) Then Cells(lRow, "B") = Cells(lRow, "B") + Cells(lRow + 1, "B") Rows(lRow + 1).Delete Else lRow = lRow + 1 End If Loop End Sub 

你能否build议,如果有最快捷的方法来做到这一点。 提前致谢。

Thera是你会做一些改善你的performance的事情:

有一个你可以使用的RemoveDuplica方法,从SOF删除所有重复的行 :

  Sub DeleteRows() With ActiveSheet Set Rng = Range("A1", Range("B1").End(xlDown)) Rng.RemoveDuplicates Columns:=Array(1, 2), Header:=xlYes End With End Sub 

如果您使用预格式化表格,则可以很容易地填写所需信息的新表格

适当时,请使用下面的代码来改善您的function/子performance:

  Application.ScreenUpdating = False 

如果仅复制应分组的列,那么可能会更好,然后将sumifinput到值列中。

希望这是有帮助的。

这是让您的macros更快的一种快速方法。 这将停止animation和其他一些福利。 :)但是,从一开始就重build你的代码将是一个好主意,避免select。

 Sub consolidateData() Dim lRow As Long Dim ItemRow1, ItemRow2 As String Dim lengthRow1, lengthRow2 As String call onstart Columns("A:C").Select Selection.Copy Sheets("Sheet3").Select Range("A1").Select ActiveSheet.Paste Cells.Select Selection.Sort _ Key1:=Range("A2"), Order1:=xlAscending, _ Key2:=Range("C2"), Order2:=xlDescending, _ Header:=xlYes, OrderCustom:=1, _ MatchCase:=False, Orientation:=xlTopToBottom, _ DataOption1:=xlSortNormal lRow = 2 Do While (Cells(lRow, 1) <> "") ItemRow1 = Cells(lRow, "A") ItemRow2 = Cells(lRow + 1, "A") lengthRow1 = Cells(lRow, "C") lengthRow2 = Cells(lRow + 1, "C") If ((ItemRow1 = ItemRow2) And (lengthRow1 = lengthRow2)) Then Cells(lRow, "B") = Cells(lRow, "B") + Cells(lRow + 1, "B") Rows(lRow + 1).Delete Else lRow = lRow + 1 End If Loop call onende End Sub Public Sub OnEnd() Application.ScreenUpdating = True Application.EnableEvents = True Application.AskToUpdateLinks = True Application.DisplayAlerts = True Application.Calculation = xlAutomatic ThisWorkbook.Date1904 = False Application.StatusBar = False End Sub Public Sub OnStart() Application.ScreenUpdating = False Application.EnableEvents = False Application.AskToUpdateLinks = False Application.DisplayAlerts = False Application.Calculation = xlAutomatic ThisWorkbook.Date1904 = False ActiveWindow.View = xlNormalView End Sub