[英]VBA Nested For Loop Crashing Excel
I am currently trying to create a list of all possible combinations of entries from two separate sheets, but whenever I try to run it, Excel crashes after about 20 seconds. 我目前正在尝试从两个单独的工作表中创建所有可能的条目组合的列表,但是每当我尝试运行它时,Excel都会在大约20秒后崩溃。 Does anybody have any tips for how to make this more efficiently, or a way to make this work? 有人对如何更有效地使它有效或使它起作用的方法有任何提示吗? Thanks! 谢谢!
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
Try this. 尝试这个。 You don't need to keep selecting the sheets as this will an an additional overhead to excel. 您无需继续选择工作表,因为这样做会增加额外的开销。 Instead just reference the cell like so: 而是像这样引用单元格:
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
Remove the .Select
calls. 删除.Select
呼叫。
groupValue = Sheets(2).Cells(groups, 1).Value
Is better than 胜过
Sheets(2).Select
groupValue = Cells(groups, 1).Value
.Select
is slow and expensive and unnecessary. .Select
速度慢,昂贵且不必要。
Does the statusbar actually update? 状态栏是否实际更新? doing so 100k times is likewise a bottleneck; 这样做10万次同样是瓶颈。 use a mod counter to update every nth iteration. 使用mod计数器每n次迭代更新一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.