Search code examples
google-apps-scriptgoogle-appsgoogle-sheets-api

Copying range of data from one spreadsheet to another deletes data from destination


The end goal is to successfully copy a range of cells from one spreadsheet to another every 10-15 minutes. Those cells get populated by an external script via the Drive API.

The issue is when the script is ran, it just deletes all the data in the destination range, which makes no sense to me!!

function ExportHourlyCitizenData() {
  var ssSource = SpreadsheetApp.openById("1kDupxE8csxYibYz-cfzkhzehwzTQGjFXOlCU3bJNUIg");
  var sheet = ssSource.getSheetByName("Hourly Citizen Capture");
  var ssDest = SpreadsheetApp.openById("1tMAP0fg-AKScI3S3VjrDW3OaLO4zgBA1RSYoQOQoNSI");
  var sheetDest = ssDest.getSheetByName("Hourly Citizen Capture");
  // Grabs the source range, some of the grabbed cells are empty..
  var rangeSource = ssSource.getRange("B70:Z168");
  var dataSource = rangeSource.getValues();
  // sets the destination cells.
  sheetDest.getRange("B85:Z183").setValues(dataSource);
}; 

So the idea was pretty simple, but I messed up something in here somehow. I am moving a decently sized set of data, so maybe there is a more efficient way as well?

EDIT: I tried using importrange but the issue with that is that it did not update when I pushed data into the spreadsheet via the drive api which was a significant problem.


Solution

  • This may be the issue:

    var rangeSource = ssSource.getRange("B70:Z168");
    

    Use source data sheet variable sheet instead of the spreadsheet variable ssSource.