VBA:如果语句在for循环

当我试图在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 

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

希望你们可以提前帮忙,谢谢。

试试这个:

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

为了查看一个单元格是否包含#NA您需要捕获这种types的错误,这是一个2步骤的If

另外,在删除行时allways向后循环,使用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 
Interesting Posts