Reputation: 49
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);
Upvotes: 0
Views: 1403
Reputation:
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:
DataCopied
Array (number of rows) with DataCopied.length
DataCopied
Array (number of columns) DataCopied[0].length
.DataCopied
with setValues()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);
}
Upvotes: 2