Excel VBA运行时间过长,但没有问题使用步入

我有一些代码删除重复的行,同时保持第一个实例特定的string出现。

当我进入代码删除重复项时,macros运行顺利。 但是,一旦我运行macros,我的Excel冻结并停止响应。 我不太清楚为什么…

如果任何人可以摆脱一些光。 这将不胜感激。 (另外我添加了一个breakline来显示我尝试运行的位置)。

Sub CleanUp() Application.ScreenUpdating = False Application.Calculation = xlCalculationManual Dim lastRow As Integer Dim i As Integer, j As Integer, k As Integer Dim stakedItem As String Dim sortCell As Range, allCell As Range, sortcell2 As Range Dim currentItem As String, baseItem As String lastRow = Sheet2.Range("A" & Sheet2.Rows.Count).End(xlUp).Row Set sortCell = Sheet2.Range("A1") Set sortcell2 = Sheet2.Range("B1") Set allCell = Sheet2.Range("A1:Z" & lastRow + 1) baseItem = Sheet2.Range("B2") allCell.Sort key1:=sortcell2, order1:=xlAscending, Header:=xlYes For i = 3 To lastRow currentItem = Sheet2.Range("B" & i) If currentItem = baseItem Then Sheet2.Rows(i).Delete i = i - 1 lastRow = lastRow - 1 Else baseItem = Sheet2.Range("B" & i) End If Next i Breakline here... allCell.AutoFilter field:=2, Criteria1:=Array("*G*", "*HUB*"), Operator:=xlFilterValues allCell.Sort key1:=sortCell, order1:=xlAscending, Header:=xlYes Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub 

谢谢!

弗朗西斯

如果发现要删除的行,这将永远不会退出。 原因是在For循环中,退出条件在该代码行计算时是固定的。 这意味着lastRow将永远是您进入循环时的任何内容。

此代码说明:

 Sub example() Dim x As Long, i As Long x = 5 For i = 1 To x Debug.Print i 'This runs 5 times... x = 1 '...even though you change x here. Next End Sub 

所以, lastRow = lastRow - 1唯一的做法是减lessvariables 。 在删除第一行之后,可以保证在表格的最后有currentItem = BaseItem 。 在这种情况下,你减less循环计数器,这给你一个无限循环。

正如@TimWilliams在注释中提到的,如果你正在删除行,你应该向后循环。 像这样的东西:

 For i = lastRow To 3 Step -1 currentItem = Sheet2.Range("B" & i) If currentItem = BaseItem Then Sheet2.Rows(i).Delete Else BaseItem = Sheet2.Range("B" & i) End If Next i