javascriptgoogle-sheetsgoogle-apps-script

Running a similar App Scripts code on Multiple Sheets


Just started to use App Scripts recently (Beginner programmer here). I'm trying to automate the creation of a column + transposition of data from column B to newly created column C.

It's working fine, but when I try to replicate the script on multiple sheets, only one of the script works.

Below is my code (I tried to duplicate my constants to replicate the first script but then the first script does not work anymore. I guess I'm doing it the wrong way) :

// First script working fine.
const ss_1 = SpreadsheetApp.getActiveSpreadsheet();
  const sheet_1 = ss_1.getSheetByName('Marketing Report'); 

  function insertColumn() {
  const range_1 = sheet_1.getRange('B1:B300').getValues();
  const newrange_1 = sheet_1.getRange('C1:C300');
  const tmp_1 = new Date();
  const yesterday_1 = new Date(tmp_1.setDate(tmp_1.getDate()-1));
    
  sheet_1.insertColumnAfter(2);
  newrange_1.setValues(range_1);
  sheet_1.getRange('B2').setValue(yesterday_1).setNumberFormat("MMMM");
  }

// Second script, I tried to duplicate my constants to replicate the first script but then the first script does not work anymore. I guess I'm doing it the wrong way
const ss_2 = SpreadsheetApp.getActiveSpreadsheet();
  const sheet_2 = ss_2.getSheetByName('Sales Report'); 

  function insertColumn() {
  const range_2 = sheet_2.getRange('C1:C150').getValues();
  const newrange_2 = sheet_2.getRange('D1:D150');
  const tmp_2 = new Date();
  const yesterday_2 = new Date(tmp_2.setDate(tmp_2.getDate()-1)); 

  sheet_2.insertColumnAfter(3);
  newrange_2.setValues(range_2);
  sheet_2.getRange('C2').setValue(yesterday_2).setNumberFormat("MMMM");
  }

Any help would be highly appreciated !


Solution

  • First of all, try to rename one of the functions in your script since they both have the same name. Don't forget to hit save. Please take note that Google Apps Script can run one function at a time (not including triggers). You can toggle through your functions through the dropdown menu (between the "Debug" and "Execution Log" buttons) to change to the function you would like to run. Make sure that both functions have different names.

    enter image description here