首页 > 解决方案 > 在 VBA 中 For 循环在大约 530 次迭代后停止执行

问题描述

我已经为我的工作相关任务编写了简单的代码,但是它在 530 迭代时停止执行而没有任何错误消息,而我仍然有一些应该处理的数据。

试图删除 VBA 中的所有代码并从记事本中粘贴。试过调试器。尝试重新启动excel和pc。

Function CoRow() As Long
    CoRow = Cells(Rows.Count, 1).End(xlUp).Row
End Function

Sub Sort()
    Dim LastNace As Integer
    Dim NextNace As Integer
    Dim i As Long
    LastNace = Cells(2, "C").Value
    NextNace = Cells(3, "C").Value
    Columns("A:E").Select
    Selection.Sort Key1:=Range("C2"), Order1:=xlAscending, Key2:=Range("E2"), Order2:=xlDescending, Header:=xlYes, _
        OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
        DataOption1:=xlSortNormal, DataOption2:=xlSortNormal
    For i = 1 To CoRow
        If LastNace <> NextNace And LastNace <> 0 And NextNace <> 0 And i <> 1 Then
            Rows(i + 1).EntireRow.Insert
            Range(Cells(i + 1, 1), Cells(i + 1, 5)).Interior.Color = RGB(255, 255, 0)
            i = i + 1
        ElseIf LastNace <> NextNace And LastNace <> 0 And NextNace = 0 And i <> 1 Then
            Rows(i + 1).EntireRow.Insert
            Range(Cells(i + 1, 1), Cells(i + 1, 5)).Interior.Color = RGB(255, 255, 0)
            i = i + 1
        End If
        LastNace = Cells(i + 1, "C").Value
        NextNace = Cells(i + 2, "C").Value
        'Range(Cells(i + 1, 3).Address(), Cells(i + 1, 3).Address()).Interior.Color = RGB(255, 0, 0)
    Next i
End Sub

预期结果是超过 530 次迭代。我怀疑排序有问题,因为在执行此代码之前它也对相同数量的行进行排序。

标签: excelvba

解决方案


您的重新计算CoRow不会影响循环的结束!

请注意,在For循环中,一旦循环开始

For i = 1 To CoRow

的任何值变化CoRow都不会影响循环的结束For循环始终使用CoRow循环开始时设置的值。

以下示例:

Dim i As Long
Dim iEnd As Long
iEnd = 10

For i = 1 To iEnd
    iEnd = 20 'this has NO EFFECT on the end of the For loop
    Debug.Print i, iEnd
Next i

这个循环只会运行,1 … 10因为一旦循环开始,For i = 1 To iEnd任何变化iEnd = 20都不会影响循环的结束。


解决方案

Do循环替换它。

Dim i As Long
Dim iEnd As Long
iEnd = 10

i = 1 'initialization needed before Do loops

Do While i <= iEnd
    iEnd = 20
    Debug.Print i, iEnd

    i = i + 1 'manual increase of counter needed in the end of Do loops
Loop

请注意,对于Do循环,您需要初始化计数器i = 1并手动增加它i = i + 1。这次更改iEnd = 20生效并且循环从开始运行,1 … 20因为循环在每次Do迭代时评估条件(不仅仅是在循环开始时)。i <= iEndFor

选择

另一种解决方案(如果您插入或删除行)是向后运行循环:

Dim CoRow As Long 'make it a variable not a function then
CoRow = Cells(Row.Count, 1).End(xlUp).Row

Dim i As Long
For i = CoRow To 1 Step -1
    'runs backwards starting at the last row ending at the first
Next i

但是,这是否可能取决于您的数据以及您在循环中执行的操作。


改进

请注意,这CoRow = Cells(Rows.Count, 1).End(xlUp).Row会消耗一些时间。与其将CoRow函数设为变量,不如在每次插入一行时将其增加 1 CoRow = CoRow + 1,这比一遍又一遍地确定最后一行要快得多。


推荐阅读