Lawrence
Lawrence

Reputation: 727

How to add column above cell onedit sheets

I'm currently using google sheets script editor to add a date to cell A2 when the value of B2 is edited.

How can I add a new column above if the auto input of A2 is the 1st da of the month?

Please see Screenshot.

y

The following is what I have now.

function onEdit(e){
  var active = e.range;
  //ADD DATE
  if(active.getA1Notation().substring(0,1) == 'B' && SpreadsheetApp.getActiveSheet().getName() !== 'Inventory'){
    if(active.isBlank()){
      active.offset(0, -1).setValue("");
    }else{
      active.offset(0, -1).setValue(Date());
    }
  }

Any guidance on where I can proceed on from here will be good. Got no clues at all if this is even possible.

Upvotes: 2

Views: 67

Answers (1)

Дмитро Булах
Дмитро Булах

Reputation: 3847

Adding a row above edited cell if it's a 1 date of the month would lead to adding a row above every row added on the 1st day of the month, which is not the desired behaviour. You'll need to check the value in the previous row to determine if the row should be added. Use sheet.insertRowsBefore to add rows. Here's sample code:

function onEdit(e) {
  var value = e.range.getValue()
  if (value == 'add') {
    var rowNum = e.range.getRow()
    SpreadsheetApp.getActiveSheet().insertRowsBefore(rowNum, 1)
    SpreadsheetApp.getActiveSheet().getRange(rowNum,1).setValue('added row')
  }
}

before edit

after edit

Upvotes: 1

Related Questions