First off, I know a little bit of Javascript but I have no clue to where I would even start on this. I did lots of searching but didn't turn up anything close to what I want. I have a daily task list in google sheets and I want to duplicate each sheet with the next days date when I right click and choose duplicate. Is this even possible? Can it be done in another way?
It is impossible to change what the "duplicate" item of the context menu does. But one can use the following script to provide an alternative way of duplication, via the menu. It adds a new menu item "Custom > New Day" every time the spreadsheet is opened. Invoking this item will duplicate the current sheet with an incremented date as a name, provided that the name follows the ISO format yyyy-mm-dd.
General reference: starting with Google Apps Script.
function duplicate() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = SpreadsheetApp.getActiveSheet();
var sheetDate = new Date(sheet.getName() + 'T00:00:00.000Z');
if (!sheetDate.valueOf()) {
Browser.msgBox('Did not recognize "' + sheet.getName() + '" as a date. Use the format yyyy-mm-dd.');
}
else {
sheetDate.setDate(sheetDate.getDate() + 1);
var newSheetName = sheetDate.toISOString().slice(0,10);
ss.insertSheet(newSheetName, {template: sheet});
}
}
function onOpen() {
SpreadsheetApp.getActiveSpreadsheet().addMenu("Custom", [{name: "New Day", functionName: "duplicate"}]);
}
The bit with + 'T00:00:00.000Z' is there because the implementation of date parsing in Google Apps Script is peculiar: it requires the time component, including milliseconds.
Related
I need your help.
I have an active google form where customers register.
When I submit the form I have 3 activators that run me scripts, especially they convert the ITALIAN date format (dd-mm-yyyy) to USA (yyyy-mm-dd).
Start of action: Upon submitting the form
The problem I find is this.
These scripts do not always work even if from the control panel I find that it has been executed correctly without reporting errors.
A code example:
function respondToFormSubmit() {
var ss = SpreadsheetApp.openById("xxxxxxxxxxxxxxxxxxxxxxxx");
var sheet = ss.getSheets()[0];
// Format column I
var column1 = sheet.getRange("F:F");
var column2 = sheet.getRange("J:J");
var column3 = sheet.getRange("K:K");
var column4 = sheet.getRange("A:A");
// Set new date format on column I
column1.setNumberFormat('yyyy-mm-dd');
column2.setNumberFormat('yyyy-mm-dd');
column3.setNumberFormat('yyyy-mm-dd');
column4.setNumberFormat('yyyy-mm-dd');
};
When the problem occurs, all 3 triggers fail.
The non-functioning occurs 20/30% of the time and this discontinuous "error" does not make me understand what the problem is.
Do you have any suggestions for me?
Thank you so much for your invaluable help.
Mauro
The problem with your script running on trigger are likely propagation
issues
It takes some time for a new form response to be inserted into the
spreadsheet, so your number formatting functionality might be run
before the new row gets inserted.
One thing you can do is implement some waiting time at the beginning
at the function, e.g. with
sleep().
However, if you bind your script to the destination spreadsheet
instead of the form itself - you will be able to use the Google
Sheets event
objects
for Form submit which include range.
Sample usage:
function respondToFormSubmit(e) {
var row = e.range.getRow();
var sheet = e.range.getSheet();
sheet.getRange("F" + row).setNumberFormat('yyyy-mm-dd');
sheet.getRange("J" + row).setNumberFormat('yyyy-mm-dd');
sheet.getRange("K" + row).setNumberFormat('yyyy-mm-dd');
sheet.getRange("A" + row).setNumberFormat('yyyy-mm-dd');
};
I am completely unfamiliar with JavaScript but I am trying to create a script that makes a formatted timestamp in a specific cell when a button is pressed.
I have gotten it to work with a true/false in sheets however I don't know how to make this in JavaScript. This is as far as I have gotten so far and I'm already hitting errors I do not understand.
Can someone help me understand or link me resources on how to figure out some of these problems? I've spent several hours googling and reading Google developer pages trying to learn but I haven't had any luck thus far.
The error:
function myFunction() {
var sheet = SpreadsheetApp.getActiveSheet()
var date = new Date(); var timeStamp = date.getTime(); // Unix Timestamp
var currentTime = date.toLocaleTimeString(); // eg. 10:23:30 AM HKT
sheet.setValue(currentTime);
}
While the accepted answer gives you a completely valid solution, I thought I would walk you through my own process for figuring this out pretty quickly using the documentation (without necessarily having any previous experience with google apps scripts).
The SpreadsheetApp.getActiveSheet() method returns the active Sheet object.
We can browse the docs for the Sheet class to see which methods are available and which might be useful to us.
getActiveRange() looks interesting. It:
Returns the selected range in the active sheet, or null if there is no active range.
So again, searching through the docs for the Range class to see what methods are available to the range class, we can find setValue.
function myFunction() {
var date = new Date();
var timeStamp = date.getTime();
var currentTime = date.toLocaleTimeString();
var sheet = SpreadsheetApp.getActiveSheet();
var activeRange = sheet.getActiveRange();
if (activeRange) {
activeRange.setValue(currentTime);
}
}
Hopefully this answer teaches you a bit more of a step-by-step approach in figuring these kind of problems out in the future.
You need to set the value on a cell, not the entire sheet. To do it on the cell at the very top left, you would select A1 for example:
function myFunction() {
var date = new Date();
var timeStamp = date.getTime(); // Unix Timestamp
var currentTime = date.toLocaleTimeString(); // eg. 10:23:30 AM HKT
var sheet = SpreadsheetApp.getActiveSheet(); // Sheet
var cell = sheet.getRange('A1'); // Cell <------------------------
cell.setValue(currentTime); // <--------------------------------------------
}
I have a public spreadsheet, where people can enter their names under the column "Name". Everything in this sheet is protected, except for the cells in the column "Name". Since the spreadsheet is public, I want to avoid a situation where someone can troll and delete all the names that have been inputted. Hence, I'm trying to set up a script using the on edit triggers to protect the cell in this range after anyone has entered their name in a cell. So far I've been manually protecting the cells after a name has been entered.
I've found out that the best way to do this would be to use the on edit trigger. I have used javascript before but as I'm new to google spreadsheet scrips, I can't get my script to run like it's supposed to. The current script is supposed to automatically protect the range on edit, and add a description of when the protection was done.
Sample spreadsheet with the script in it here: https://docs.google.com/spreadsheets/d/18NlVKcaeyOkgqIa6WAuDsu5TSYK37m_vXLmp7p7Q8kc/edit?usp=sharing
function protectOnEdit(event) {
var ss = SpreadsheetApp.getActive();
var range = ss.getRange('Sheet1!A2:A1000');
var timeZone = Session.getScriptTimeZone();
var stringDate = Utilities.formatDate(new Date(), timeZone, 'dd/MM/yy HH:mm');
var description = 'Protected on ' + stringDate;
var protection = range.protect().setDescription(description);
// below code taken directly from Google's documentation
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
}
Reference: https://developers.google.com/apps-script/reference/spreadsheet/range#protect()
The data range in question is A2:A1000 and currently it -seems- to partially work, however, it protects the WHOLE range after editing a single cell, instead of just protecting the edited cell like it's supposed to.
Are there any steps I'm missing in order for the script to lock the cells individually, instead of the whole range? Any insights are very appreciated!
I have made some corrections:
function protectOnEdit(e) {
var range = e.range;
// Be sure to have edited the sheet "Sheet1"
if (range.getSheet().getName() != "Sheet1") return;
// Be sure to have a single cell as edited range
if (range.getWidth() != 1 || range.getHeight() != 1) return;
// Be sure to have edited cell inside A2:A1000
if (range.getColumn() != 1 || range.getRow() < 2) return;
// Be sure to have non-blank new value
if (!e.value) return;
// Protect this range
var timeZone = Session.getScriptTimeZone();
var stringDate = Utilities.formatDate(new Date(), timeZone, 'dd/MM/yy HH:mm');
var description = 'Protected on ' + stringDate;
var protection = range.protect().setDescription(description);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) protection.setDomainEdit(false);
}
At first the script checks several conditions for desired protection. They seem to me to be important for the task. If all of them are TRUE, then protects a single cell. The spreadsheet owner has no restrictions to edit protected cells but other editors have.
Of course, the owner should install a trigger for this function properly to automate the process.
Hoping this is a simple problem for you lot. I have no coding knowledge at all. But been using the below script in a Google Sheet to grab changing data from another sheet and log it daily, appending as it goes. Can't remember where I found the script - if I did I'd go back and ask its creator. It's been working fine; only thing is I have to manually copy paste my preferred date format every day. So I'd like the script to print the date in "dd/MM/yyyy" format (while retaining hours and minutes data inside the cell). I've been reading and searching online, and experimenting for ages but can't figure it out. This is the base code:
function recordHistory() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("History");
var source = sheet.getRange("A2:C2");
var values = source.getValues();
values[0][0] = new Date();
sheet.appendRow(values[0]);
};
I've tried placing setnumberformat in various places and nearly always get an error. Perhaps my best attempt, inspired by other examples I've seen, was to add these new lines:
function recordHistory() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("History");
var source = sheet.getRange("A2:C2");
var values = source.getValues();
values[0][0] = new Date();
sheet.appendRow(values[0]);
var cell = SpreadsheetApp.getActiveSheet().getRange(2, 1, 979);
cell.setNumberFormat("dd/MM/yyyy");
};
I hoped this would format the entire date row (Row A) after appending the new data. Probably a clunky solution even if it worked, but it didn't. It's my only attempt so far that doesn't return an error! So, yay? But it doesn't change the date format. So I give up. Any ideas?
To specify the format for a specific cell
var cell = sheet.getRange("A2");
cell.setNumberFormat("dd/MM/yyyy");
To specify the format for a range of cells
var cells = sheet.getRange("A2:C2");
cells.setNumberFormat("dd/MM/yyyy");
Please see the documentation for Range and formats.
Just in case you need the time as well, follow this code.
var cell = sheet.getRange("A2");
cell.setNumberFormat("dd/MM/yyyy h:mm:ss AM/PM");
So I'll start out by saying I just started learning Javascript 4 days ago. Now that that's out of the way, my intention with this script.
I'd like to automate the process of moving Google Form Responses, which are collected in a spreadsheet, to a new sheet within the same workbook as an archive.
I'd like this to happen on a weekly basis, and for each archive sheet that is created to have only 1 weeks responses. This should be between 12:01AM-1:00AM on Sundays, it really doesn't matter during that hour when it happens.
I would also like to then delete all of those responses from the primary collection sheet(Current_Responses), but if I have to manually delete these later it's fine (and probably good, because then I can review that the script worked properly).
I feel like I have a pretty solid start on doing this, but since I am new to all this, I would really appreciate it if a more experienced scripter could look over my code and tell me if this will work how I intend it to, and if not, where the mistakes are and how to correct them. I'm happy to make mistakes, and then learn from them so any advice will be deeply honored.
I researched several topics and scripts across three websites to help put this together. Thanks in advance for any help and advice!
// function to copy from Current_Responses to new sheet 'Archived_Responses
//(UTC Date)' placed after Current_Responses
function CreateCopySheetWeekly() {
//source info
var ss = SpreadsheetApp.getActiveSpreadsheet();
var templateSheet = ss.getSheetByName('Current_Responses');
var range = ss.getRange ('A:I'); //replace column length as needed
var data = range.getValues ();
//creates target sheet to copy responses to
var ts = 'Archived_Responses '+formatDate();
ss.insertSheet(sheetName, ss.getSheets().length, {template: templateSheet});
ts.getRange(ts.getLastRow()+1, 1, data.length, data[0].length).setValues(data);
}
//end of primary function
//function to determine and format UTC Date for CreateCopySheetWeekly function
function formatDate() {
var month, day, d = new Date();
month = ('0'+(d.getUTCMonth()+1)).slice(-2);
day = ('0'+(d.getUTCDate()).slice(-2);
return d.getUTCFullYear()+'-'+month+'-'+day;
}
//end of date function
//check every hour to determine when to perform newSheetLast function. Intended for Sunday
//between 0001-0100
window.setInterval (onSunday(){
var today = new Date();
if (today.getDay() == 0 && today.getHours() === 12) {
CreateCopySheetWeekly();
}, 600000);
Go easy on me since I am new at this, but constructive criticism never hurt anyone.
If you run this once a week we can make the simplifying assumption that you want all responses backed up once a week and then clear the main response sheet.
Let's go through the functions step by step and optimize it.
First of all you are already getting all rows, if you want all data you can just getDataRange() and not have to worry about extending.
Also we won't need the actual data.
function CreateCopySheetWeekly() {
//source info
var ss = SpreadsheetApp.getActiveSpreadsheet();
var templateSheet = ss.getSheetByName('Current_Responses'); // Current Responses
var range = ss.getDataRange();
formatDate() is just creating a ISO8601 representation of the current date if I understand correctly so you can remove the function and instead use
var ts = 'Archived_Responses '+ new Date().toISOString().slice(0,10);
Insert sheet with a template already copies all the data so you only need
ss.insertSheet(ts, ss.getSheets().length, {template: templateSheet});
Then we want to clean up our main response sheet.
If we just clear the range the form will keep appending after what would be the last row if we had never cleared because it remembers how many responses it got so we need to delete all rows but the headers.
templateSheet.deleteRows(2, range.getNumRows() - 1);
Making the final script
function CreateCopySheetWeekly() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var templateSheet = ss.getSheetByName('Current_Responses');
var range = ss.getDataRange();
var ts = 'Archived_Responses '+ new Date().toISOString().slice(0,10);
ss.insertSheet(ts, ss.getSheets().length, {template: templateSheet});
templateSheet.deleteRows(2, range.getNumRows() - 1);
}
Lastly you can schedule it by going to Resources > Current Project's Triggers and set up a time based trigger.