首页 文章

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

提问于
浏览
1

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

enter image description here

对此:

enter image description here

我尝试了以下宏:

Sub move()

Selection.Offset(-1, 1).Value = Selection.Value
Selection.ClearContents

End Sub

但结果是:

enter image description here

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

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

4 回答

  • 3

    你可以试试这样的......

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

    我个人不喜欢使用 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
    
  • 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
    
  • 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
    

相关问题