google-sheets

I would like to always have the row above open for new data


Row 1 would be my headers Row 2 Open for new data and when I hit enter, it goes down to row 3 leaving row 2 open for new data to input.

I was working with this code in Excel but can't get it to go in Sheets. Help Please!

Private Sub Worksheet_Change(ByVal Target As Excel.Range)

'Support Us on patreon.com/excel10tutorial

'Subscribe us on youtube.com/excel10tutorial

On Error GoTo enditall

Application.EnableEvents = False

If Target.Cells.Column = 5 Then

  If Target.Cells.Row = 2 Then

    N = Target.Cells.Row

    If Range("E" & N).Value <> "" Then

     Range("E2").EntireRow.Insert

     Range("A2").Select

    End If

  End If

End If

enditall:

Application.EnableEvents = True

End Sub


Solution

  • Use an onEdit() simple trigger and the event object, like this:

    /**
    * Simple trigger that runs each time the user hand edits the spreadsheet.
    *
    * @param {Object} e The onEdit() event object.
    */
    function onEdit(e) {
      if (!e) throw new Error('Please do not run the onEdit(e) function in the script editor window. It runs automatically when you hand edit the spreadsheet. See https://stackoverflow.com/a/63851123/13045193.');
      if (e.range.rowStart !== 2 || e.range.columnStart !== 5) return;
      e.range.getSheet().getRange('A2:E2').insertCells(SpreadsheetApp.Dimension.ROWS).activate();
    }
    

    See simple trigger and event object.