【问题标题】:Excel VBA - Delete empty rowsExcel VBA - 删除空行
【发布时间】:2012-03-11 21:19:00
【问题描述】:

我想删除我的 ERP 报价单生成的空行。我正在尝试浏览文档(A1:Z50),对于单元格中没有数据的每一行(A1-B1...Z1 = emptyA5-B5...Z5 = empty)我想删除它们。

我找到了这个,但似乎无法为我配置。

On Error Resume Next
Worksheet.Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete
On Error GoTo 0

【问题讨论】:

  • 你试过用C:C代替A:A,是吗?
  • Serg,看来我解释我的问题是错误的。我需要检查一整行 (A1-Z1) 以查看它是否为空,这一直到 A50-Z50。
  • 因此,对于您而言,“整行”是 A-Z 列,而不是 AA...ZZ...?
  • 是的,A1 到 Z1 列对我来说是一整行。如果这些单元格(A1 到 Z1)中没有任何项目,则该行为空并且可以删除。

标签: vba excel


【解决方案1】:

试试这个

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Range("A" & i & ":" & "Z" & i)
            Else
                Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

如果您想删除整行,请使用此代码

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Rows(i)
            Else
                Set DelRange = Union(DelRange, Rows(i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

【讨论】:

  • 感谢您的努力,不确定是否有效,但它比我接受的sn-p长一点。
  • @Tom:时间更长,因为我使用了正确的编码方式来处理所有错误。无论如何离开它;)
  • 哦,抱歉 :) 不过我只需要快速修复。感谢您提供详尽的示例:)
【解决方案2】:

怎么样

sub foo()
  dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A1:Z50")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
  Next
End Sub

【讨论】:

  • 还不错,只是有点太长了,不适合我的需要。不过,可能有同样问题的其他人会在你的例子中得到帮助;)
【解决方案3】:

要使 Alex K 的回答更加动态,您可以使用以下代码:

Sub DeleteBlankRows()

Dim wks As Worksheet
Dim lngLastRow As Long, lngLastCol As Long, lngIdx As Long, _
    lngColCounter As Long
Dim blnAllBlank As Boolean
Dim UserInputSheet As String

UserInputSheet = Application.InputBox("Enter the name of the sheet which you wish to remove empty rows from")

Set wks = Worksheets(UserInputSheet)

With wks
    'Now that our sheet is defined, we'll find the last row and last column
    lngLastRow = .Cells.Find(What:="*", LookIn:=xlFormulas, _
                             SearchOrder:=xlByRows, _
                             SearchDirection:=xlPrevious).Row
    lngLastCol = .Cells.Find(What:="*", LookIn:=xlFormulas, _
                             SearchOrder:=xlByColumns, _
                             SearchDirection:=xlPrevious).Column

    'Since we need to delete rows, we start from the bottom and move up
    For lngIdx = lngLastRow To 1 Step -1

        'Start by setting a flag to immediately stop checking
        'if a cell is NOT blank and initializing the column counter
        blnAllBlank = True
        lngColCounter = 2

        'Check cells from left to right while the flag is True
        'and the we are within the farthest-right column
        While blnAllBlank And lngColCounter <= lngLastCol

            'If the cell is NOT blank, trip the flag and exit the loop
            If .Cells(lngIdx, lngColCounter) <> "" Then
                blnAllBlank = False
            Else
                lngColCounter = lngColCounter + 1
            End If

        Wend

        'Delete the row if the blnBlank variable is True
        If blnAllBlank Then
            .rows(lngIdx).delete
        End If

    Next lngIdx
End With


MsgBox "Blank rows have been deleted."

 End Sub

这源自this website,然后稍作调整以允许用户选择他们想要从哪个工作表中清空删除的行。

