Excel For 循环 VBA 宏不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13363959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 18:28:57  来源:igfitidea点击:

Excel For Loop VBA Macro not working

excelvbaexcel-vba

提问by John Bale

I have an excel spread sheet with 2 columns, with the last row being 287983. In column A there's numbers, if a cell doesn't have a number NaNis placed there. In, column B there's dates. I'm trying to use the following macro to remove all rows where cells in column A have NaN:

我有一个 2 列的 excel 电子表格,最后一行是287983. 在 A 列中有数字,如果单元格没有数字,则在NaN那里放置数字。在 B 列中有日期。我正在尝试使用以下宏删除 A 列中的单元格具有的所有行NaN

Sub Rowdel()
    Dim i As Long
    For i = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
        If Cells(i, 1) = "NaN" Then Cells(i, 1).EntireRow.Delete
    Next i
End Sub

However, when I run the above code, the NaNcells are still there. Can anyone suggest why the code isn't working?

但是,当我运行上面的代码时,NaN单元格仍然存在。谁能建议为什么代码不起作用?

回答by JustinJDavies

Make sure that this code is referencing the correct Worksheet. You are probably running the code on the wrong worksheet, which contains no NaNin column A and thus leads to no deletions or other visible signs of the code running.

确保此代码引用了正确的工作表。您可能在错误的工作表上运行代码,该工作表NaN在 A 列中包含 no ,因此不会导致代码运行的任何删除或其他可见迹象。

You could try to debug this code using the following (debug-only) version:

您可以尝试使用以下(仅限调试)版本调试此代码:

Sub Rowdel()
    Dim i As Long
    For i = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
        Cells(i, 1).Select
        If Cells(i, 1) = "NaN" Then Cells(i, 1).EntireRow.Delete
    Next i
End Sub

From the Excel VBA window, execute the sub using F8, which will allow you to step through the code and check which worksheet you are referencing.

在 Excel VBA 窗口中,使用 执行子F8,这将允许您单步执行代码并检查您正在引用哪个工作表。