将每个第3个单元格2个单元格中的值向右移动

时间:2018-06-04 14:40:49

标签: excel vba excel-vba

从C7开始,我想将C7中两个单元格中的值向右移动,C7 - > E7和F7 - > H7等我必须这样做直到列的结尾

我的代码:

Sub MoveCells2ToTheRight(specifiedWorksheet)

Dim lastCol As Long
With specifiedWorksheet
    lastCol = .Cells(7, .Columns.Count).End(xlToLeft).Column
    ' from column 3 to end of used columns in worksheet
    For i = 3 To lastCol
        If Not IsEmpty(.Cells(7, i)) Then
            .Cells(7, i).Cut
            Sheets(specifiedWorksheet).Range(.Cells(7, i + 2)).Select
            ActiveSheet.Paste
            i = i - 1
            lastCol = lastCol - 1
        Else
            Exit For
        End If
    Next i
End With

End Sub

1 个答案:

答案 0 :(得分:2)

如果没有剪切和粘贴,您可以只插入向右移动的空白单元格,如:Range("C7").Resize(ColumnSize:=2).Insert Shift:=xlToRight,如果之间没有数据。

Sub MoveCells2ToTheRight(specifiedWorksheet As Worksheet)

    Dim lastCol As Long
    With specifiedWorksheet
        lastCol = .Cells(7, .Columns.Count).End(xlToLeft).Column
        ' from column 3 to end of used columns in worksheet
        For i = 3 To lastCol
            If Not IsEmpty(.Cells(7, i)) Then
                .Cells(7, i).Resize(ColumnSize:=2).Insert Shift:=xlToRight
                i = i - 1
                lastCol = lastCol - 1
            Else
                Exit For
            End If
        Next i
    End With

End Sub

注意我建议指定pecifiedWorksheet As Worksheet