2017-08-28 112 views
0

我有一個簡單的宏,用來在一分鐘內運行。但現在運行速度非常緩慢。大約需要一個小時才能運行。這是因爲我使用的循環?有人能幫我看看出了什麼問題嗎?宏運行緩慢

Sub Runtable() 

Sheets("RateTable").Cells(1, "A") = "ID" 
Sheets("RateTable").Cells(1, "B") = "Section" 
Sheets("RateTable").Cells(1, "C") = "Gender" 
Sheets("RateTable").Cells(1, "D") = "Age" 
     ' 
LastID = Sheets("Input").Cells(2, 22) 
For ID = 0 To LastID 

LastSet = Sheets("Input").Cells(2, 19) 
For myRow = 2 To LastSet 
Sheets("RateTable").Cells(ID * (LastSet - 1) + myRow, 1) = Sheets("Input").Cells(ID + 2, 1) 
Next myRow 
Next ID 
    ' 
Dim myMyRow As Long 
Dim OutputMyRow As Long 
OutputMyRow = 2 

LastID = Sheets("Input").Cells(2, 22) 
LastSection = Sheets("Input").Cells(2, 21) 
LastAge = Sheets("Input").Cells(2, 20) 
For ID = 0 To LastID 
For Section = 0 To LastSection 
For myMyRow = 2 To LastAge 
Sheets("RateTable").Cells(OutputMyRow, 2).Value = Sheets("Input").Cells(Section - FirstID + 2, "N").Value 

OutputMyRow = OutputMyRow + 1 

Next myMyRow 
Next Section 
Next ID 

    ' 
EndGenderLoop = Sheets("Input").Cells(2, 23) 
For myRow = 2 To EndGenderLoop 
Sheets("RateTable").Cells(myRow, 3) = Sheets("Input").Cells(2, 17) 
Next myRow 
    ' 
EndAgeLoop = Sheets("Input").Cells(2, 24) 
For AgeCurve = 0 To EndAgeLoop 
    ' 
For myRow = 2 To 52 
Sheets("RateTable").Cells(AgeCurve * 51 + myRow, 4) = Sheets("Input").Cells(myRow, 10) 
Next myRow 
Next AgeCurve 
' 
End Sub 
+1

關閉計算並在開始時禁用事件和屏幕更新,請務必在最後關閉所有內容。 –

回答

1

使用狀態欄來確定代碼放慢的位置。 Here's one site with simple code(在鏈接失敗的情況下包含在下面),但還有很多其他的。對於代碼來說,與以前相比,現在運行速度慢了60倍,可能表明計算機出了問題。你重新啓動了嗎?你能恢復到以前的備份狀態嗎?

Option Explicit 

Sub StatusBar() 

    Dim x    As Integer 
    Dim MyTimer   As Double 

    'Change this loop as needed. 
    For x = 1 To 250 

     'Dummy Loop here just to waste time. 
     'Replace this loop with your actual code. 
     MyTimer = Timer 
     Do 
     Loop While Timer - MyTimer < 0.03 

     Application.StatusBar = "Progress: " & x & " of 250: " & Format(x/250, "Percent") 
     DoEvents 

    Next x 

    Application.StatusBar = False 

End Sub