我有以下代碼 - 其中大部分是用宏記錄器記錄的。它很慢,似乎有點不可靠(有時需要大約1分鐘,其他時間需要更長的時間)。優化緩慢的VBA代碼
我想知道如果在這裏任何人都可以幫我打掃一下,並得到它更有效地運行。
謝謝!
Sub RemainingMIUL()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Sheets("Sheet2").Select
Columns("A:A").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Sheets("Sheet1").Select
ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort.SortFields.Add Key:=Range _
("L1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortTextAsNumbers
With ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Columns("L:L").Select
Selection.Copy
Sheets("Sheet2").Select
Range("A1").Select
ActiveSheet.Paste
Sheets("Sheet1").Select
Application.CutCopyMode = False
ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort.SortFields.Add Key:=Range _
("A1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortTextAsNumbers
With ActiveWorkbook.Worksheets("Sheet1").AutoFilter.Sort
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Sheets("Sheet2").Select
Range("B2").Select
Dim cell As Range
For Each cell In Range("B2", Cells(Rows.Count, "B").End(xlUp))
If Range("A:A").Find(What:=cell.Value2, LookAt:=xlWhole) Is Nothing Then cell.Interior.Color = vbYellow
Next cell
With Sheets("Sheet2")
For Each cell In .Range("B2", Cells(Rows.Count, "B").End(xlUp))
If .Range("A:A").Find(What:=cell.Value2, LookAt:=xlWhole) Is Nothing Then _
Intersect(.UsedRange, cell.EntireRow).Offset(, 1).Copy _
Sheets("Sheet1").Cells(Rows.Count, "L").End(xlUp).Offset(1)
Next cell
End With
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
End Sub
還沒有來得及看看這個正確的,但你似乎是通過在B列的細胞中循環兩次,所以你也許可以做的代碼更改顏色和代碼在同一個循環內複製。將cell.Interior.Color = vbYellow放在複製代碼下,並在下面添加End If。然後刪除第一個For Each ... Next Cell代碼。在此期間嘗試一下。我相信會有人給你的代碼提供全面的治療。 – Gordon
如果它是一個工作代碼,你只需要優化它然後發佈到[代碼評論](http://codereview.stackexchange.com/) – user3598756