粘贴特殊值(Paste Special Values)

2019-08-31 11:45发布

我有一个范围由3列和2(或更多)的行。 中间列包含公式: =TRANSPOSE(SPLIT(A1,","))

脚本需要移动(切断),范围到另一片作为 ,而不是公式。

谷歌是否-应用程序脚本有做的一种手段“PasteSpecial的 - 值”?

这是我目前使用的行:

sheet1.getRange("F1:H3").moveTo(sheet2.getRange("A1")); 

谁能告诉我,他们移动到Sheet2中之前,我如何能够锁定这些价值?

(供参考:这仅需要一个代码溶液)

Answer 1:

只是作为一个替代方案,可以使用CopyTo从()以先进的参数只复制值。 为了模仿的moveTo()的作用,你仍然需要清除源范围。

此外,如果它更容易,getRange()接受字符串参考,其包括片材名称。 所以:

function moveValuesOnly() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var source = ss.getRange('Sheet1!F1:H3');
  source.copyTo(ss.getRange('Sheet2!A1'), {contentsOnly: true});
  source.clear();
}


Answer 2:

使用的GetValues()上的目标的源范围和setValues方法()。 你必须保证范围是相同的尺寸。 然后,您可以清除()的来源。

下面是做这项工作的实用程序功能。 它也可以作为一个依据 。 请注意,它需要Range对象作为参数。

/**
 * Move all values from source range to destination range. Upon
 * completion, source range will be cleared. Source values will
 * be moved into a destination range starting at the "top left"
 * of the destination range, using the dimensions of the source
 * range. This is a blind copy, with no overwrite test.
 *
 * @param {Range} source Range Object to take values from.
 * @param {Range} destination Range Object to receive values.
 *
 * @returns nothing
 */
function moveRange(source,destination) {
  var sourceSheet = source.getSheet();
  var destSheet = destination.getSheet();
  var sourceData = source.getValues();
  var dest = destSheet.getRange(
    destination.getRow(),        // Top row of destination
    destination.getColumn(),     // left col of destination
    sourceData.length,           // # rows in source
    sourceData[0].length);       // # cols in source (elements in first row)
  dest.setValues(sourceData);
  source.clear();
}

测试功能

一个成功的测试将清除整个源范围内,和它的内容将显示在目的地范围,因为只有值。 目标尺寸将匹配源尺寸不论什么作为目标提供 - 这只是左上角锚定的举动。

function test_moveRange() {
  var sourceSheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[0];
  var destSheet = SpreadsheetApp.getActiveSpreadsheet().getSheets()[1];

  var source = sourceSheet.getRange("A7:C10");
  var destination = destSheet.getRange("C4:H2");
  moveRange(source,destination);
}


文章来源: Paste Special Values