繁体   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