Home > database >  Problem with connecting Google app script to my google sheet
Problem with connecting Google app script to my google sheet

Time:12-05

I have been trying to get the time stamp in my google sheet every time I make an entry in the first column it should give me the date and time stamp in the fourth column. However, I don't know what I'm doing wrong all the tutorials are a year old and Google has removed the edit script feature from google Sheets' "tools" menu so I don't know how to connect the function to it properly.

Here's the code :

function onEdit(e) {
  var row = e.range.getRow();
  var col = e.range.getColoumn();

  if(col===1 && row>1 && e.source.getActiveSheet.getName()=== "Dummy1")  {
    e.source.getActiveSheet.getRange(row,4).setValue(new Date());
  }
}

And this is the error it gives me:

TypeError: Cannot read property 'range' of undefined onEdit @ TimeStamp.gs:3

And a link of the sheet: https://docs.google.com/spreadsheets/d/1lBe7GDT7-yAS3GiBhoiVppIZe7gDkI3ihExmo5ZaEy8/edit?usp=sharing

CodePudding user response:

You have a typo. It is getColumn() not getColoumn().

Also getActiveSheet is a function, so it needs parenthesis getActiveSheet().

function onEdit(e) {
  var row = e.range.getRow();
  var col = e.range.getColumn();

  if(col===1 && row>1 && e.source.getActiveSheet().getName()=== "Dummy1")  {
    e.source.getActiveSheet().getRange(row,4).setValue(new Date());
  }
}

CodePudding user response:

This solution takes advantage of the event object much better and will run much faster.

function onEdit(e) {
  //e.source.toast('Entry');//these lines can be an aid to debugging 
  //Logger.log(JSON.stringify(e));//uncomment this to learn more about event object
  const sh = e.range.getSheet();
  if (e.range.columnStart == 1 && e.range.rowStart > 1 && sh.getName() == "Dummy1") {
    e.range.offset(0, 3).setValue(new Date());
  }
}

You cannot run functions like this from the script editor because they require the event object from the onedit trigger which is generated when you edit a cell on the spreadsheet. So to test them you simply need to create them and save them as function onEdit(e) and then edit the page to see it work or not. You can utilize e.source.toast('flags') in different locations to help you to determine where problems exist in the function.

  • Related