简体   繁体   中英

Google Sheet scripts

I created the following script to sort data on certain pages in google sheets, and it will only run the second function and not the first one. I am new to programming and switching over to sheets from excel. I am sure its something small and obvious, but i can't figure it out. I appreciate any help.

function onEdit(event){
var sheet = event.source.getActiveSheet();
if(sheet.getName() ==='ADMIN')
var editedCell = sheet.getActiveCell();

var columnToSortBy = 1;
var tableRange = "A2:G48"; // What to sort.

if(editedCell.getColumn() == columnToSortBy){   
var range = sheet.getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
}
}

function onEdit(event){
var sheet = event.source.getActiveSheet();
if(sheet.getName() ==='HQ', 'ARMT', 'MAINT', 'AVNX', 'SHOPS')
var editedCell = sheet.getActiveCell();

var columnToSortBy = 2;
var tableRange = "A4:D40"; // What to sort.

if(editedCell.getColumn() == columnToSortBy){   
var range = sheet.getRange(tableRange);
range.sort( { column : columnToSortBy, ascending: true } );
 } 
}

In javascript and google scripts, functions are objects. What you are doing here is creating an object (function onEdit) and then creating it again. It's like setting a variable named xyz to 4 and then setting the same variable to 14. The last one set is all that matters. You can accomplish what you want by merging the functions together so you have one onEdit, or naming one(or both) differently and having the onEdit call them.

 function onEdit(event) {
     first(event);
     second(event);
 }

 function first(event) {
     var sheet = event.source.getActiveSheet();
     if (sheet.getName() === 'ADMIN')
         var editedCell = sheet.getActiveCell();

     var columnToSortBy = 1;
     var tableRange = "A2:G48"; // What to sort.

     if (editedCell.getColumn() == columnToSortBy) {
         var range = sheet.getRange(tableRange);
         range.sort({
             column: columnToSortBy,
             ascending: true
         });
     }
 }

 function second(event) {
     var sheet = event.source.getActiveSheet();
     if (sheet.getName() === 'HQ', 'ARMT', 'MAINT', 'AVNX', 'SHOPS')
         var editedCell = sheet.getActiveCell();

     var columnToSortBy = 2;
     var tableRange = "A4:D40"; // What to sort.

     if (editedCell.getColumn() == columnToSortBy) {
         var range = sheet.getRange(tableRange);
         range.sort({
             column: columnToSortBy,
             ascending: true
         });
     }
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM