【问题标题】:Find and delete Rows where cell value is "#N/A"查找并删除单元格值为“#N/A”的行
【发布时间】:2015-01-13 16:38:09
【问题描述】:

我有一个 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

【问题讨论】:

  • 对不起,我不明白你是怎么写这个问题的;你的 excel 电子表格是什么样的?您是说每一行都是一个条目,但每个条目可以有任意数量的列?你能添加一个截图。当您按下按钮时,究竟会发生什么?删除与单元格匹配的行?
  • 当我点击按钮时,我需要它来评估 A 列和 B 列并删除带有#N/A 的行。只有一列必须包含 N/A 才能满足删除的要求。我使用电子表格作为模板,因此每次使用 SS 时我的行数都会有所不同。

标签: vba excel find delete-row


【解决方案1】:

你的逻辑差不多,但你的语法是错误的。此外,您检查 A 列的值,而不是 B 列(根据上面的 cmets)。

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

【讨论】:

  • 我得到一个错误 Run-Time '13" type mismatch on this line If Cells(iCntr, 1).Value = "#N/A" Or Cells(iCntr, 2).Value = " #N/A" 然后
  • @Dan - 我在发布后意识到您正在寻找 Excel 错误(标记为“#NA”)。我更新了使用Text 属性而不是Value 的答案。这应该可以解决错误。
【解决方案2】:

因为你有两个 sub,你必须将 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. 子是未嵌套的
  2. 使用 .Text

【讨论】:

    猜你喜欢
    • 2015-08-08
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 2017-03-07
    • 2014-03-14
    相关资源
    最近更新 更多