简体   繁体   中英

Copy rows automatically to new sheet with Google Apps Script

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); 
}

You can do it much more simply by using the =IMPORTRANGE() function, eg =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!

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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