Search code examples
vbarowcellinsertion

Insert worksheet row based on given relative range row index vba


What I'm trying to do is insert a row in a particular spot in an Excel range using VBA. I scan the range to find out what row the string "Administration" first appears on and then would like to insert a row directly above. The code below works. But it only inserts a row to my Range, not to the entire work sheet, which messes up the position of some other tables further down on the same worksheet. It would be good to figure out a way to select the entire row, so that everything further down on the worksheet gets relocated too, not just the stuff in the range. Any thoughts? Thanks.

Sub insertRow(Name As String)
    Dim Rw, target As Range
    Dim insertRowNum As Integer

    Set target = ActiveSheet.Range("Table")

    'Determine proper insertion row index.  Goal is to insesrt new project right
    'before Administration'

    insertRowNum = -1 'Flag to see if loop finds "Administration" in any of the cells"
    For Each Rw In target.Rows
        If target.Cells(Rw.Row, 1) = "Administration" Then
            insertRowNum = Rw.Row
            Exit For
        End If
    Next

    'Check to see if "Administration" was found'
    If insertRowNum = -1 Then
        insertRowNum = target.Rows.Count
    End If

    'Insert Blank Row
    target.Rows(insertRowNum).Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove

Solution

  • instead of

    target.Rows(insertRowNum).Select
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    

    try

    Range("A" & insertRowNum).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove