简体   繁体   中英

GAS Scan all spreadsheets in folder and change a specific cell value and sheet name?

 function getAllSheetsInFolder () { var folder = DriveApp.getFolderById("ID"); var contents = folder.getFiles(); Logger.log("file length: " + contents.length); var file; var data; var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Class Data") sheet.clearContents(); var numOfFiles = contents.length; for (var i = 0; i < numOfFiles; i++) { file = contents[i]; Logger.log("count: " + i); //Reset to null on every iteration var onecell = null; var theRange = null; var theFileType = file.getFileType(); Logger.log("theFileType: " + theFileType); if (theFileType==DocsList.FileType.SPREADSHEET) { var sheet = SpreadsheetApp.open(file).getSheets()[0]; var cell = sheet.getRange(2,7); cell.setValue('RTI') }; } } } 

I am looking to write a GAS that scans all of the spreadsheets in a folder and changes the value of cell (G2) in every spreadsheet. Can it be set up to scan all spreadsheets in the folders and subfolders? Or just each spreadsheet in a specific folder.

I am also looking to change the name of of the 4th sheet in each of the spreadsheets as well. I just wanted to see if you guys thought this was a possibility before I start messing with some code.

Here some code that gets a reference to a folder, and loops through the folder looking for spreadsheet files.

function getAllSheetsInFolder () {
  var folder = DriveApp.getFolderById("Your Folder ID");
  Logger.log('folder: ' + folder);

  var sheetFiles = folder.getFilesByType("application/vnd.google-apps.spreadsheet");
  Logger.log("sheetFiles.hasNext(): " + sheetFiles.hasNext());

 while (sheetFiles.hasNext()) {
   var file = sheetFiles.next();

   var theFileType = file.getMimeType();
   Logger.log("theFileType: " + theFileType);


   var ssID = file.getId();
   Logger.log('ssID: ' + ssID);

   var thisSS = SpreadsheetApp.openById(ssID);

   var sheet = thisSS.getSheets()[0];

   var cell = sheet.getRange(2,7);
   cell.setValue('Test Cell Set')
  };
};

This code uses a combination of DriveApp to get a list of spreadsheet files in a specific folder, then uses SpreadsheetApp to actually open the spreadsheet file, and write a value to a cell.

The DocsList Class is now deprecated. My original code was using DocsList rather than DriveApp , but they are very different. DriveApp can get a Folder, a list of files, and set and get other file information, but DriveApp can't open a spreadsheet file. You have to open the spreadsheet file with SpreadsheetApp . So the code must first get the folder, then a list of all spreadsheets in the folder, and the ID of each spreadsheet. Then open the spreadsheet by ID.

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