Lydia Meier
Lydia Meier

Reputation: 1

I want to use the same google script twice on a google sheet but it will only run once

I wrote this script for google sheets and want to use it twice in the same sheet. When I put them in the same script part of the sheet it only runs one of them and not both of them.

Here is the of I've been putting the script in:

var sourceSpreadsheetID = "INPUT1";//these are global Cooper Edit
var sourceWorksheetName = "INPUT1";
var targetSpreadsheetID = "INPUT1";
var targetWorksheetName = "INPUT1";

function importData1() {
  var thisSpreadsheet = SpreadsheetApp.openById(sourceSpreadsheetID);
  var thisWorksheet = thisSpreadsheet.getSheetByName(sourceWorksheetName);
  var thisData = thisWorksheet.getDataRange().getValues();
  var toSpreadsheet = SpreadsheetApp.openById(targetSpreadsheetID);
  var toWorksheet = toSpreadsheet.getSheetByName(targetWorksheetName);
  toWorksheet.clearContents();
  toWorksheet.getRange(1, 1, thisData.length, thisData[0].length).setValues(thisData); 
}



    var sourceSpreadsheetID = "INPUT2";//these are global Cooper Edit
    var sourceWorksheetName = "INPUT2";
    var targetSpreadsheetID = "INPUT2";
    var targetWorksheetName = "INPUT2";

    function importData2() {
      var thisSpreadsheet = SpreadsheetApp.openById(sourceSpreadsheetID);
      var thisWorksheet = thisSpreadsheet.getSheetByName(sourceWorksheetName);
      var thisData = thisWorksheet.getDataRange().getValues();
      var toSpreadsheet = SpreadsheetApp.openById(targetSpreadsheetID);
      var toWorksheet = toSpreadsheet.getSheetByName(targetWorksheetName);
      toWorksheet.clearContents();
      toWorksheet.getRange(1, 1, thisData.length, thisData[0].length).setValues(thisData); 
    }

Cooper Edit: The global declarations get run everytime you run every function.

Upvotes: 0

Views: 82

Answers (1)

Anees Hameed
Anees Hameed

Reputation: 6544

If you want to run both the function from a single call then add a middleman which will call both the functions. for eg

function middleman(){
  importData1();
  importData2();
}

Upvotes: 1

Related Questions