0

I am building on a previous project in which I have a Google Form which takes responses in a Google Sheet and uses a template Sheet to populate the Form responses and have that generate a new Sheet document. This is a very dumbed-down version of what I'm trying to execute in reality, but the goals remain the same: I am trying to replace text across multiple tabs in the template Sheet when generating a new one.

Currently, in my Apps Script, I have code which is successfully able to make a copy of the template file and name it accordingly:

//Enter collected info into Requirements Template
      const googleSheetTemplate = DriveApp.getFileById('1wqCwMhpuDLReU1hE1CbcDL-Vdw_4zge1xM6oOl34Ohg');
      const destinationFolder = DriveApp.getFolderById('1GxNZQmP8mxHBhVl5AMoqBFs8sAIYzcm3');

      const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form Responses 2');

      const copy = googleSheetTemplate.makeCopy(`${row[3]}, ${row[0]} Vehicle Order` , destinationFolder);
      const newSheet = SpreadsheetApp.openById(copy.getId());
      const A1 = newSheet.getDataRange();

And the next few lines which are meant to be able to find and replace certain strings within the newly copied Sheet are as follows:

  A1.createTextFinder("{{Customer}}").replaceAllWith(row[3]);
  A1.createTextFinder("{{Car}}").replaceAllWith(row[1]);
  A1.createTextFinder("{{Color}}").replaceAllWith(row[2]);
  A1.createTextFinder("{{Delivery}}").replaceAllWith(row[5]);

The issue I am experiencing is that the first tab of the Sheet gets populated, but the second tab does not.

Is there more I must add somewhere in order to get the second tab filled out? Is this even possible in Google Apps Script?


Entire code below:

function myFunction() {
    // get the spreadsheet information
  const ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  //const responseSheet = ss.getSheetByName('Form Responses 2');
  const data = ss.getDataRange().getValues();
  //console.log(data);

  // Loop over the rows
  data.forEach((row,i) => {

    // Identify whether notification has been sent
    if (row[4] === '') {

      // Get the Form info
      var emailTo = "jeffreyabr@gmail.com"
      var subject = 'Car Request';
      const Timestamp = row[0];
      var Car = row[1];
      var Color = row[2];
      var requestor = row[3]
      var delivery = row[5];

      //Form variable declarations
      formTime = Timestamp;
      formCar = Car;
      formColor = Color;
      formName = requestor;
      formDelivery = delivery;

      //Enter collected info into Requirements Template
      const googleSheetTemplate = DriveApp.getFileById('1wqCwMhpuDLReU1hE1CbcDL-Vdw_4zge1xM6oOl34Ohg');
      const destinationFolder = DriveApp.getFolderById('1GxNZQmP8mxHBhVl5AMoqBFs8sAIYzcm3');

      const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Form Responses 2');

      const copy = googleSheetTemplate.makeCopy(`${row[3]}, ${row[0]} Vehicle Order` , destinationFolder);
      const newSheet = SpreadsheetApp.openById(copy.getId());
      const A1 = newSheet.getDataRange();

      A1.createTextFinder("{{Customer}}").replaceAllWith(row[3]);
      A1.createTextFinder("{{Car}}").replaceAllWith(row[1]);
      A1.createTextFinder("{{Color}}").replaceAllWith(row[2]);
      A1.createTextFinder("{{Delivery}}").replaceAllWith(row[5]);


      const orderLink = newSheet.getUrl();
      //Add URL to Sheet
      sheet.getRange(i + 1, 7).setValue(orderLink)

      orderBlob = [];

      //Get the blob of order attachment
      if(row[6]){
        var order1 = row[6].split(', ');
      
        order1.forEach(url => {
          var orderFileId = url.replace('https://drive.google.com/open?id=','');
          var orderFile = DriveApp.getFileById(orderFileId);
          orderBlob.push(orderFile.getBlob());
        });
      }


      let body = '';

      // Generate email
      var html = HtmlService.createTemplateFromFile("email.html");
      var htmlText = html.evaluate().getContent();
      
      // Send email
      GmailApp.sendEmail(emailTo, subject, body, {htmlBody: htmlText, attachments: orderBlob})

  // Mark as Notified
  const g = 'Notification sent';
  ss.getRange(i + 1,5).setValue(g);
      }
  })
}
  • row is undefined. Yes we want you're code to be minimal but it also has to be reproducible. Try again. I don't like following links. If you want my help post everything I need in the question. – Cooper Jul 01 '21 at 15:20
  • Sorry about that. I have copied and pasted my entire code into an update at the bottom of the original post. I can update with more screenshots of the Sheets and Forms if that helps at all. – Jeff Abrahams Jul 01 '21 at 17:11

1 Answers1

2

Answer

  • You can try a looping method to access all of the sheet tabs inside of your newSheet Spreadsheet file using the getSheets() method.

Just replace part of your script from the creation of newSheet to the last line of A1.createTextFinder with the script below:

[UPDATED] Sample Script

  const newSheet = SpreadsheetApp.openById(copy.getId());
    
  for (currentSheet = 0; currentSheet < newSheet.getSheets().length; currentSheet++) {
    const a1 = newSheet.getSheets()[currentSheet].getDataRange();
    a1.createTextFinder("{{Customer}}").replaceAllWith(row[3]);
    a1.createTextFinder("{{Car}}").replaceAllWith(row[1]);
    a1.createTextFinder("{{Color}}").replaceAllWith(row[2]);
    a1.createTextFinder("{{Delivery}}").replaceAllWith(row[5]);
  }

Sample Test:

Sample copy of the newSheet file w/ 2 sheet tabs

enter image description here

enter image description here

Script test demonstration

enter image description here

The newSheet file that contains 2 sheet tabs:

Sheet 1

enter image description here

Sheet 2

enter image description here

SputnikDrunk2
  • 3,398
  • 1
  • 5
  • 17
  • I'm getting an error that reads: `TypeError: Assignment to constant variable` after I have added the code you recommended. This error is in reference to the line `for (sheet = 0; sheet < newSheet.getSheets().length; sheet++) {` If you didn't see already, I copied and pasted my entire code in the end of the original post. – Jeff Abrahams Jul 01 '21 at 17:31
  • Got it, yes, I have updated my script & changed the "sheet" in the for loop to "currentSheet". It looks it has interfered with the line sheet.getRange(i + 1, 7).setValue(orderLink). – SputnikDrunk2 Jul 01 '21 at 17:41
  • 1
    Winner! Thanks so much! Works in my example as well as my primary application. Perfect. – Jeff Abrahams Jul 01 '21 at 17:48