Google脚本-创建表单后找不到目标表

问题描述 投票:1回答:1

我的脚本以编程方式创建了Google表单,并将目标设置为当前电子表格:

var sheetId = SpreadsheetApp.getActiveSpreadsheet().getId();  
var form = FormApp.create(acctName).setTitle(acctName).setDestination(FormApp.DestinationType.SPREADSHEET, sheetId);

// several form items added here

[下一步,我想重命名目标工作表并进行一些格式编辑。但是,当我这样做时,工作表似乎不存在。例如,getSheets()不包含新的工作表! (是的,理想情况下,我想按ID打开工作表;请参见下面的功能,该功能也不起作用。)

var sheets = SpreadsheetApp.openById(form.getDestinationId()).getSheets();
SpreadsheetApp.setActiveSheet(sheets[0]);

上面的代码打开了我认为索引1而不是索引0的位置,因为工作表没有被索引。我什至尝试创建几秒钟的延迟(希望让客户端和服务器之间进行同步只是时间问题),但没有成功。

我也尝试过以下类似的方法,如Stack Overflow此处其他地方所建议,但是即使通过单独的函数调用,目标工作表也不会出现在getSheets()中:

function getFormDestinationSheetId(form) {

  var destinationId = form.getDestinationId();      
  if(destinationId) {

    var spreadsheet = SpreadsheetApp.openById(destinationId);        
    spreadsheet.getSheets().forEach(          
      function(sheet) {            
        var sheetFormUrl = sheet.getFormUrl();
        if(sheetFormUrl) {             
          var sheetForm = FormApp.openByUrl(sheetFormUrl);
          if(sheetForm.getId() == form.getId()) {
            return sheet.getSheetId();
          }
        }
      }
    );
  }
  return null;
}

我还没有找到任何人在网络上遇到类似的问题。任何意见,将不胜感激。谢谢!

google-apps-script google-sheets google-form
1个回答
1
投票

欢迎堆叠!

我假设您的脚本已绑定到工作表?根据您调用脚本的方式,由于浏览器缓存,您可能看不到新的工作表。

function myFunction() {
  var sheet = SpreadsheetApp.getActive();
  var sheetId = sheet.getId();  
  var form = FormApp.create('acctName').setTitle('acctName').setDestination(FormApp.DestinationType.SPREADSHEET, sheetId);

  var ssSheets = sheet.getSheets();

  var respSheet = ssSheets[0]

  respSheet.getRange('A1').setBackground('RED');
  respSheet.getRange('C1').setFormula('=COUNTA($C$2:$C)');
  respSheet.setColumnWidth(2, 100);

  SpreadsheetApp.flush();
}
© www.soinside.com 2019 - 2024. All rights reserved.