Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google script to copy and rename a sheet and name is based on a cell reference

I'm new to google scripts and I need to copy the current active sheet to a new sheet and then rename this sheet based on a cell value. My issue is the cell value is a date and the below code works but instead on renaming the sheet 30-May-2014 it is returning the numeric equivalent 41789. How can I paste the actual date.

function CreateNewTimesheet() {

  // The code below makes a duplicate of the active sheet
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  SpreadsheetApp.getActiveSpreadsheet().duplicateActiveSheet();

  // The code below will rename the active sheet to Month End date based on cell O3
 var myValue = SpreadsheetApp.getActiveSheet( ).getRange("O3").getValue();
 SpreadsheetApp.getActiveSpreadsheet().renameActiveSheet(myValue);

}
like image 359
user3604137 Avatar asked May 05 '14 12:05

user3604137


People also ask

How do I copy and rename a sheet in Google Sheets?

To duplicate a sheet:Click the tab of the sheet you want to duplicate, then select Duplicate from the menu that appears. A duplicate of the sheet will appear in the sheets toolbar. It will be named as a copy of the original sheet, such as Copy of May. If you want, you can rename the sheet.

How do you dynamically reference a sheet in Google Sheets?

So, how do you dynamically reference another sheet in Google Sheets? The best option is to use the INDIRECT formula. This is great if you have multiple sheets that are identical but have different data. You can pull all of this information dynamically into one sheet using the INDIRECT function.


1 Answers

You would need to format the value into a string and then use it to set the name.

var localTimeZone = "Europe/London";
var dateFormatForFileNameString = "yyyy-MM-dd'at'HH:mm:ss";

function CreateNewTimesheet() {

  // The code below makes a duplicate of the active sheet
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  SpreadsheetApp.getActiveSpreadsheet().duplicateActiveSheet();

  // The code below will rename the active sheet to Month End date based on cell O3
 var myValue = SpreadsheetApp.getActiveSheet( ).getRange("O3").getValue();
 var dateString = getDateString_(myValue);
 SpreadsheetApp.getActiveSpreadsheet().renameActiveSheet(dateString);
}

//Function to get Date as a string
function getDateString_(dateValue) {
      return Utilities.formatDate(dateValue, localTimeZone,
                                  dateFormatForFileNameString);
}

Hope that helps.

like image 155
VLBaindoor Avatar answered Oct 07 '22 03:10

VLBaindoor