excel - 在 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 次迭代。我怀疑排序有问题,因为在执行此代码之前它也对相同数量的行进行排序。
解决方案
您的重新计算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 <= iEnd
For
选择
另一种解决方案(如果您插入或删除行)是向后运行循环:
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
,这比一遍又一遍地确定最后一行要快得多。
推荐阅读
- java - 我可以在 Jxls 2+ 的模板和输出格式中使用 .XLSX 吗?
- c# - 从 HttpPostedFileBase 读取 Excel 文件以缓冲流
- xml - XML 输出需要 Xpath 帮助
- python - 最后一个日历月的纪元时间
- django - Django & Celery:我需要 transaction.atomic/locking 来避免竞争条件吗?
- python - 如何在odoo10中为经理创建新的记录规则?
- python - Python - 规范化/标准化字典值
- angular - 验证停止工作
- awk - 使用 awk 对多行记录进行排序
- ios - ReactNative:react-native-router-flux 中的深度链接无法正常工作