以下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中的比較將被考慮。也許考慮這樣一種情況,而不是選擇和引用不同的子與代碼對所有這些案件...... –