如果在单元格中找不到内容/文本/数字,则清除整行

时间:2015-12-06 16:44:26

标签: excel vba excel-vba

我正在编写一个VBA脚本,如果发现行中的一个单元格为空或者没有任何文本或整数值,则会删除整行的(清除内容)。

我几乎就在那里,但我认为我的代码卡在for循环中。请告诉我如何进一步改进我的代码。

    Sub Remove_Rows_BlankData()
          For SheetCount = 1 To Sheets.Count  'SHEET LEVEL

        Sheets(SheetCount).Visible = True
        Sheets(SheetCount).Select
        StartRow = 2
        ' EndRow = Cells(ActiveSheet.UsedRange.Rows.Count, 34)
        LastRow = ActiveSheet.UsedRange.Rows.Count
        LastCol = ActiveSheet.UsedRange.Columns.Count
        Dim myRange As Range
        Set myRange = Range(Cells(StartRow, 1), Cells(LastRow, LastCol))         
        'REMOVE ROWS W/ ANY BLANK CELLS

        Dim DRow As Variant  ' Sets DRow = Row w/ Blank
            'From start row to last row

        Cells.SpecialCells(xlCellTypeBlanks).EntireRow.Select
        Selection.ClearContents


         Next

        End Sub  

1 个答案:

答案 0 :(得分:1)

我已经重写了你的sub,以避免使用Select工作表来使用它。通过使用With ... End With statement引用循环中的每个工作表,可以处理每个工作表的单元格和属性,而无需选择¹工作表只是为了使用ActiveSheet的固有关联。

Sub Remove_Rows_BlankData()
    Dim ws As Long, fr As Long, lr As Long, lc As Long

    On Error Resume Next   'just in case there are no blank cells

    For ws = 5 To Worksheets.Count  'SHEET LEVEL
        With Worksheets(ws)

            .Visible = True
            'Sheets(SheetCount).Select  'not necessary to select in order to process
            fr = 2
            ' EndRow = Cells(ActiveSheet.UsedRange.Rows.Count, 34)
            lr = .UsedRange.Rows.Count
            lc = .UsedRange.Columns.Count

            With .Range(.Cells(fr, 1), .Cells(lr, lc))
                .SpecialCells(xlCellTypeBlanks).EntireRow.ClearContents
            End With

        End With
    Next ws

End Sub

请注意,循环内不会创建变量(也就是Dim);只重新分配的值。

¹有关远离依赖选择和激活以实现目标的更多方法,请参阅How to avoid using Select in Excel VBA macros