0
votes

I have a spreadsheet with some information on, and I want it to copy across to a second sheet automatically. I also want it to copy across automatically when I insert new rows within the rows copied across. I found the code below but I don't completely understand what I would have to do to it for it to do what I want, or if I would need to add anything. I have basic coding knowledge but not much, so if someone could explain this it would be much appreciated.

function myFunction() {
var source = SpreadsheetApp.openById('xxxxxx');
var sourcesheet = source.getSheetByName('sheet1');
var target = SpreadsheetApp.openById('xxxxx')
var targetsheet = target.getSheetByName('sheet1');
var rangeValues = sourcesheet.getRange(2, 1, sourcesheet.getLastRow(), sourcesheet.getLastColumn()).getValues();
targetSheet.appendRow(rangeValues); 
}
2

2 Answers

1
votes

You can do it much more simply by using the =IMPORTRANGE() function, e.g. =IMPORTRANGE("https://docs.google.com/spreadsheets/d/10X7KGGFd4U8IwQO4QgunmLMphtwwEF9bGwfu3Vrm3AM/","Sheet1!A:Z")

Put this formula in the second spreadsheet, replace the URL with the URL of the first spreadsheet (I just put an example one) and tweak the "sheet_name!range" with what you need. The 2nd spreadsheet will then automatically update whenever the inputted range of the 1st spreadsheet changes :)

Hope this helps!

1
votes

If you don't completely understand the code that you are using for these, then you can check the documentation of Google Apps Script for Spreadsheet to know the use and purpose of different classes and methods.

Now, for your question about rows that you need to copy from one sheet to another, I think this tutorial can help you with that. It explains here the step by step procedure that you need to do in your Apps Script.

For more information, check this related SO questions: