【发布时间】:2019-06-22 06:17:59
【问题描述】:
我已经为我的工作相关任务编写了简单的代码,但它在 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 - 这是您的意图吗?您在所有容易出错的地方都使用隐式活动表引用 - 您应该在单元格/范围前面添加工作表名称(或将整个内容包装在 With 语句中并使用点运算符,例如 .Cells)。避免 .Select 并使用 Long 而不是 Integer。
-
是的。在我插入新行后,CoRow 会重新计算我的表中有多少行。此代码由工作表数据上的按钮激活,但你是对的,我应该添加工作表名称。我需要 Selection.Sort 来对我的数据进行排序。
-
您可以确定范围并将其用于您的排序,而不是使用 .Select
-
我已将主程序更改如下: ... Sheets("Imp").Range("A:E").Sort Key1:=Range("C2"), Order1:=xlAscending , Key2:=Range("E2"), Order2:=xlDescending, Header:=xlYes, _ OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _ DataOption1:=xlSortNormal, DataOption2:=xlSortNormal 但是它仍然不超过 530 次迭代。