简体   繁体   English

使用VBA删除空行-MS Excel

[英]Delete empty rows using VBA - MS Excel

I am looking to see if there is a more efficient way to achieve the result below, so it can be extended if needed. 我正在寻找是否有一种更有效的方法来实现以下结果,因此可以根据需要进行扩展。

I'm using this to clean up large spreadsheets that have the rows CZ blank. 我正在使用它来清理CZ行为空的大型电子表格。 I imagine there should be a way to clean it up so that it doesn't have to double in size if I need to clean up a spreadsheet with data from C to AZ. 我想应该有一种清理它的方法,这样,如果我需要清理包含C到AZ数据的电子表格,它的大小就不必加倍。

It's been a while since I used VBA, I found the code below online. 自从我使用VBA已经有一段时间了,我在网上找到了下面的代码。 (counting ROW B as the spreadsheet in question had an empty ROW A) (将ROW B视为有问题的电子表格,其中ROW A为空)

Sub delem()
Dim lr As Long, r As Long
lr = Cells(Rows.Count, "B").End(xlUp).Row
For r = lr To 1 Step -1
    If Range("C" & r).Value = "" And Range("D" & r).Value = "" And Range("E" & r).Value = "" And Range("F" & r).Value = "" And Range("G" & r).Value = "" And Range("H" & r).Value = "" And Range("I" & r).Value = "" And Range("J" & r).Value = "" And Range("K" & r).Value = "" And Range("L" & r).Value = "" And Range("M" & r).Value = "" And Range("N" & r).Value = "" And Range("O" & r).Value = "" And Range("P" & r).Value = "" And Range("Q" & r).Value = "" And Range("R" & r).Value = "" And Range("S" & r).Value = "" And Range("T" & r).Value = "" And Range("U" & r).Value = "" And Range("V" & r).Value = "" And Range("W" & r).Value = "" And Range("X" & r).Value = "" And Range("Y" & r).Value = "" And Range("Z" & r).Value = "" Then Rows(r).Delete
Next r
End Sub

Thanks! 谢谢!

Just add an inner loop to go through the columns you care about. 只需添加一个内部循环即可遍历您关心的列。 This will actually run much faster, as VBA doesn't short-circuit the If statement (all of the conditionals are evaluated). 实际上,这将运行得更快,因为VBA不会使If语句短路(所有条件语句都会被求值)。 But with the loop, you can exit early if you find a value anywhere: 但是通过循环,如果您在任何地方找到值,就可以提早退出:

Sub delem()
    Dim last As Long
    Dim current As Long
    Dim col As Long
    Dim retain As Boolean

    last = Cells(Rows.Count, "B").End(xlUp).Row
    For current = last To 1 Step -1
        retain = False
        For col = 3 To 26
            If Cells(current, col).Value <> vbNullString Then
                retain = True
                Exit For
            End If
        Next col
        If Not retain Then Rows(current).Delete
    Next current
End Sub

The Excel worksheet function COUNTA is a clean way to test if a range is empty. Excel工作表函数COUNTA是测试范围是否为空的一种干净方法。

Sub delem()
  Dim lr As Long, r As Long
  lr = Cells(Rows.Count, "B").End(xlUp).Row
  For r = lr To 1 Step -1

    'This function Counts the number of cells that are not empty
    If WorksheetFunction.CountA(Range(Cells(r, 3), Cells(r, 26)) = 0 Then 
      Rows(r).Delete 
    End If

  Next r
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM