查找并删除单元格值为“#N / A”的行

时间:2015-01-13 16:38:09

标签: excel vba excel-vba find delete-row

我有一个excel文档,用于分析数据集,我带来的每个数据资产都有不同数量的数据。我试图写一个宏,我分配给一个按钮,可以根据单元格的值识别删除行。这是行不通的。我做错了什么?

Sub Button2_Click()
[vb]
'This will find how many rows there are
 With ActiveSheet
    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    MsgBox lastRow
 End With

 Sub sbDelete_Rows_Based_On_Criteria()
     Dim lRow As Long
     Dim iCntr As Long
     lRow = lastRow
     For iCntr = lRow To 1 Step -1
         'Replaces XX with the variable you want to delete
         If Cells(iCntr, 1) = "#N/A" Then
             Rows(iCntr).Delete
         End If
     Next
 End Sub
 [/vb]
End Sub

2 个答案:

答案 0 :(得分:4)

你的逻辑就在那里,但你的语法已经关闭了。此外,您检查A列的值而不是B列(根据您的评论)。

Sub Button2_Click()
    Dim lRow As Long
    'This will find how many rows there are
    With ActiveSheet
        lRow = .Cells(.Rows.Count, "A").End(xlUp).Row
        MsgBox lastRow
    End With

    Dim iCntr As Long
    For iCntr = lRow To 1 Step -1
        'Replace "#N/A" with the value you want to delete
        ' Check column A and B for the value.
        If Cells(iCntr, 1).Text = "#N/A" Or Cells(iCntr, 2).Text = "#N/A" Then
            Rows(iCntr).Delete
        End If
    Next
End Sub

或简化:

Sub Button2_Click()
    Dim iCntr As Long
    For iCntr = Cells(Rows.Count, "A").End(xlUp).Row To 1 Step -1
        'Replace "#N/A" with the value you want to delete
        ' Check column A and B for the value.
        If Cells(iCntr, 1).Text = "#N/A" Or Cells(iCntr, 2).Text = "#N/A" Then
            Rows(iCntr).Delete
        End If
    Next
End Sub

答案 1 :(得分:0)

因为你有两个潜艇,你必须将 lastRow 从一个传递到另一个:

Sub Button2_Click()
'This will find how many rows there are
 With ActiveSheet
    lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    MsgBox lastRow
End With

Call sbDelete_Rows_Based_On_Criteria(lastRow)

End Sub

 Sub sbDelete_Rows_Based_On_Criteria(lastRow)
 Dim lRow As Long
 Dim iCntr As Long
 lRow = lastRow
 For iCntr = lRow To 1 Step -1
    'Replaces XX with the variable you want to delete
    If Cells(iCntr, 1).Text = "#N/A" Then
        Rows(iCntr).Delete
    End If
 Next
 End Sub

注意:

  1. sub unnested
  2. 使用 .Text