Google Script to loop folder contents and copy Google Sheets content

I helped one of our athletic directors do some budget sheets for different teams.

We then needed to add an additional sheet to all the workbooks and copy over content from a similar page. Given it’s about 20 or so workbooks, I scripted it.

 

//this function does the looping
function addAllRecruitingPages(){
  const parentFolder = DriveApp.getFolderById("LONG_STRING_ID_YOU_SHOULD_WRITE_IN_THESE_QUOTES");//get this folder by ID
  const files = parentFolder.getFiles()
  
   while (files.hasNext()) { //for each file in this folder
      const childFile = files.next();
       let contentType = childFile.getMimeType(); //get the type of file
      if(contentType == "application/vnd.google-apps.spreadsheet"){ // if it's a spreadsheet
        const fileId = childFile.getId();//get the id
        if(fileId != 'IGNORE_THIS_ID_HERE'){
        addRecruitingPage(fileId);//do the function with the ss ID
      }
    }
  }
}

//this function does the copying
function addRecruitingPage(fileId){
  const ss = SpreadsheetApp.openById(fileId);
  const newSheet = ss.insertSheet('recruiting',4);//insert sheet and name it recruiting
  const newCells = newSheet.getRange('A1:H1');
  const funds = ss.getSheetByName('fundraising');//get existing sheet named fundraising
  const fundCells = funds.getRange('A1:H1');//get this range of cells
  fundCells.copyTo(newCells); //copy it to the new recruiting sheet
}

Leave a Reply