按行删除空单元格,根据需要移动组中的单元格值

时间:2015-04-13 09:32:37

标签: excel excel-vba vba

我想删除单元格中的空元素,逐行将单元格值从右向左移动到A到E的一组列中,如下所示

A   B   C   D   E            
                3
    3       2   
6       2   2   
    1   6       
2   3           
    6   6   6   
1       1       

我想要的是

A   B  C   D   E
3   3  2   6   2
2   1  6   2   3
6   6  6   1   1

结果数据(解决方案)应该从A1开始,如上所述,

1 个答案:

答案 0 :(得分:1)

选择你想要的区域" compact"并运行:

Sub CompactData()
    Dim r As Range
    Set r = Selection.Cells.SpecialCells(xlCellTypeBlanks)
    r.Delete Shift:=xlToLeft
End Sub

所以如果我们从这开始:

enter image description here

我们将导致:

enter image description here

修改#1:

根据您的评论,您可能需要蛇纹石压缩。如果是这样的话,那么:

Sub SerpentineMotion()
    Dim r As Range, rng As Range, c As Collection
    Dim K As Long
    Set c = New Collection
    Set rng = Intersect(Range("A:E"), ActiveSheet.UsedRange)
    For Each r In rng
        If r.Value <> "" Then
            c.Add r.Value
        End If
    Next r

    rng.Clear
    K = 1

    For Each r In rng
        r.Value = c.Item(K)
        K = K + 1
        If K > c.Count Then Exit Sub
    Next r

End Sub

将转换:

enter image description here

分为:

enter image description here