VBA:If语句在for循环中
在尝试在for循环中编写if语句时,我似乎遇到了一个不匹配错误 这是我得到错误的代码片段。注意,我只在IF条件为true时得到错误VBA:If语句在for循环中,vba,excel,Vba,Excel,在尝试在for循环中编写if语句时,我似乎遇到了一个不匹配错误 这是我得到错误的代码片段。注意,我只在IF条件为true时得到错误 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
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”
的行
希望你们能提前帮上忙并表示感谢 试试看:
If WorksheetFunction.IsNA(Worksheets("csvFile").Cells(r, 1)) Then
为了查看单元格是否包含
#NA
,您需要捕获此类错误,这是一个两步if
此外,在删除行时始终向后循环,对于r=lastRow2到3步骤-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
中合并所有要删除的行来实现这一点(它是一个范围
对象,由所有需要删除的行组合而成)
代码
尝试单元格(r,1)。value
尝试了它,不幸的是它不起作用。也许添加(也会添加到开场白)的好方法是,我只有在条件为真时才会得到错误。您是否尝试过双等于:如果工作表(“csvFile”)。单元格(r,1)=“#N/A”,那么
@kurdtpage这不是VBA中比较的工作方式。我需要在喝咖啡之前停止评论。。。可能是重复的谢谢你,这似乎是工作。我将进一步测试它。不知道我做了什么不同,但它为我删除了行。我错了,它也为我删除了行。谢谢
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