根据特定列中的文本值删除行

Deleting Rows Based on Text Values in Specific Column

我已经为我的工作簿的 "Budget" 选项卡编写了一个简短的宏来删除 I 列中值为 "Not Applicable" 的所有行。

当我 运行 通过我的测试时,宏似乎没有做任何事情:

Sub Remove_NA_Macro_Round_2()
    With Sheets("Budget") 'Applying this macro to the "Budget" sheet/tab.

        'Establishing our macro range parameters
        Dim LastRow As Long
        Dim i As Long

        'Setting the last row as the ending range for this macro
        LastRow = .Range("I50").End(xlUp).Row

        'Looping throughout all rows until the "LastRow" ending range set above
        For i = LastRow To 1 Step -1
            If .Range("I" & i).Value = "Not Applicable" Then
                .Range("I" & i).EntireRow.Delete
            End If
        Next
    End With
End Sub

感谢任何帮助!

您实际上并没有引用 With Sheets("Budget")。在 Range 的每个实例之前添加一个句点 .,否则会有一个隐含的 ActiveSheet,它不一定是预算选项卡。

With Sheets("Budget") 
    ...

    LastRow = .Range("I50").End(xlUp).Row

    ...
        If .Range("I" & i).Value = "Not Applicable" Then
            .Range("I" & i).EntireRow.Delete
        End If
    ...

End With

编辑:

根据评论和您提供的屏幕截图,更改 LastRow 的确定方式(去掉硬编码的 I50):

LastRow = .Cells(.Rows.Count, "I").End(xlUp).Row

或者,当根据条件删除行时,使用过滤器比循环更快。

Dim rng As Range
Set rng = ThisWorkbook.Sheets("Sheet1").Range("A1:I" & Cells(Rows.Count, "I").End(xlUp).Row)

Application.DisplayAlerts = False
    With rng
        .AutoFilter
        .AutoFilter field:=9, Criteria1:="Not Applicable"
        rng.Resize(rng.Rows.Count - 1).Offset(1).SpecialCells(xlCellTypeVisible).Delete 'deletes the visible rows below the first row
        .AutoFilter
    End With
Application.DisplayAlerts = True