【问题标题】:VBA Nested For Loop Crashing ExcelVBA嵌套循环崩溃Excel
【发布时间】:2015-06-30 06:37:39
【问题描述】:

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

【问题讨论】:

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

标签: vba excel for-loop


【解决方案1】:

试试这个。您无需继续选择工作表,因为这将增加 E​​xcel 的额外开销。而是像这样引用单元格:

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

【讨论】:

  • 这样做了,除了将状态栏移到仅更新以反映日期外,效果很好!
【解决方案2】:

删除.Select 调用。

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

优于

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

.Select 速度慢、成本高且不必要。

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

【讨论】:

  • 删除所有 '.Select' 效果很好!感谢您指出状态栏问题,一旦我将其更改为仅反映日期值,那么一切正常。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-01
相关资源
最近更新 更多