2015-04-22 191 views
2

我目前正试图创建一个列表,从两个单独的工作表,所有可能的条目组合,但每当我尝试运行它,大约20秒后Excel崩溃。有没有人有任何提示如何更有效地做到这一点,或一种方法来使这项工作?谢谢!VBA嵌套for循环崩溃Excel

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 
+0

如果一个答案解决了你的问题,你可以点击复选标记来帮助奖励那些帮助你的人:) – bmende

回答

2

删除.Select调用。

groupValue = Sheets(2).Cells(groups, 1).Value 

是优于

Sheets(2).Select 
groupValue = Cells(groups, 1).Value 

.Select是缓慢而昂贵的和不必要的。

状态栏是否实际更新?这样做10万次同样是一个瓶颈;使用mod计数器更新每第n次迭代。

+0

删除所有'.Select'完美无缺!并且感谢您指出状态栏问题,一旦我将其更改为仅反映日期值,然后一切正常。 – DomSchwe

2

试试这个。您不需要继续选择工作表,因为这会增加额外的开销。取而代之的是像这样引用单元格:

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 
+0

这样做除了移动状态栏只更新以反映日期,它工作的很棒! – DomSchwe