Home > Enterprise >  Google script : Sheet duplicate rename and move to the end
Google script : Sheet duplicate rename and move to the end

Time:11-10

I have a simple invoicing system made and my only issue is that I don't know how to combine multiple scripts into one. What I want is that when I press the create invoice to make a copy of the print sheet and rename it accordingly ( Invoice nr Customer name , lets say B12 cell contains the customer name and G12 the invoice number so the sheet name would be "James Bond 007") after that the sheet to be moved to the end of the sheets. So far I use these scripts to achieve the duplication and moving to the end

function Dupewithvaluesonly() {
  const range = SpreadsheetApp.getActiveSpreadsheet().duplicateActiveSheet().getDataRange();
 
  range.copyTo(range, {formatOnly: true});  // Added
  range.copyTo(range, {contentsOnly: true});
  
}

function MovetoEnd() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.moveActiveSheet(ss.getNumSheets());
}


CodePudding user response:

I believe your goal is as follows.

  • You want to copy the active sheet and set the sheet name using the values from the cells "B12" and "G12" of the active sheet.
  • And also, want to convert the cell values to static values.
  • You want to achieve this by merging your 2 functions.

In this case, how about the following modification?

Modified script:

function myFunction() {
  // Copy the active sheet.
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.duplicateActiveSheet();

  // Retrieve the values from cells "B12" and "G12". And set the sheet name.
  const [b12, , , , , g12] = sheet.getRange("B12:G12").getValues()[0];
  sheet.setName(`${g12} ${b12}`);

  // Convert values to static values.
  const range = sheet.getDataRange();
  range.copyTo(range, { formatOnly: true }); // This is from your script.
  range.copyTo(range, { contentsOnly: true }); // This is from your script.

  // Move the copied sheet to the last tab.
  ss.moveActiveSheet(ss.getNumSheets()); // This is from your script.
}

Note:

  • If you want to use the specific sheet instead of the active sheet, please modify the above script as follows.

    • From

        const sheet = ss.duplicateActiveSheet();
      
    • To

        const sheet = ss.getSheetByName("Sheet1").copyTo(ss).activate(); // Please set the sheet name to "Sheet1".
      
  • Related