简体   繁体   English

从1张纸中复制值并将值设置到另一张纸的最后一行

[英]Copy values from 1 sheet and set values to last row of another sheet

I know this has been done before, but I'm struggling to get mine working, I want to copy all data from sheet 'Templates' to 'History' sheet. 我知道以前已经做过,但是我正在努力使我的工作正常,我想将所有数据从表“模板”复制到“历史”表。

I want to send the values in a new row at the bottom of history sheet. 我想将值发送到历史记录表底部的新行中。

Here is my working code, I just need to change where the values are set. 这是我的工作代码,我只需要更改设置值的位置。

var sheetTemplate = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Template');
var sheetHistory = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('History');

var getRange = sheetTemplate.getDataRange();
var DataCopied = SRange.getValues();

sheetHistory.getRange("a2:F7").setValues(DataCopied);

You're using the getDataRange() and getValues() methods, this will return the corresponding values in which data is present in a two-dimensional array, so when you copy the values to the new sheet with setValues() you need to take into account the dimensions of the data retrieved so they match, you need to: 您正在使用getDataRange()getValues()方法,这将返回二维数组中存在数据的相应值,因此当您使用setValues()将值复制到新工作表时,需要考虑到检索到的数据的大小以便它们匹配,您需要:

  1. Get the last available row of the History Sheet with getLastRow() 使用getLastRow()获取历史记录表的最后一个可用行
  2. Get the "height" of the DataCopied Array (number of rows) with DataCopied.length 获得了“高度” DataCopied阵列(行数)与DataCopied.length
  3. Get the "width" of the DataCopied Array (number of columns) DataCopied[0].length . 获取DataCopied数组的“宽度”(列数) DataCopied[0].length
  4. Get the range of that dimensions with getRange(row, column, numRows, numColumns) . 使用getRange(row,column,numRows,numColumns)获得该尺寸范围。
  5. Set the values of the DataCopied with setValues() 使用setValues()设置DataCopied的值

Your code should look like this: 您的代码应如下所示:

function myFunction(){
  var sheetTemplate = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Template');
  var sheetHistory = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('History');

  var getRange = sheetTemplate.getDataRange();
  var DataCopied = getRange.getValues();

  // I defined the variables for better understanding      
  var startRow = sheetHistory.getLastRow()+1; // +1 because remember that while a range index starts at 1, 1, the JavaScript array will be indexed from [0][0].
  var startColumn = 1;
  var numRows = DataCopied.length;
  var numColumns = DataCopied[0].length;
  sheetHistory.getRange(startRow, startColumn, numRows, numColumns).setValues(DataCopied);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM