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

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

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 

你的逻辑很多,但你的语法是closures的。 此外,您只是检查列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 

因为你有两个subs,你必须把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. 子是unnested
  2. 使用.Text