【问题标题】:Can I use Google Apps Script to replace text across multiple tabs in a Google Sheet?我可以使用 Google Apps 脚本替换 Google 表格中多个选项卡中的文本吗?
【发布时间】:2021-07-01 14:58:26
【问题描述】:

我正在构建 a previous project,其中我有一个 Google Form,它在 Google Sheet 中接受响应,并使用 template Sheet 填充表单响应并让它生成一个新的工作表文档。这是我在现实中尝试执行的一个非常简单的版本,但目标保持不变:我尝试在生成新标签时替换模板工作表中多个选项卡中的文本。

目前,在我的Apps Script 中,我的代码能够成功复制模板文件并相应地命名:

//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]);

我遇到的问题是工作表的第一个选项卡被填充,但第二个选项卡没有。

为了填写第二个标签,我还必须在某处添加更多内容吗?这在 Google Apps 脚本中是否可行?


完整代码如下:

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

【问题讨论】:

  • 行未定义。是的,我们希望您的代码最少,但它也必须是可重现的。再试一次。我不喜欢以下链接。如果您需要我的帮助,请在问题中发布我需要的所有内容。
  • 很抱歉。我已将整个代码复制并粘贴到原始帖子底部的更新中。如果有帮助,我可以更新表格和表单的更多屏幕截图。

标签: javascript google-apps-script google-sheets


【解决方案1】:

回答

  • 您可以尝试一种循环方法,使用getSheets() 方法访问newSheet 电子表格文件中的所有工作表选项卡。

只需将部分脚本从newSheet 的创建到A1.createTextFinder 的最后一行替换为以下脚本:

[更新] 示例脚本

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

样本测试:

newSheet 文件的示例副本,带有 2 个工作表标签

脚本测试演示

newSheet 文件包含 2 个工作表标签:

Sheet 1

Sheet 2

【讨论】:

  • 在我添加了您推荐的代码后,我收到一条错误消息:TypeError: Assignment to constant variable。此错误与for (sheet = 0; sheet &lt; newSheet.getSheets().length; sheet++) { 行有关
  • 知道了,是的,我已经更新了我的脚本并将 for 循环中的“工作表”更改为“当前工作表”。看起来它干扰了行 sheet.getRange(i + 1, 7).setValue(orderLink)。
  • 赢家!非常感谢!适用于我的示例以及我的主要应用程序。完美。
猜你喜欢
  • 2014-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-13
  • 2021-12-27
  • 1970-01-01
相关资源
最近更新 更多