excel vba insert a range and shift cells down code example

Example: excel vba shift range

' Returns a shifted version of initial range (same size)
Function ShiftRange(ByVal pRange As Range, ByVal pRowOffset, ByVal pColumnOffset)
    Set ShiftRange = pRange.Offset(pRowOffset, pColumnOffset)
End Function

'--------------------------------------------------------------------------------
Sub TestIt()
    Dim rInitialRange, rShiftedRange As Range
    Dim iRowOffset, iColOffset As Long
    
    iRowOffset = 2      ' Shifts 2 rows down
    iColOffset = -1     ' Shifts 1 column left
    Set rInitialRange = Range("D1:B3")
    
    ' Sets a shifted version of initial range (2 rows below, 1 column left)
    Set rShiftedRange = ShiftRange(rInitialRange, iRowOffset, iColOffset)
    
    MsgBox "Initial range: " & rInitialRange.Address(False, False) & vbCrLf _
        & vbCrLf & "Row offset : " & iRowOffset _
        & vbCrLf & "Column offset : " & iColOffset & vbCrLf _
        & vbCrLf & "New range : " & rShiftedRange.Address(False, False)
End Sub

Tags:

Vb Example