Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

javascript - 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);

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...