问题
I need help to write a script. Here's what I want to do: the script is time trigger (every day), but when it run, I want to add specific date (one date per rang(cells)). And if the date is not in the option, the script will run but do noting.
Here is the script that I have already work with the help from here:
function AddProtectionToColumn() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var range = GetRange(ss);
var protectSs = range.protect().setDescription('Protect');
var me = Session.getEffectiveUser();
protectSs.addEditor(me);
protectSs.removeEditors(protectSs.getEditors());
if (protectSs.canDomainEdit()) {
protectSs.setDomainEdit(false);
}
}
function GetRange(ss){
var today = new Date().getDate();
// assuming you're only making protected ranges on the first sheet
var protections = ss.getSheets()[0].getProtections(SpreadsheetApp.ProtectionType.RANGE);
if (at date == ('october 01, 2019')){
return ss.getRange('A1:B5');
if (at date == ('october 02, 2019')){
return ss.getRange('C1:D5');
}
}
The part of the script (protect) work well. I have trouble with the date setting thing. I try something and it didn't work. Do you have a solution for that? Also, I don't have much experience with scripting and my first language is French. Thank you!!
回答1:
Answer:
You can use the getDate() method to get the number of the current date and use a conditional similar to your current code.
Code example:
function GetRange(ss){
var today = new Date().getDate();
var protections = ss.getSheets()[0].getProtections(SpreadsheetApp.ProtectionType.RANGE);
if (today == 1){
return ss.getRange("day-1-range");
}
else if (today == 2){
return ss.getRange("day-2-range");
}
else if (today == 3){
return ss.getRange("day-3-range");
}
// else block continues...
else if (today == 31){
return ss.getRange("day-31-range");
}
}
Honestly, I don't really recommend this as you're going to have a very large if block, but for your use case this will work.
Explanation:
The getDate() method returns a number, which is equal to the numerical date of the day of the date object.
For example:
var date1 = new Date('01 October 2019').getDate(); // == 1
var date2 = new Date('21/12/1984').getDate(); // == 21
var date3 = new Date('Jan 14 2000').getDate(); // == 14
var date4 = new Date('29 February 2004').getDate(); // == 29
来源:https://stackoverflow.com/questions/58186992/google-script-run-at-specific-date-more-than-one-date