5

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

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

google-apps-script 是否可以执行“PasteSpecial - Values”?

这是我目前正在使用的线路:

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

谁能告诉我如何在这些值移动到 sheet2 之前将它们锁定?

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

4

2 回答 2

19

作为替代方案,您可以使用带有高级参数的 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();
}
于 2013-04-18T22:14:35.770 回答
4

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

这是一个可以完成这项工作的实用程序函数。它也可以作为 gist 使用。请注意,它将范围对象作为参数。

代码

/**
 * 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);
}
于 2013-04-18T18:35:52.173 回答