var SHEET_NAME = ["1", "2", "3", "연습시트", "복사용"];
function onEdit() {
var s = SpreadsheetApp.getActiveSheet();
if( s.getName() == "1" ) { //checks that we're on the correct sheet
var r = s.getActiveCell();
if( r.getColumn() == 1 ) { //checks the column
var nextCell = r.offset(0, 19);
if( nextCell.getValue() === '' ) //is empty?
nextCell.setNumberFormat("MM/dd HH:mm:ss")
nextCell.setValue(new Date());
}
}
if( s.getName() == "2" ) { //checks that we're on the correct sheet
var r = s.getActiveCell();
if( r.getColumn() == 1 ) { //checks the column
var nextCell = r.offset(0, 19);
if( nextCell.getValue() === '' ) //is empty?
nextCell.setNumberFormat("MM/dd HH:mm:ss")
nextCell.setValue(new Date());
}
}
if( s.getName() == "3" ) { //checks that we're on the correct sheet
var r = s.getActiveCell();
if( r.getColumn() == 1 ) { //checks the column
var nextCell = r.offset(0, 19);
if( nextCell.getValue() === '' ) //is empty?
nextCell.setNumberFormat("MM/dd HH:mm:ss")
nextCell.setValue(new Date());
}
}
if( s.getName() == "연습시트" ) { //checks that we're on the correct sheet
var r = s.getActiveCell();
if( r.getColumn() == 1 ) { //checks the column
var nextCell = r.offset(0, 19);
if( nextCell.getValue() === '' ) //is empty?
nextCell.setNumberFormat("MM/dd HH:mm:ss")
nextCell.setValue(new Date());
}
}
if( s.getName() == "복사용" ) { //checks that we're on the correct sheet
var r = s.getActiveCell();
if( r.getColumn() == 1 ) { //checks the column
var nextCell = r.offset(0, 19);
if( nextCell.getValue() === '' ) //is empty?
nextCell.setNumberFormat("MM/dd HH:mm:ss")
nextCell.setValue(new Date());
}
}
}
with this script, to add more sheet, I need to add new sheet name and one bunch of code on the script.
So I wanna change them like, If sheet had Specific text of alphabet in his name, they automatically applied by this script.
CodePudding user response:
There's no need to repeat the same block of code over and over again. Just check if the edited sheet is in the array of 'sheetNames'. See if this helps
function onEdit(e) {
const sheetNames = ["1", "2", "3", "연습시트", "복사용"];
const sheet = e.source.getActiveSheet();
if (sheetNames.includes(sheet.getName()) && e.range.columnStart === 1) {
const offset = e.range.offset(0, 19)
if (!offset.getValue()) {
offset.setValue(new Date()).setNumberFormat("MM/dd HH:mm:ss")
}
}
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>