[英]VBA Nested For Loop Crashing Excel
我目前正在嘗試從兩個單獨的工作表中創建所有可能的條目組合的列表,但是每當我嘗試運行它時,Excel都會在大約20秒后崩潰。 有人對如何更有效地使它有效或使它起作用的方法有任何提示嗎? 謝謝!
Sub Create()
Dim dates, groups, current As Integer
Dim dateValue As Date
Dim groupValue As String
Dim cell As Long
Application.ScreenUpdating = False
Sheets(3).Cells.Clear
cell = 1
For dates = 1 To 730
Sheets(1).Select
dateValue = Cells(dates, 1).Value
For groups = 1 To 155
Application.StatusBar = dateValue & " " & groupValue
Sheets(2).Select
groupValue = Cells(groups, 1).Value
Sheets(3).Select
Cells(cell, 1) = dateValue
Cells(cell, 2) = groupValue
cell = cell + 1
Next groups
Next dates
Application.StatusBar = False
Application.ScreenUpdating = True
End Sub
嘗試這個。 您無需繼續選擇工作表,因為這樣做會增加額外的開銷。 而是像這樣引用單元格:
Sub Create()
Dim dates, groups, current As Integer
Dim dateValue As Date
Dim groupValue As String
Dim cell As Long
Application.ScreenUpdating = False
Sheets(3).Cells.Clear
cell = 1
For dates = 1 To 730
dateValue = Sheets(1).Cells(dates, 1).Value
For groups = 1 To 155
Application.StatusBar = dateValue & " " & groupValue
groupValue = Sheets(2).Cells(groups, 1).Value
Sheets(3).Cells(cell, 1) = dateValue
Sheets(3).Cells(cell, 2) = groupValue
cell = cell + 1
Next groups
Next dates
Application.StatusBar = False
Application.ScreenUpdating = True
End Sub
刪除.Select
呼叫。
groupValue = Sheets(2).Cells(groups, 1).Value
勝過
Sheets(2).Select
groupValue = Cells(groups, 1).Value
.Select
速度慢,昂貴且不必要。
狀態欄是否實際更新? 這樣做10萬次同樣是瓶頸。 使用mod計數器每n次迭代更新一次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.