I don't understand why I am getting this error

Viewed 90

I am completely unfamiliar with JavaScript but I am trying to create a script that makes a formatted timestamp in a specific cell when a button is pressed.

I have gotten it to work with a true/false in sheets however I don't know how to make this in JavaScript. This is as far as I have gotten so far and I'm already hitting errors I do not understand.

Can someone help me understand or link me resources on how to figure out some of these problems? I've spent several hours googling and reading Google developer pages trying to learn but I haven't had any luck thus far.

The error:

enter image description here

function myFunction() {
  var sheet = SpreadsheetApp.getActiveSheet()
  var date = new Date(); var timeStamp = date.getTime(); // Unix Timestamp
  var currentTime = date.toLocaleTimeString(); // eg. 10:23:30 AM HKT 
  sheet.setValue(currentTime);
}
2 Answers

While the accepted answer gives you a completely valid solution, I thought I would walk you through my own process for figuring this out pretty quickly using the documentation (without necessarily having any previous experience with google apps scripts).

The SpreadsheetApp.getActiveSheet() method returns the active Sheet object.

We can browse the docs for the Sheet class to see which methods are available and which might be useful to us.

getActiveRange() looks interesting. It:

Returns the selected range in the active sheet, or null if there is no active range.

So again, searching through the docs for the Range class to see what methods are available to the range class, we can find setValue.

function myFunction() {
  var date = new Date();
  var timeStamp = date.getTime();
  var currentTime = date.toLocaleTimeString(); 

  var sheet = SpreadsheetApp.getActiveSheet();
  var activeRange = sheet.getActiveRange();
  if (activeRange) {
      activeRange.setValue(currentTime);
  }
}

Hopefully this answer teaches you a bit more of a step-by-step approach in figuring these kind of problems out in the future.

You need to set the value on a cell, not the entire sheet. To do it on the cell at the very top left, you would select A1 for example:

function myFunction() {
  var date = new Date();
  var timeStamp = date.getTime(); // Unix Timestamp
  var currentTime = date.toLocaleTimeString(); // eg. 10:23:30 AM HKT 

  var sheet = SpreadsheetApp.getActiveSheet(); // Sheet
  var cell = sheet.getRange('A1'); // Cell           <------------------------
  cell.setValue(currentTime); // <--------------------------------------------
}
Related