VBA:如果语句在for循环中

时间:2017-11-29 23:39:00

标签: excel vba excel-vba

在尝试在for循环中编写if语句时,我似乎遇到了不匹配错误。

这是我得到错误的代码段。注意,我只在IF条件为真时才得到错误。

Dim lastRow2 As Long
lastRow2 = Worksheets("csvFile").Cells(rows.Count, 1).End(xlUp).Row

Dim r As Integer
For r = 3 To lastRow2
    If Worksheets("csvFile").Cells(r, 1) = "#N/A" Then
        rows(r).EntireRow.delete
    End If
Next r

因此,目标是删除第一个单元格"#N/A"中输入的行作为值。

希望你们能提前帮助和感谢。

2 个答案:

答案 0 :(得分:1)

试试这个:

If WorksheetFunction.IsNA(Worksheets("csvFile").Cells(r, 1)) Then

答案 1 :(得分:0)

为了查看单元格是否包含#NA,您需要捕获此类错误,这是一个两步If

此外,在删除Rows时,总是向后循环,使用For r = lastRow2 To 3 Step -1

尝试下面的代码,代码注释中的解释:

Option Explicit

Sub DelNARows()

Dim lastRow2 As Long
Dim r As Long
Dim CellVal As Variant

With Worksheets("csvFile") ' use with statement to qualify all Range, Rows and Cells object nested inside
    lastRow2 = .Cells(.Rows.Count, 1).End(xlUp).Row

    For r = lastRow2 To 3 Step -1 ' always loop backward when deleting rows
        ' trap #NA error section
        On Error Resume Next
        CellVal = .Cells(r, 1).Value
        On Error GoTo 0

        If IsError(CellVal) Then
            If CellVal = CVErr(xlErrNA) Then ' check if current error if xlErrNA (2042)
                .Rows(r).Delete
            End If
        End If
    Next r
End With

End Sub

编辑1 :删除多行的更快捷的方法是一次删除所有行,而不是一个一个地删除。您可以通过在DelRng(它是一个Range对象中合并要删除的所有行来实现这一点,该对象由需要删除的所有行组合而成。)

<强> 代码

For r = lastRow2 To 3 Step -1
    ' trap #NA error section
    On Error Resume Next
    CellVal = .Cells(r, 1).Value
    On Error GoTo 0

    Dim DelRng As Range ' define a new range to save all the rows to delete

    If IsError(CellVal) Then
        If CellVal = CVErr(xlErrNA) Then ' check if current error if xlErrNA (2042)
            If Not DelRng Is Nothing Then
                Set DelRng = Application.Union(DelRng, .Rows(i))
            Else
                Set DelRng = .Rows(i)
            End If
        End If
    End If
Next r

' delete the entire rows at once
If Not DelRng Is Nothing Then DelRng.Delete