在Excel中移动不连续的单元格内容

时间:2017-07-01 02:44:13

标签: excel vba excel-vba

在我当前的Excel工作表中,我想将选定的非连续单元格内容向右移动,从而向上移动:

enter image description here

到此:

enter image description here

我尝试了以下宏:

object(stdClass)#17 (4) { ["took"]=> int(4) ["timed_out"]=> bool(false) ["_shards"]=> object(stdClass)#18 (3) { ["total"]=> int(5) ["successful"]=> int(5) ["failed"]=> int(0) } ["hits"]=> object(stdClass)#19 (3) { ["total"]=> int(1) ["max_score"]=> float(1.6931472) ["hits"]=> array(1) { [0]=> object(stdClass)#20 (5) { ["_index"]=> string(11) "tryelastic2" ["_type"]=> string(11) "tryelastic2" ["_id"]=> string(20) "AVz4fiU3Gx0i_9jPP49l" ["_score"]=> float(1.6931472) ["_source"]=> object(stdClass)#21 (6) { ["id"]=> int(2) ["nama"]=> string(7) "Jhordan" ["url"]=> string(11) "jhordan.com" ["pesan"]=> string(5) "aiueo" ["code"]=> string(3) "247" ["status"]=> int(2) } } } } } 

但结果却是这样:

enter image description here

有没有办法在移动后保留A5和A8的内容?谢谢!

编辑:最后,移动选定的单元格内容后,是否可以删除原始行(在我的示例中为A2,A5和A8)?

4 个答案:

答案 0 :(得分:3)

我个人不喜欢使用Selection,但如果你坚持,以下内容可能会有所帮助。

Sub test()

    Dim rngTemp As Range
    For Each rngTemp In Selection.Areas
        rngTemp.Copy Destination:=rngTemp.Offset(-1, 1)
        rngTemp.ClearContents
    Next rngTemp

End Sub

答案 1 :(得分:3)

另一种方式

Sub Sample()
    Dim aCell As Range

    '~~> Check if what the user selected is a valid range
    If TypeName(Selection) <> "Range" Then
        MsgBox "Select a range first."
        Exit Sub
    End If

    For Each aCell In Selection
        aCell.Cut Destination:=aCell.Offset(-1, 1)
    Next aCell
End Sub

答案 2 :(得分:2)

你可以尝试这样的事情......

Sub TransformData()
    Dim cell As Range
    For Each cell In Selection
        cell.Offset(-1, 1) = cell
    Next cell
    Selection.ClearContents
End Sub

答案 3 :(得分:0)

没有选择复制数据。

Sub test()
    Dim rngDB As Range, rng As Range
    Dim i As Long, n As Long
    Set rngDB = Range("a1", Range("a" & Rows.Count).End(xlUp))
    n = rngDB.SpecialCells(xlCellTypeConstants).Areas.Count
    For i = 1 To n
        Set rng = rngDB.SpecialCells(xlCellTypeConstants).Areas(i)
        rng(rng.Rows.Count).Copy rng.Range("a1").Offset(, 1)
        rng(rng.Rows.Count).Clear
    Next i
End Sub