我正在电子表格上运行以下代码:
Do While i <= 100000
If Not Cells(i, 4) = "String" Then
Cells(i, 4).EntireRow.Delete
End If
i = i + 1
Loop
Run Code Online (Sandbox Code Playgroud)
有很多条目不是“ String”,但它们不会被删除。
当我将这段代码复制到单独的工作表时,我什至收到错误“Excel 无法使用可用资源完成此任务。选择较少的数据或关闭其他应用程序。”
我做错了什么导致这个循环不起作用?
注意:我无法使用自动筛选,因为我需要根据不满足条件删除行。
这是一个基本的算法错误。
假设您的程序位于第 10 行。您将其删除。因此,第 11 行变为第 10 行,第 12 行变为第 11 行,依此类推。然后转到第 11 行,跳过第 10 行,之前的第 11 行!
这会起作用:
Do While i <= 100000
If Not Cells(i, 4) = "String" Then
Cells(i, 4).EntireRow.Delete
Else
i = i + 1
End If
Loop
Run Code Online (Sandbox Code Playgroud)