以下VBA代码需要很长时间才能执行。我25分钟前跑了48,000行,它仍在运行。我怎样才能缩短执行时间?VBA代码需要很长时间才能执行
Sub delrows()
Dim r, RowCount As Long
r = 2
ActiveSheet.Columns(1).Select
RowCount = UsedRange.Rows.Count
userresponse = MsgBox("You have " & RowCount & " rows", vbOKOnly, "Info")
Rows(RowCount).Delete Shift:=xlUp
' Trim spaces
Columns("A:A").Select
Selection.Replace What:=" ", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, searchFormat:=False, _
ReplaceFormat:=False
' Delete surplus columns
Range("L:T,V:AA,AE:AG,AR:AR,AU:AU,AZ:AZ").Select
Selection.Delete Shift:=xlToLeft
' Delete surplus rows
Do
If Left(Cells(r, 1), 1) = "D" _
Or Left(Cells(r, 1), 1) = "H" _
Or Left(Cells(r, 1), 1) = "I" _
Or Left(Cells(r, 1), 2) = "MD" _
Or Left(Cells(r, 1), 2) = "ND" _
Or Left(Cells(r, 1), 3) = "MSF" _
Or Left(Cells(r, 1), 5) = "MSGZZ" _
Or Len(Cells(r, 1)) = 5 _
Or Cells(r, 3) = 0 Then
Rows(r).Delete Shift:=xlUp
ElseIf Int(Right(Cells(r, 1), 4)) > 4000 Then
Rows(r).Delete Shift:=xlUp
Else: r = r + 1
End If
Loop Until (r = RowCount)
End Sub
您应该使用一个变量数组或一个不起眼的IF测试(手动或使用VBA),可以用'使用AutoFilter'删除符合指定条件的行。切勿使用范围循环 - 但如果这样做,请删除底部以避免跳过行 – brettdj
总是对每个变量进行变暗,以确保您在每个程序中都使用Option Explicit。通过转到工具>选项>(打勾)需要变量声明来默认进行设置。另外Dim A,B as Integer将A标注为Variant或Object,您将不得不分别声明每个变量的类型! –
此外,如果我没有错误的VBA不短路,因此所有在IF或与...或...或IF中的比较将被考虑。也许考虑这样一种情况,而不是选择和引用不同的子与代码对所有这些案件...... –