Search code examples
excelvba

Insert Row to the top of data rather than 1st empty row from bottom


So, I have a vba code that looks on 1 workbook for a row marked with "x" and where it is it opens another workbook and pastes the row into the first empty row from the bottom up.

What I need it to do now is paste this to the top of the row (e.g. above the first line of data not including the headers), or if easier it will always be above row 6.

Sub addtoconfirmdatabase()
    
    Const WB_PATH As String = "S:\Goods Ordering\Confirmed Orders.xlsx"
    Dim srcSht As Worksheet, wb As Workbook, shtDest As Worksheet, i As Long
    
    Set srcSht = ActiveSheet
    
    For i = 2 To srcSht.Range("A" & srcSht.Rows.Count).End(xlUp).Row
        If srcSht.Cells(i, 1) = "x" Then
            
            If shtDest Is Nothing Then
                Set wb = Workbooks.Open(Filename:=WB_PATH)
                Set shtDest = wb.Sheets("Orders Confirmed")
            End If
            srcSht.Cells(i, 2).Resize(1, 86).Copy _
        shtDest.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
        End If
        If srcSht.Cells(i, 1) = "x" Then
            srcSht.Cells(i, 7).Interior.ColorIndex = 46
        End If
        
    Next i
    
    
    If Not wb Is Nothing Then wb.Close True
    
    Sheets("Quote Database").Select
    Range("P1:R1").ClearContents
    
    MsgBox "your orders have been added to the orders confirmed database."
    
End Sub

Solution

  • Try this mod. This only change the insertion target so as that add a new line to the defined row in ToInsert variable.

    Sub addtoconfirmdatabase()
    
    Const WB_PATH As String = "S:\Goods Ordering\Confirmed Orders.xlsx"
    Dim srcSht As Worksheet, wb As Workbook, shtDest As Worksheet, i As Long
    
    Set srcSht = ActiveSheet
    ToInsert = 6                 'added
    For i = 2 To srcSht.Range("A" & srcSht.Rows.Count).End(xlUp).Row
        If srcSht.Cells(i, 1) = "x" Then
    
            If shtDest Is Nothing Then
                Set wb = Workbooks.Open(Filename:=WB_PATH)
                Set shtDest = wb.Sheets("Orders Confirmed")
            End If
            shtDest.Rows(ToInsert).Insert              'added
            srcSht.Cells(i, 2).Resize(1, 86).Copy _
                     shtDest.Cells(ToInsert, 1)        'edited  
        End If
        If srcSht.Cells(i, 1) = "x" Then
         srcSht.Cells(i, 7).Interior.ColorIndex = 46
        End If
         
    Next i
    
    
    If Not wb Is Nothing Then wb.Close True
    
    Sheets("Quote Database").Select
    Range("P1:R1").ClearContents
    
    MsgBox "your orders have been added to the orders confirmed database."
    End Sub