簡體   English   中英

Google Apps 腳本 CopyPasteType.PASTE_VALUES 不斷返回空白值。 此枚舉是否已棄用或我的代碼有問題?

[英]Google Apps Script CopyPasteType.PASTE_VALUES keep returning blank values. Is this enum deprecated or something's wrong with my code?

我正在編寫一個簡單的代碼,目的是:

  1. 在引用列 [n] 的列 [x] 上設置公式
  2. 復制公式(在同一列上)以覆蓋第 [n] 列數據的所有行
  3. 僅使用CopyPasteType.PASTE_VALUES將結果從 Column[x] 復制回 Column [n] 作為值

我的代碼如下所示:

function Test() {
  
  var ss = SpreadsheetApp.getActive()
  var startingcell = ss.getActiveCell()
  ss.getSelection().getNextDataRange(SpreadsheetApp.Direction.DOWN).activate()
  var lastrow = ss.getActiveRange().getNumRows()

  // offset to create formula
  ss.getCurrentCell().offset(0, 1).activate()
  ss.getCurrentCell().setFormulaR1C1('IF(R[0]C1<>0,R[0]C1,12)')
    
  
  // set active range then copy down to cover all row with data on initial column
  ss.getCurrentCell().offset(0, 0, lastrow).activate()
  ss.getCurrentCell().copyTo(ss.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_NORMAL, false)

  // copy paste value back to initial column
  ss.getCurrentCell().offset(0, -1, lastrow).activate();
  ss.getCurrentCell().offset(0, 1, lastrow).copyTo(ss.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
 

}

假設我的數據在 A 列上,我在 B 列上生成公式的offset ,然后嘗試將結果復制粘貼回 A 列

但是我在 A 列中得到的不是值,而是空單元格(初始值被刪除)

我的代碼有什么問題或枚舉被棄用了嗎?

有趣的是,當我改用枚舉CopyPasteType.PASTE_NORMAL時,我得到了預期的結果,其中內容(在本例中為公式)被復制到 A 列(當然,由於循環依賴,粘貼的公式不會運行)

在您的腳本中,如何使用SpreadsheetApp.flush()如下所示?

從:

// copy paste value back to initial column
ss.getCurrentCell().offset(0, -1, lastrow).activate();
ss.getCurrentCell().offset(0, 1, lastrow).copyTo(ss.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);

到:

// copy paste value back to initial column
SpreadsheetApp.flush(); // Added
ss.getCurrentCell().offset(0, -1, lastrow).activate();
ss.getCurrentCell().offset(0, 1, lastrow).copyTo(ss.getActiveRange(), SpreadsheetApp.CopyPasteType.PASTE_VALUES, false);
  • 從你Funny thing is when I use the enum CopyPasteType.PASTE_NORMAL instead, I get the expected result where the content, in this case formula, is copied to Column A (of course the pasted formula wont run due to circular dependency) ,我認為可能需要使用SpreadsheetApp.flush()

參考:

暫無
暫無

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

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