简体   繁体   English

使用Excel VBA删除SpecialType空白单元格

[英]Removing SpecialType Blank Cells using Excel VBA

This script "works", but only if I run it twice. 该脚本“有效”,但前提是我运行两次。 Anyone have an idea of why this is happening? 任何人都知道为什么会这样吗? Dealing with the special types has been somewhat of a nightmare, I'm not sure if that's just me or known issues. 处理特殊类型一直是一场噩梦,我不确定这是我还是已知问题。 Using Excel 2010 on Windows 7. I've tried repeating the code twice as well to no avail. 在Windows 7上使用Excel2010。我尝试重复两次代码,但无济于事。 I tried putting this in a Do Until and ALWAYS get stuck in a forever loop the first time I execute. 我尝试将其放在“直到”中,并且总是在我第一次执行时陷入永久循环。 I'm not sure why executing it the second time seems to work 我不确定为什么第二次执行似乎有效

'Remove all Blank Cells

    On Error Resume Next
    For i = Cells.SpecialCells(xlCellTypeBlanks).Count To 1 Step -1
    Cells.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
    Next i

  If Cells.SpecialCells(xlCellTypeBlanks).Count = 0 Then 
     ActiveWorkbook.Close (True)

EDIT : Updated answer to show how deleting a "specialcells" range doesn't reset the sheet's UsedRange property, and how that can lead to problems. 编辑 :更新的答案显示了如何删除“ specialcells”范围不会重置工作表的UsedRange属性,以及这如何导致问题。

Try running this sub multiple times on a sheet with or without the call to Activesheet.UsedRange commented out... 尝试在带有或不带有Activesheet.UsedRange调用的工作表上多次运行此子项Activesheet.UsedRange注释掉...

Sub Tester()
    Dim rng As Range

    On Error Resume Next
    Set rng = ActiveSheet.Cells.SpecialCells(xlCellTypeBlanks)
    On Error GoTo 0

    If Not rng Is Nothing Then
        Debug.Print "have empty cells"
        rng.EntireRow.Delete
        ActiveSheet.UsedRange
    Else
        Debug.Print "no empty cells"
    End If

End Sub

Saving and re-opening seems to also reset UsedRange... 保存并重新打开似乎还会重置UsedRange ...

EDIT2 you should be very careful using this! EDIT2,您应该非常小心地使用它! It deletes whole rows even if there are non-blank cells in that row . 即使该行中有非空白单元格,它也会删除整行。 It will be OK for certain types of data layout, but not for others. 某些类型的数据布局可以,但其他类型则不能。 Under certain circumstances you may also see an error "Cannot use that command on overlapping selection" when calling "delete". 在某些情况下,调用“删除”时,您可能还会看到错误“无法在重叠选择上使用该命令”。

I'll caveat this by saying that @TimWilliams's answer is more elegant, but you can try this: 我将通过@TimWilliams的答案更为优雅的方式对此加以说明,但是您可以尝试以下操作:

Sub Deletes()

Dim rng As Range
Set rng = ActiveSheet.UsedRange

' Check each cell in the range and if its value is empty, delete the row
For Each Cell In rng
  If Cell.Value = "" Then
    Cell.EntireRow.Delete
  End If
Next Cell

' Close
ActiveWorkbook.Close

End Sub

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

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