To insert a new row or column in a Google Sheet using Apps Script, you can use the insertRowAfter()
, insertRowBefore()
, insertColumnAfter()
, or insertColumnBefore()
methods of the Sheet
class. Here’s an example code snippet:
function insertRow() { var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); var sheet = spreadsheet.getActiveSheet(); var rowNumber = 2; // Replace with the desired row number to insert sheet.insertRowAfter(rowNumber); } function insertColumn() { var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(); var sheet = spreadsheet.getActiveSheet(); var columnLetter = 'B'; // Replace with the desired column letter to insert sheet.insertColumnAfter(sheet.getRange(columnLetter + '1').getColumn()); }
In this code, there are two functions: insertRow()
and insertColumn()
. You can choose the appropriate function based on whether you want to insert a row or a column.
To insert a new row, you need to specify the desired row number to insert after using the rowNumber
variable. In this example, the row number is set to 2
, indicating that the new row will be inserted after the second row. You can modify the rowNumber
variable to your desired row number.
The insertRowAfter()
method is called on the sheet
object, passing the rowNumber
as an argument. This method inserts a new row after the specified row number.
To insert a new column, you need to specify the desired column letter to insert after using the columnLetter
variable. In this example, the column letter is set to 'B'
, indicating that the new column will be inserted after column B. You can modify the columnLetter
variable to your desired column letter.
The insertColumnAfter()
method is called on the sheet
object, passing the column number retrieved from the range 'B1'
using getRange().getColumn()
as an argument. This method inserts a new column after the specified column.
You can call the insertRow()
or insertColumn()
function from another function or set up triggers to execute them based on your needs. When executed, they will insert a new row or column at the specified location in the Google Sheet.
Feel free to modify the code to suit your specific requirements, such as inserting rows or columns before a specific location, inserting multiple rows or columns, or performing additional operations after the insertion.