如何使用vba删除excel中的空单元格

时间:2017-10-31 08:41:23

标签: excel vba excel-vba

This is just a sample I am testing the code in this data. 我在sheet2中有三列。我必须删除空单元格。这是更新的代码,仅适用于B列。您可以查看快照

   Sub delete()
   Dim counter As Integer, i As Integer
    counter = 0

  For i = 1 To 10
    If Cells(i, 1).Value <> "" Then
        Cells(counter + 1, 2).Value = Cells(i, 1).Value
        counter = counter + 1

    End If
Next i
End Sub

示例截图
enter image description here

2 个答案:

答案 0 :(得分:2)

如果您只想删除空单元格,请尝试一下......

Sub DeleteBlankCells()
Dim rng As Range
On Error Resume Next
Set rng = Intersect(ActiveSheet.UsedRange, Range("A:C"))
rng.SpecialCells(xlCellTypeBlanks).Delete shift:=xlUp
End Sub

答案 1 :(得分:1)

不是最优雅的解决方案,但它确实有效。

Option Explicit
Sub delete()
Dim rCells As Range, rCell As Range, sFixCell As String

Set rCells = Range("A1:A13")
For Each rCell In rCells
    If rCell = "" Then
        sFixCell = rCell.Address
        Do While rCell.Value = ""
        rCell.delete Shift:=xlUp
        Set rCell = Range(sFixCell)
        Loop
    End If
Next rCell

End Sub