Automatically protect a cell / range after inputting data in Google Sheets - javascript

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.

Related

Extract month and year from Date and display as MMM-YY

I am new to google apps script, I am having a hard time with date format conversion
my source column has data in the format "mm/dd/yyyy". I would like to change this to "MMM-YY" i.e. I just need to extract Month and year.
Below is my unsuccessful attempt
// Get all values in column A on sheet titled "Transactions"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourcesheet = ss.getSheetByName("Transactions");
var targetsheet = ss.getSheetByName("stage");
// get source range
var source = sourcesheet.getRange("A:J");
//get the data and place in array
var alldata = sourcesheet.getRange("A:I").getValues();
Logger.log(alldata.length) ;
//********************************************************************************//
// loop through date column and change format
for(var i=1; i<alldata.length; i++)
{
alldata[i][0]= new Date(alldata[i][0]);
var Mnth = alldata[i][0].getMonth() ;
var Year = alldata[i][0].getYear() ;
var Day = alldata[i][0].getDay() ;
var Day2 = new Date(Year,Mnth,Day);
alldata[i][10] = Utilities.formatDate(Day2, Session.getScriptTimeZone(), "MMM-YY");
}
//********************************************************************************//
// get destination range
var destination = targetsheet.getRange(2, 1, alldata.length, 11);
// clear contents of destination sheet
destination.clear();
// copy values to destination range
destination.setValues(alldata);
}
Example
Source column value = "01/06/2019" value written to output column "1/19/2019" but it displays as "Jan-19"
Replace
alldata[i][10] = Utilities.formatDate(Day2, Session.getScriptTimeZone(), "MMM-YY");
by
alldata[i][10] = "'" + Utilities.formatDate(Day2, ss.getSpreadsheetTimeZone(), "MMM-yy");
Explanation
Prepend an apostrophe to prevent that Google Sheets from interpreting the values of the form MMM-YY as MMM-dd
Replace YY by yy
Replace Session.getScriptTimeZone() by ss.getSpreadsheetTimeZone()
NOTES
YY means weak year that could lead to some errors in certain dates of the year. To prevent this, instead use yy.
Some letters used for date format in Google Sheets and in Google Apps Script could mean different things. See the references to use them properly.
The script time zone and the spreadsheet time zone could be different. Since you will passing the values to the spreadsheet, it's better to use its time zone instead of the one from the script.
The solution to get the dates displayed as MMM-yy as date values instead of text (string) values, doesn't require to use Google Apps Script, instead use the Google Sheets number format feature (click on Format > Number > More Formats > More date and time formats), well you could use Google Apps Script to set the number format by using setNumberFormat(numberFormat)
References
Date and Number Formats
In Google Sheets
https://developers.google.com/sheets/api/guides/formats
In Utilities.formatDate(date,timezone,format)
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
This works with the format as MMM-yy
function myFunction1() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var ssh=ss.getSheetByName("Transactions");
var tsh=ss.getSheetByName("stage");
var srg=ssh.getRange(1,1,ssh.getLastRow(),11);
var data=srg.getValues();
data.forEach(function(r,i){r[10]=Utilities.formatDate(new Date(data[i][0]),Session.getScriptTimeZone(), "MMM-yy");});
var destination=tsh.getRange(1,1,data.length,11);
destination.clear();
destination.setValues(data);
}
reference
You just copy date values to the target sheet without any changes whatsoever and the apply custom number format to the target range.
var datesRange = sheet.getRange("A1:A");
var values = datesRange.getValues();
var destination = targetSheet.getRange("A1:A");
destination.setValues(values).setNumberFormat("mmm-yy");
As Ruben pointed out, you can simply change the number format in UI (no need for scripting) so his solution is probably the best one.

Javascript in Google Sheets script: help using setNumberFormat

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

Google Script to copy and archive Form Responses in New Sheet on Weekly Basis

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.

How to move a row from one google spreadsheet to another based on a value in a cell?

My script is supposed to move a row from one google spreadsheet to another based on a value in a cell. It fails to do so, and I think it's because of the onEdit() function but can't figure it out. I found a solution for different sheets in the same spreadsheet but not in different spreadsheets. My code is below.
function onEdit(e) {
var sss = SpreadsheetApp.getActiveSpreadsheet();
var ss = e.source.getActiveSheet();
var r = e.source.getActiveRange();
if(s.getName() == "source_sheet" && r.getColumn() == 7 && r.getValue() == "Pavlovo"){
//Get full range of data
var SRange = ss.getRange(1, 3, 1, 5);
//get A1 notation identifying the range
var A1Range = SRange.getA1Notation();
//get the data values in range
var SData = SRange.getValues();
// tss = target spreadsheet
var tss = SpreadsheetApp.openById('1_t7BDCWgHJDip_cndzVashxLDQ_pVS6obi3I9TB_EJI');
var ts = tss.getSheetByName('Vitosha'); // ts = target sheet
//set the target range to the values of the source data
ts.getRange(A1Range).setValues(SData);
}
}
You are using a simple trigger onEdit. Such triggers run without authorization and therefore are subject to several restrictions, such as:
They can modify the file they are bound to, but cannot access other files because that would require authorization.
This is why SpreadsheetApp.openById fails to execute in your code.
Solution: rename the function to something other than onEdit, and add an installable trigger running on edits. An installable trigger runs as you (i.e., the user who created it), and therefore can access any files that you can access.

Clear cell value of adjacent cell if value is a date

I've been working on this script in Google Apps Script for a little while now and think I've got it almost figured out. I could really use another pair of eyes though, as it hasn't yet worked to completion.
What I'm trying to do:
I'm working on a sheet dealing with tentative and actual dates. These two dates are in adjacent columns. Once the "actual" date gets filled into its cell, I would like the "tentative" date to be deleted.
Here is my script thus far:
function onEdit() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange('F4:F');
var range2 = sheet.getRange('E4:E');
var rule = range.getDataValidation();
if (rule != null) {
var criteria = rule.getCriteriaType();
var args = rule.getCriteriaValues();
var clear = range2.clear({validationsOnly: false});
}
}
What do I need to do to get this script running?
It appears you want to delete the value in column E if column F was filled. If so, I don't see the need for dealing with data validation rules. The following script checks that the edited cell is in column F, row >= 4, and that the new value in the cell is a date. If these conditions hold, it clears the cell to the left (using offset).
function onEdit(e) {
if (e.range.getColumn() == 6 && e.range.getRow() >= 4) {
if (e.range.getValue() instanceof Date) {
e.range.offset(0, -1).clear();
}
}
}
Note: this script uses the event object passed to onEdit function. Interestingly, its "value" property turned out to be not useful here, because it is not a date object even when a user enters a date. This is what I use e.range.getValue() instead.

Categories