首页 > 解决方案 > 根据特定列中的文本值删除行

问题描述

在此处输入图像描述 我写了一个简短的宏来删除我的工作簿的“预算”选项卡中 I 列中值为“不适用”的所有行。

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

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

我很感激任何帮助!

标签: excelvbaloopsdelete-row

解决方案


您实际上并没有引用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

推荐阅读