这是我昨天发布的持续时间的后续活动,“这段代码为什么会导致无限循环”
首先运行“ SortByEcode”需要5.51秒 接下来运行“ KeepEcode”需要1.65秒
但是,如果我从“ KeepEcode”中调用“ SortByEcode”,则KeepEcode需要4分钟54秒才能运行。
Sub EcodeKeep()
'Needs REH to be sorted first by ECode
TurnOffFunctionality ' Turn off Calculations, DisplayStatusBar, EnableEvents and ScreenUpdating
Dim i As Long
Dim j As Long
Dim LastRow As Long
Dim StartTime As Double
'Sort REH by ECode first
Call SortByEcode 'THIS IS STILL THE BIG PROBLEM
Dim wks As Worksheet
Set wks = rawData5 'Work in sheet("RawEquipHistory")
LastRow = wks.Range("A" & Rows.Count).End(xlUp).Row
StartTime = Timer
Dim Ecodes() As Variant
Ecodes = Application.Transpose(wks.Range("A1:A" & LastRow).Value)
Dim Results As Variant
ReDim Results(UBound(Ecodes) - 1)
wks.Range("AM1") = "ECODE KEEP" 'Add the header to "S1"
For i = LBound(Results) To UBound(Results) - 1
Results(i) = Ecodes(i + 1) <> Ecodes(i + 2)
Next i
'wks.Range("AM2:AM" & i + 1).Value = Results 'I cannot get this line of code to work at all, so added a "write" loop
' outside of maim loop
For j = 0 To i
wks.Range("AM" & j + 2) = Results(j)
Next j
TurnOnFunctionality ' Turn back on at the end
Call EndTimer("EcodeKeep", StartTime)
End Sub
Sub SortByEcode()
TurnOffFunctionality ' Turn off at the start
Dim LastRow As Long
LastRow = ThisWorkbook.Sheets("RawEquipHistory").Range("A" & Rows.Count).End(xlUp).Row
With ThisWorkbook.Sheets("RawEquipHistory").Sort ' SORT sheet by E-Code(a)
.SortFields.Clear
.SortFields.Add Key:=Range("A1:A" & LastRow), Order:=xlAscending
.SetRange Range("A1:AZ" & LastRow)
.Header = xlYes
.Apply
End With
TurnOnFunctionality ' Turn back on at the end
Debug.Print "SortByEcode is Done"
End Sub
此外,我根本无法运行Mathieu Guindon @MathieuGuindonto提供的代码行。该代码不会引发任何错误,但是Range(“ AM2:AM”&LastRow)中的每个单元都等于TRUE。但是,如果我遍历Range(“ AM2:AM”&LastRow)并一次写入一个值,则会得到正确的值。
如果我循环并调试.Pring Results(i),我会在立即窗口中获得正确的结果。所以我知道Results数组具有正确的值。
wks.Range("AM2:AM" & i + 1).Value = Results