Search code examples
google-apps-script

App script to copy all data from Workbook A to Workbook B, appending to first blank row not working correctly


I modified a script I found to copy data from the 'Data' tab of workbook A to the 'LookerData' tab of workbook B, but need it to add continuously to the 'LookerData' tab with no blank rows between.

The first time I run it, copies fine. But everytime I run it after that it starts the data 27 rows below the last entry. Why is it not starting at the first empty row?

data format

https://docs.google.com/spreadsheets/d/1mzAizqlyEGfhKH6DJdNCMXvsAH9JxihVHucOsJNvd2A/edit?usp=drivesdk

`// https://stackoverflow.com/questions/48691872/google-apps-script-copy-data-to-different-worksheet-and-append
// Copies to Row 2 of target sheet the first time  and then appends to first blank row.

function CopyRange() {
 var sss = SpreadsheetApp.openById(’SpreadsheetA ID’); //replace with source ID
 var ss = sss.getSheetByName('Data'); //replace with source Sheet tab name
 var range = ss.getRange(2, 1, ss.getLastRow(), ss.getLastColumn()); //assign the range you want to copy
 var data = range.getValues();

// Logger.log(data);

 var tss = SpreadsheetApp.openById(‘SpreadsheetB ID’); //replace with destination ID
 var ts = tss.getSheetByName('LookerData'); //replace with destination Sheet tab name

 ts.getRange(ts.getLastRow()+1, 1,ss.getLastRow(), ss.getLastColumn()).setValues(data); 

}
`

Solution

  • I think I have finally worked out the problems by learning some things the hard way. Please correct me if any of these assumptions are wrong. The getLastRow being wrong due to array formulas in some of the columns went away after I made sure both the source and destination sheets had the same number of columns and started with the same number of rows (1000). Then I made sure the data for both started in Row2 with Row 1 being the header. (Data was starting in Row3 with Row 2 being blank). Script is now working as needed. Thx to all.