So I’m trying to create a script that can apply to several tabs in my spreadsheet file and will automatically update the timestamp in each individual tab when something in that tab is updated/changed. The cell that I want the timestamp in is different in each tab. I thought I had it working but after not touching the file for two days and returning to it, I found that it’s no longer updating. Can anyone take a look and see where the issue is? Also, any idea why it would have been working for two days and then stopped working without any edits to the script? I’m new to java so appreciate any help. Here’s the current script I’m using:
function onEdit(e) {
var ss = SpreadsheetApp.getActiveSheet();
if(ss.getName()=='Sheet 1') {e.source.getSheetByName("Sheet 1")
ss.getRange("F3").setValue(new Date())}
if(ss.getName()=='Sheet 2') {e.source.getSheetByName("Sheet 2")
ss.getRange("L3").setValue(new Date())}
if(ss.getName()=='Sheet 3') {e.source.getSheetByName("Sheet 3")
ss.getRange("K4").setValue(new Date())}
if(ss.getName()=='Sheet 4') {e.source.getSheetByName("Sheet 4")
ss.getRange("K4").setValue(new Date())}
}
Is there a different way I should be approaching the script for this?
2
Answers
Your script has a couple of inefficiencies and unnecessary lines of code, but let’s first address the main issues:
Variable Scope: You are using
ss
as the active sheet but also trying to get the sheet by name viae.source.getSheetByName(...)
, which is redundant.Event Object: You’re not using the event object
e
effectively, which provides you with all the details related to the edit event.Here is a different (and hopefully more optimized version) of the script:
I suspect you are looking for
Sheet 1
etc. with a space in it, when the default Sheets naming convention isSheet1
without a space.Try:
Additionally, there are some code-style improvements you can make:
e.source.getSheetByName("Sheet X")
is not being used, you can remove that entirely.date
to a variable, e.g.const date = new Date()
switch/case
to improve readabilityvar
unless you absolutely have to; uselet
for mutable variables, or in this case,const
because they do not mutate.