VBA嵌套For Loop Crashing Excel

时间:2015-04-22 14:15:06

标签: excel vba excel-vba for-loop

我目前正在尝试从两个单独的工作表创建所有可能的条目组合列表,但每当我尝试运行它时,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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

删除.Select来电。

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

优于

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

.Select既缓慢又昂贵且不必要。

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