簡體   English   中英

getSheets() Google Apps Script 多次調用問題

[英]getSheets() Google Apps Script multiple calls issue

(為了這篇文章的目的,我將谷歌電子表格中的每個“工作表”稱為標簽,我發現在閱讀時命名約定令人困惑)

在 Google Sheets 插件中,我試圖創建一個設置過程,允許用戶根據該表單的提示輸入 Google 表單的鏈接(我不只是將所有 ID 拉入手動代碼是使用的表單本身可能會因用戶而異),並將該表單的響應鏈接到電子表格,然后使用預先分配的名稱重命名該選項卡。

無論出於何種原因,每當我getSheets()調用getSheets()函數時,調用的返回值與第一次調用的返回值相同。 例如,如果我有 3 個標簽,名為“第一、第二、第三”並且我運行了附加的代碼, sheetList正確返回為[first, second, third] 但是,說在for循環期間,添加了一個選項卡(作為鏈接表單的結果),然后我再次調用getSheets()以獲取新的第一個選項卡(應該是鏈接的表單數據),返回的仍然是[first]

不知道從哪里開始,這是應用程序腳本的問題嗎? 還是我的方法? 任何提示或建議將不勝感激。

    const separateSheetNames = [
    "English Household Information",
    "English Camper Information",
    "English Parent Signatures",
    "English Household Number Recovery",
    "Spanish Household Information",
    "Spanish Camper Information",
    "Spanish Parent Signatures",
    "Spanish Household Number Recovery"
  ];
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheetList = []
  ss.getSheets().forEach(function(val){sheetList.push(val.getName())});

  for (i=0;i<separateSheetNames.length;i++){
    var ui = SpreadsheetApp.getUi();
    var currentSheetName = separateSheetNames[i]
    var isAlreadySheet = sheetList.indexOf(currentSheetName)

    if (isAlreadySheet == -1){
      var formUrl = ui.prompt('Paste the link for the ' + currentSheetName + ' form').getResponseText()
      var form = FormApp.openByUrl(formUrl)
      const ssId = ss.getId();
      form.setDestination(FormApp.DestinationType.SPREADSHEET, ssId)
      var firstsheet = ss.getSheets()[0]
      console.log('firstSheetName ' + firstsheet.getName())
      firstsheet.setName(currentSheetName)
      var currentSheetLastCol = ss.getSheetByName(currentSheetName).getLastColumn()+1
      ss.getSheetByName(currentSheetName).getRange(1,currentSheetLastCol).setValue('Row in Combined Data')
    }
  }

將此留給可能遇到類似問題的任何其他人-@TheMaster 提供的解決方案完美運行:

getSheets()調用之前嘗試SpreadsheetApp.flush()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM