Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.


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

1 Answer

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();
         });
   });   
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...