选择范围取决于两个关键词

时间:2019-02-05 20:00:48

标签: excel vba

我目前正在研究创建VBA以自动删除空白行的项目。我在帮助下创建了以下内容:

    Dim rngFirst As Range
    Dim rngLast As Range

    Application.ScreenUpdating = False

    With Sheets("Input")
        'Find the start and stop
        Set rngFirst = .Cells.Find(what:="[Performance Income]", lookat:=xlWhole, _
            LookIn:=xlValues, MatchCase:=False)
        Set rngLast = .Cells.Find(what:="[Miscellaneous Income]", _
            lookat:=xlWhole, LookIn:=xlValues, MatchCase:=False)

        .Range(rngFirst, rngLast).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
    End With

    Application.ScreenUpdating = True

我遇到1004运行时错误。我一直在寻找与我的范围选择有关的原因。但是我具体不知道,我希望得到帮助。先感谢您。

1 个答案:

答案 0 :(得分:0)

这对我有用。

您必须确保第一个范围是最后一个范围之前的单元格,并且它们位于同一列中。否则会引发错误。

要定义新范围,请使用开始和结束范围的Address属性。

Sub DeleteBlankCells()

    Dim rngFirst As Range
    Dim rngLast As Range

    Dim rngUnion As Range
    Application.ScreenUpdating = False

    With Sheets("Input")
        'Find the start and stop
        Set rngFirst = .Cells.Find(what:="Performance Income", lookat:=xlWhole, _
            LookIn:=xlValues, MatchCase:=False)
        Set rngLast = .Cells.Find(what:="Miscellaneous Income", _
            lookat:=xlWhole, LookIn:=xlValues, MatchCase:=False)

        Set rngUnion = Range(rngFirst.Address, rngLast.Address)

        rngUnion.SpecialCells(xlCellTypeBlanks).EntireRow.Delete

    End With

    Application.ScreenUpdating = True

End Sub