粘贴特殊值

时间:2013-04-18 18:24:35

标签: google-apps-script google-sheets

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

脚本需要将该范围移动(剪切)到另一个工作表上 ,而不是公式。

google-apps-script是否有办法执行“PasteSpecial - Values”?

以下是我目前正在使用的行:

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

有人能告诉我在进入sheet2之前如何锁定这些值吗?

(仅供参考:这只需要代码解决方案)

2 个答案:

答案 0 :(得分:17)

作为替代方案,您可以使用copyTo() with advanced arguments仅复制值。要模仿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();
}

答案 1 :(得分:4)

在源范围上使用getValues(),在目标上使用setValues()。您必须确保范围是相同的尺寸。然后你可以清除()源。

这是一个完成工作的实用功能。它也是available as a gist。请注意,它将Range Objects作为参数。

代码

/**
 * 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);
}
相关问题