VBA代码删除不正确的行

时间:2016-12-14 20:43:12

标签: excel vba excel-vba

我有这段代码,如果在D到L列中有空单元格,则删除一行 出于某种原因,它也删除了位于C8的标题单元格 谁知道为什么?以及如何解决它?

Sub RemoveEmptyRows()

Dim ws As Worksheet
For Each ws In Sheets
ws.Activate

  Dim n As Long
    Dim nlast As Long
    Dim rw As Range
    Set rw = ActiveWorkbook.ActiveSheet.UsedRange.Rows
    nlast = rw.count
    For n = nlast To 1 Step -1
        If (rw.Cells(n, 4).Value = "" And rw.Cells(n, 5).Value = "" And rw.Cells(n, 6).Value = "" And rw.Cells(n, 7).Value = "" And rw.Cells(n, 8).Value = "" And rw.Cells(n, 9).Value = "" And rw.Cells(n, 10).Value = "" And rw.Cells(n, 11).Value = "") Then
            rw.Rows(n).Delete
        End If
    Next n
    Next ws
End Sub

4 个答案:

答案 0 :(得分:3)

问题是您使用UsedRange的行索引和列索引,并假设它们与Worksheet的索引匹配。情况不一定如此。正如你在评论中指出@ YowE3K,你有一些完全空的列。

解决方案非常简单 - 只需使用ws.Cells代替rw.Cells即可。我还将循环中的所有内容放入With块中,以使其更快,更易读。您还可以将该If语句转换为Select Case阶段,从而使该Sub RemoveEmptyRows() Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets With ws Dim n As Long Dim nlast As Long nlast = .UsedRange.Rows(.UsedRange.Rows.Count).Row For n = nlast To 9 Step -1 Select Case False Case .Cells(n, 4).Value = vbNullString Case .Cells(n, 5).Value = vbNullString Case .Cells(n, 6).Value = vbNullString Case .Cells(n, 7).Value = vbNullString Case .Cells(n, 8).Value = vbNullString Case .Cells(n, 9).Value = vbNullString Case .Cells(n, 10).Value = vbNullString Case .Cells(n, 11).Value = vbNullString Case Else .Rows(n).Delete End Select Next n End With Next ws End Sub 语句短路:

A1:A2

请注意,还有更可靠的方法来查找工作表的最后一行。

答案 1 :(得分:1)

你的标题是在C8中,然后在第1行之前不要删除:

替换

For n = nlast To 1 Step -1

通过

For n = nlast To 9 Step -1

答案 2 :(得分:0)

这是你的代码稍加修改。

Sub RemoveEmptyRows()

    Dim ws As Worksheet
    Dim n As Long
    Dim nlast As Long
    Dim rw As Range

    For Each ws In Worksheets 'changed. In case there are Chart Sheets.
    'deleted ws.activate. AVOID THAT AS PLAGUE
        Set rw = ws.UsedRange.Rows
        With rw
            nlast = .Count
            For n = nlast To 2 Step -1 'Note the 2, to skip title row. As was pointed in comments.
                If (.Cells(n, 4).Value2 = "" And .Cells(n, 5).Value2 = "" And .Cells(n, 6).Value2 = "" And .Cells(n, 7).Value2 = "" And .Cells(n, 8).Value2 = "" And .Cells(n, 9).Value2 = "" And .Cells(n, 10).Value2 = "" And .Cells(n, 11).Value2 = "") Then
                    .Rows(n).Delete
                End If
            Next n
        End With 'rw
    Next ws
End Sub

答案 3 :(得分:0)

你可以尝试这个(未经测试的)代码:

Sub RemoveEmptyRows()
    Dim ws As Worksheet
    Dim nCols As Long

    For Each ws In Sheets
        With Intersect(.Range("D:K"), .UsedRange)
            nCols = .Columns.Count
            With .SpecialCells(xlCellTypeBlanks)
                For iArea = .Areas.Count To 1 Step -1
                    If .Areas(iArea).Count = nCols Then .Areas(iArea).EntireRow.Delete
                Next
            End With
        End With
    Next ws  
End Sub