Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

javascript - How can i add list of sheets to Google App Script?

I have a script, which works in a tab, which is hardcoded in the line 4 (Sheet1):

function fillColumn() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet1');
  const values = sh.getRange('A2:A'+sh.getLastRow()).getValues().flat([1]);

  var toCopy;
  values.forEach((el,index)=>{
    if (el != ''){
      toCopy = sh.getRange(index+2,1).getValue();
    } else {
      sh.getRange(index+2,1).setValue(toCopy)
    }
  })
}

What is the correct way to add a list of tabs, to make script working in tabs Sheet1, Sheet2, Sheet12? I tried some notations, but they were all erroneous.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Explanation:

  • You need to loop over the sheets. There are multiple ways to do that, but since you are already familiar with the forEach loop, you can wrap your code with another forEach loop that iterates over the selected sheets.

  • You want to iteratively get and set values in multiple sheets, then it is a good idea to flush the changes at the end of each sheet iteration.

Solution:

function fillColumn() {
  const ss = SpreadsheetApp.getActive();
  ["Sheet1", "Sheet2", "Sheet12"]. // Add sheets here
  forEach(sn=>{ 
         let sh = ss.getSheetByName(sn);
         let values = sh.getRange('A2:A'+sh.getLastRow()).getValues().flat();                                                                               
         let toCopy;
         values.forEach((el,index)=>{
         if (el != ''){
                toCopy = sh.getRange(index+2,1).getValue();
         } else {
                sh.getRange(index+2,1).setValue(toCopy)
         }
         SpreadsheetApp.flush();
         });
   });   
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...