I am writing this to understand how to run a script on multiple tabs (worksheets) in one google spreadsheet file.
Problem that I am having:
step1: write down code for tab Apple and save, script will work on Apple.
step2: write down code for tab Banana (in the same script file, right after code for Apple) and save, script will work on Banana, but not working on Apple anymore.
What I have tried so far (not working):
function onEdit(e) {
addTimestamp(e);
}
function addTimestamp(e){
var startRow = 2;
var targetColumn = 24;
var ws = "Apple";
var row = e.range.getRow();
var col = e.range.getColumn();
if(col === targetColumn && row >= startRow && e.source.getActiveSheet().getName() === ws){
var time = Utilities.formatDate(new Date(), 'Asia/Tokyo', 'yyyy/MM/dd');
e.source.getActiveSheet().getRange(row,25).setValue(time);
}
}
function addTimestamp(e){
var startRow = 2;
var targetColumn = 66;
var ws = "Banana";
var row = e.range.getRow();
var col = e.range.getColumn();
if(col === targetColumn && row >= startRow && e.source.getActiveSheet().getName() === ws){
var time = Utilities.formatDate(new Date(), 'Asia/Tokyo', 'yyyy/MM/dd');
e.source.getActiveSheet().getRange(row,67).setValue(time);
}
}
status
is the header value of the status
column, you could programmatically find the column index for this header using getRange(a1Notation) and findIndex; there's no need to specify that explicitly for all your sheets (which can be feasible when there are only two sheets, but can become annoying with 6 sheets).Considering the previous points, your code could be greatly simplified:
function addTimestamp(e) {
const range = e.range;
const sheet = range.getSheet();
const statusColumn = sheet.getRange("1:1").getValues()[0]
.findIndex(header => header === "status") + 1;
if (range.getColumn() === statusColumn && range.getRow() > 1) {
const time = Utilities.formatDate(new Date(), 'Asia/Tokyo', 'yyyy/MM/dd');
range.offset(0,1).setValue(time);
}
}
If you want to find the timestamp
column by header name too, just replace this:
range.offset(0,1).setValue(time);
With this:
const timestampColumn = sheet.getRange("1:1").getValues()[0]
.findIndex(header => header === "timestamp") + 1;
sheet.getRange(range.getRow(), timestampColumn).setValue(time);