【问题标题】:Delete blank row using For Next使用 For Next 删除空白行
【发布时间】:2015-03-17 01:12:29
【问题描述】:

我的代码有关于删除空白行的问题。它只需要删除一些行,而不是所有空白行和行值“0”。我不想在 SO 论坛上使用 .SpecialCells(xlCellTypeBlanks) 作为威胁。

Dim R As Integer
R = Range("CuoiNKC").Row - 1
Dim DelCell As Range
Dim DelRange As Range
Set DelRange = Range("J9:J" & R)
For Each DelCell In DelRange
    If DelCell.Value = "0" Or DelCell.Formula = Space(0) Then
        DelCell.EntireRow.Delete
    End If
Next DelCel

【问题讨论】:

标签: vba excel


【解决方案1】:

为什么不使用Range AutoFilter Method 而不是循环。
假设您的代码中有正确的 DelRange 值,请尝试以下操作:

DelRange.AutoFilter 1, AutoFilter 1, "=0", xlOr, "=" 'filtering 0 and space
DelRange.SpecialCells(xlCellTypeVisible).EntireRow.Delete xlUp 'delete visible cells
ActiveSheet.AutoFilterMode = False 'remove auto filter mode

顺便说一句,如果您想坚持自己的逻辑,则需要向后迭代行。
您只能使用传统的For Next Loop 来做到这一点。再次假设 R 的值是正确的。

For i = R To 9 Step -1
    If Range("J" & i).Value = "0" Or Range("J" & i).Value = " " Then
        Range("J" & i).EntireRow.Delete xlUp
    End If
Next

【讨论】:

  • 这种方式录制宏的时候,我也知道。但是在我的代码中,我不知道为什么它只是删除了一些行并再次执行它会继续删除更多但不是全部。用我的代码我想解决更多问题@L42
  • 谢谢L42,如果我想知道删除了多少行,怎么办? (我用了多少)
  • @kobebryant 只需在循环中添加另一个计数器变量。
  • 如何添加。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-20
  • 1970-01-01
  • 2011-05-30
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多