简体   繁体   English

删除范围内的空白单元格

[英]Delete blank cells in range

I want to delete blank cells in a range (E1:E130).我想删除一个范围内的空白单元格 (E1:E130)。

This code skips cells.此代码跳过单元格。

For Each cell In ranger
    If cell.Value = "" Then
        cell.Delete
    End If
next cell

To make my objective more clear: I have a list of cells with text and empty cells in the range E1:E130 and I want to make a list starting on E1 without any empty cells.为了使我的目标更加明确:我有一个包含文本的单元格列表和 E1:E130 范围内的空单元格,我想制作一个从 E1 开始的列表,没有任何空单元格。
Sorting on alphabet for instance would also be a good solution, however that didn't work out for me either.例如,按字母排序也是一个很好的解决方案,但这对我来说也行不通。

I'd go like follows我会像下面这样

With Range("E1:E130")
    If WorksheetFunction.CountA(.Cells) > 0 Then .SpecialCells(xlCellTypeBlanks).Delete Shift:=xlShiftUp
End With

您可以使用Range.SpecialCells 方法一次删除特定范围内的所有空白单元格:

Range("E1:E130").SpecialCells(xlCellTypeBlanks).Delete

You can try with this code to remove blank cell on define range :您可以尝试使用此代码删除定义范围上的空白单元格:

Sub RemoveBlankCells()

Dim rng As Range

'Store blank cells inside a variable
  On Error GoTo NoBlanksFound
    Set rng = Range("E1:E130").SpecialCells(xlCellTypeBlanks)
  On Error GoTo 0

'Delete blank cells and shift upward
  rng.Rows.Delete Shift:=xlShiftUp

Exit Sub

'ERROR HANLDER
NoBlanksFound:
  MsgBox "No Blank cells were found"

End Sub

Necromancing an old question here, but: OP, I'm not sure your issue (of the 'for each cell in range' not deleting all the wanted cells) stems from the following, but before I knew about Range(...).RemoveDuplicates, i wrote 'for loops' for that very task.在这里解决一个老问题,但是:OP,我不确定您的问题(“范围内的每个单元格”没有删除所有想要的单元格)源于以下问题,但在我知道 Range(...) .RemoveDuplicates,我为那个任务写了“for 循环”。

At first i ran the loop from top to bottom and removed the unwanted cells.起初我从上到下运行循环并删除不需要的单元格。 But when you remove a cell, the whole column shifts up, while your counter stays on the same value, so if there were 2 blank, the second one was shifted up when removing the first, and then the loop jumped over the blank.但是当你删除一个单元格时,整个列向上移动,而你的计数器保持在相同的值上,所以如果有 2 个空白,第二个在删除第一个时向上移动,然后循环跳过空白。

So I, then, ran the loop bottom to top (step -1), and that took care of this issue.所以我,然后,从下到上运行循环(步骤 -1),这就解决了这个问题。

This should work:这应该有效:

Columns("E:E").Select
Selection.SpecialCells(xlCellTypeBlanks).Select
Selection.Delete Shift:=xlUp

This one uses special methods and is more useful if you wanna erase all the data associated with the blank cells.此方法使用特殊方法,如果您想擦除与空白单元格关联的所有数据,则更有用。

 Range("A:B").SpecialCells(xlCellTypeBlanks).Select
            Selection.EntireRow.Delete

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

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