【讨论】:

    【解决方案4】:

    这对我很有用(您可以根据需要调整 lastrow 和 lastcol):

    Sub delete_rows_blank2()
    
    t = 1
    lastrow = ActiveSheet.UsedRange.Rows.Count
    lastcol = ActiveSheet.UsedRange.Columns.Count
    
    Do Until t = lastrow
    
    For j = 1 To lastcol
        'This only checks the first column because the "Else" statement below will skip to the next row if the first column has content.
        If Cells(t, j) = "" Then
    
            j = j + 1
    
                If j = lastcol Then
                Rows(t).Delete
                t = t + 1
                End If
    
        Else
        'Note that doing this row skip, may prevent user from checking other columns for blanks.
            t = t + 1
    
        End If
    
    Next
    
    Loop
    
    End Sub
    

    【讨论】:

      【解决方案5】:

      为了使 On Error Resume 功能起作用,您必须声明工作簿和工作表值

      On Error Resume Next  
      ActiveWorkbook.Worksheets("Sheet Name").Columns("A:A").SpecialCells(xlCellTypeBlanks).EntireRow.Delete  
      On Error GoTo 0
      

      我遇到了同样的问题,这消除了所有空行而无需实现 For 循环。

      【讨论】:

        【解决方案6】:

        我知道我迟到了,但这里有一些我编写/使用的代码来完成这项工作。

        Sub DeleteERows()
            Sheets("Sheet1").Select
            Range("a2:A15000").Select
            Selection.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
        End Sub
        

        【讨论】:

        • 给这个人一枚该死的勋章。迄今为止最古老、最简单的解决方案。
        • 如果至少有一个空单元格会删除整行吗?
        【解决方案7】:

        对于那些有兴趣删除“空”和“空白”行的人(Ctrl + Shift + End 深入工作表).. 这是我的代码。 它将在每张表中找到最后一个“真实”行并删除剩余的空白行。

        Function XLBlank()
            For Each sh In ActiveWorkbook.Worksheets
                sh.Activate
                Cells(1, 1).Select
                lRow = Cells.Find(What:="*", _
                    After:=Range("A1"), _
                    LookAt:=xlPart, _
                    LookIn:=xlFormulas, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row
                
                Range("A" & lRow + 1, Range("A1").SpecialCells(xlCellTypeLastCell).Address).Select
                On Error Resume Next
                Selection.EntireRow.SpecialCells(xlBlanks).EntireRow.Delete
                Cells(1, 1).Select
            Next
            ActiveWorkbook.Save
            ActiveWorkbook.Worksheets(1).Activate
        End Function
        

        打开 VBA ( ALT + F11 ),插入 -> 模块, 复制我的代码并按 F5 启动它。 瞧瞧:D

        【讨论】:

          【解决方案8】:

          当您只想删除完全为空的行但不删除单个空单元格时,我还有另一种情况。它也可以在 Excel 之外使用,例如关于通过 Access-VBA 或 VB6 访问 Excel。

          Public Sub DeleteEmptyRows(Sheet As Excel.Worksheet)
              Dim Row As Range
              Dim Index As Long
              Dim Count As Long
          
              If Sheet Is Nothing Then Exit Sub
          
              ' We are iterating across a collection where we delete elements on the way.
              ' So its safe to iterate from the end to the beginning to avoid index confusion.
              For Index = Sheet.UsedRange.Rows.Count To 1 Step -1
                  Set Row = Sheet.UsedRange.Rows(Index)
          
                  ' This construct is necessary because SpecialCells(xlCellTypeBlanks)
                  ' always throws runtime errors if it doesn't find any empty cell.
                  Count = 0
                  On Error Resume Next
                  Count = Row.SpecialCells(xlCellTypeBlanks).Count
                  On Error GoTo 0
          
                  If Count = Row.Cells.Count Then Row.Delete xlUp
              Next
          End Sub
          

          【讨论】:

          • 有效,只是我建议使用Sub DeleteEmptyRows(Sheet) 而不是DeleteEmptyRows(Sheet As Excel.Worksheet)。我用DeleteEmptyRows (Workbooks.Open(path).Sheets("sheet1"))
          • 好建议。事实上,我从 Excel 类中取出了这个,所以Sheet 通常是一个类内部局部变量,Subs Header 就是Sub DeleteEmptyRows()。为了适应这里,我添加了参数,以便它作为独立函数工作。这可能与我们在 Excel 工作表对象和工作表对象中存在的事实相冲突,尽管它们描述了相同的实体,但它们在每种情况下都不相同。随意根据您的需要进行更改。
          猜你喜欢
          • 1970-01-01
          • 2020-03-22
          • 2013-10-18
          • 1970-01-01
          • 2017-02-15
          • 1970-01-01
          • 1970-01-01
          • 2018-02-21
          • 1970-01-01
          相关资源
          最近更新 更多