Home » excel » excel – Move value in every 3rd cell 2 cells to the right

excel – Move value in every 3rd cell 2 cells to the right

Posted by: admin April 23, 2020 Leave a comment

Questions:

Starting from C7, I’d like to move the value in C7 two cells to the right, C7 -> E7 and F7 -> H7, etc. I have to do this until the end of the columns

My code:

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
How to&Answers:

Instead of cut and paste you can just insert blank cells with shift to right like: Range("C7").Resize(ColumnSize:=2).Insert Shift:=xlToRight if there is no data in between.

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

Note I recommend to specify pecifiedWorksheet As Worksheet.