Google脚本将一个单元格写入另一个电子表格中的范围

时间:2015-03-19 16:59:09

标签: javascript google-apps-script google-sheets

把我的头发拉到这里。

我正在尝试构建类似数据库的#34; Google表格上的结构(修改一个文档中的条目,在其他地方更新)。

  • 2个电子表格,需要将数据从一个移动到另一个
  • 在" Spreadsheet1"上选择SINGLE CELL,复制到" Spreadsheet2"
  • 上的单元格范围
  • 我遇到了很多错误并修复了它们,但这个错误是无敌的:

未找到范围(第10行,文件"代码")

我做错了什么?

function ImportDataRange() {

  var activeSs = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = activeSs.getSheetByName("PRODUCT dashboard");
  var ssOrigin = SpreadsheetApp.openById("1gF-IsnPdnjAaoUSwOOaBfWTmK1eVzxDG87XPzjjsWxA");
  var sheetOrigin = ssOrigin.getSheetByName("INITIAL_BUDGETS");

  for (var i = 7; i < 26; i++) {

    var rangeOrigin = sheetOrigin.getRange("i, 1");
    var dataOrigin = rangeOrigin.getValues();

    for (var i = 10; i < 275; i += 6) {
      sheet.getRange("i, 1").setValues(dataOrigin);
    }
  }

} 

你可能得到了它但是我需要:将文件1中的A7复制到document2的15个单元格中,而不是将单元格A8格式的文档1复制到document2的下一个15个单元格中,然后取A9 ....你得到它。

2 个答案:

答案 0 :(得分:1)

我将如何做到这一点:

function ImportDataRange() {

  var activeSs = SpreadsheetApp.getActiveSpreadsheet(),
      sheet = activeSs.getSheetByName("PRODUCT dashboard"),
      rangeSheet = sheet.getRange(10, 1, 265), // 3rd number is the number of rows to get into the range, as described in documentation
      valsSheet = rangeSheet.getValues(); //Get all values in a double array, this is to keep any previous values in the sheet, also it already gets the array just as it is needed to use in setValues()
      ssOrigin = SpreadsheetApp.openById("1gF-IsnPdnjAaoUSwOOaBfWTmK1eVzxDG87XPzjjsWxA"),
      valsOrigin = ssOrigin.getRange(7, 1, 15).getValues(), // Same as the other getRange, gets 15 lines, starting in line 7
      sheetOrigin = ssOrigin.getSheetByName("INITIAL_BUDGETS");

  for ( origins in valsOrigin  ) { // For each value in the valsOrigin array, do something -> in each loop origins will be the next index, Eg. 0, then 1, then 2...
    for (var i = 10; i < 275; i += 6) {
      i = (+i) + (+origins); // Add the origins so it don't begin in the same line, altough it will start to overwrite after 6 loops, you should look into this logic - also, the '+' converts it to number, as they can be strings
      valsSheet[i][0] = valsOrigin[origins][0]; // Puts the current value of origins in the target array
    }
  }
  rangeSheet.setValues( valsSheet ); // Inserts all values at once in the range
}

最小化SpreadsheetApp调用,这些调用成本很高,在GAS中受到限制,也使代码更清晰。

答案 1 :(得分:0)

在getRange()参数中删除引号,您不使用字符串。只需要.getRange(i, 0)

此外,如果您只是将一个单元格作为范围和一个设置值,则可以使用.setValue()