Trying to delete rows in a spreadsheet based on the date - google-apps-script

I'm trying to loop through the rows of my sheet to delete certain rows based on the date found in column F. I have an syntax error showing up on line 28. I'm not sure what's triggering this as the code looks fine to me. Any advice would be appreciated.
function dateReduce() {
var ss = SpreadsheetApp.openById('1yl599Ff7d1aaSTKpHAeHW5wswiDOzNegrKxS1Z1SquY');
var sheet = ss.getSheetByName("worksheet");
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1;
var yyyy = today.getFullYear();
var range = sheet.getRange(2, 6, 1374);
var values = range.getValues(); // getValues() results in a javascript array as opposed to a google script array
var numRows = range.getNumRows();
var endDate;
for (var i = 1; i <= numRows; i++) {
endDate = new Date(values[i][5]);
if (yyyy > endDate.getFullYear()) {
sheet.deleteRow(i);
};
else if (yyyy === endDate.getFullYear()) {
if ( mm > (endDate.getMonth()+1)) {
sheet.deleteRow(i);
};
};
else if ((mm === endDate.getMonth()+1) && (yyyy == endDate.getFullYear())) {
if (dd > endDate.getDate()) {
sheet.deleteRow(i);
};
};
};
};

You need to remove the semicolons after all of the ending curly braces ("}"). You don't need to put semicolons after curly braces unless there is an assignment operation involved.
function dateReduce() {
var ss = SpreadsheetApp.openById('1yl599Ff7d1aaSTKpHAeHW5wswiDOzNegrKxS1Z1SquY');
var sheet = ss.getSheetByName("worksheet");
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1;
var yyyy = today.getFullYear();
var range = sheet.getRange(2, 6, 1374);
var values = range.getValues(); // getValues() results in a javascript array as opposed to a google script array
var numRows = range.getNumRows();
var endDate;
for (var i = 1; i <= numRows; i++) {
endDate = new Date(values[i][5]);
if (yyyy > endDate.getFullYear()) {
sheet.deleteRow(i);
} else if (yyyy === endDate.getFullYear()) {
if (mm > (endDate.getMonth() + 1)) {
sheet.deleteRow(i);
}
} else if ((mm === endDate.getMonth() + 1) && (yyyy == endDate.getFullYear())) {
if (dd > endDate.getDate()) {
sheet.deleteRow(i);
}
}
}
}

Related

Is it possible to copy range with formating using apps scripts?

dears
I need your support to edit this function as I need to copy data with formatting
This is the equation I working on
function copyRows()
{
var copySheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('sheet1');
var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('sheet2');
var dataRange = dataSheet.getDataRange();
var dataValues = dataRange.getValues();
for(var i = 1; i < dataValues.length; i++)
{
if(dataValues[i][29] === 'done')
{
copySheet.appendRow([dataValues[i][0],
dataValues[i][1],
dataValues[i][2],
dataValues[i][3],
dataValues[i][4]]);
}
}
for(var i = 1; i < dataValues.length; i++)
{
if(dataValues[i][29] === 'done')
{
var clearRow = i+1;
dataSheet.getRange('A' + clearRow + ':AC' + clearRow).clear();
}

Google Apps Script to protect range based on dates

im trying to make a google script to protect a range in google sheets based on dates
I want to protect all the rows that its date is 14 days before today
this is the code I have so far,
function ProtectEntradas() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
const sheetEntradas = ss.getSheetByName('Entradas')
var dateRange = sheetEntradas.getRange(3, 1, sheetEntradas.getLastRow() - 2, 1);
var val = dateRange.getDisplayValues();
var date = new Date();
var protectDateRaw = new Date(date.getFullYear(), date.getMonth(), date.getDate() - 14);
var protectDate = Utilities.formatDate(protectDateRaw, Session.getScriptTimeZone(), "dd-MMM-YY");
var protectRow;
//check if date is less than the current date
for (var i = 0; i < val.length; i++) {
if (val[i][0] >= protectDate) {
protectRow = i;
break;
}
}
var protection = sheetEntradas.getProtections(SpreadsheetApp.ProtectionType.RANGE);
//If protection exists, update else add new one.
if (protection.length > 0) {
var range = sheetEntradas.getRange(3, 1, protectRow, 10);
protection[0].setRange(range);
}
else {
sheetEntradas.getRange(3, 1, protectRow, 10).protect();
}
it is doing some protection, but not the range im expecting
what im I doing wrong ?
then I want to make a trigger to run every day so it will be protecting the range dinamically
Thanks in advance
Try this to compare correctly dates (3 lignes of code has been modified)
function ProtectEntradas() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
const sheetEntradas = ss.getSheetByName('Entradas')
var dateRange = sheetEntradas.getRange(3, 1, sheetEntradas.getLastRow() - 2, 1);
// #### modification on how to fetch dates
var val = dateRange.getValues().map(d => Utilities.formatDate(d[0], Session.getScriptTimeZone(), "yyyy-MM-dd"))
var date = new Date();
var protectDateRaw = new Date(date.getFullYear(), date.getMonth(), date.getDate() - 14);
// #### modification of the format
var protectDate = Utilities.formatDate(protectDateRaw, Session.getScriptTimeZone(), "yyyy-MM-dd");
var protectRow;
//check if date is less than the current date
for (var i = 0; i < val.length; i++) {
// #### modification
if (val[i] >= protectDate) {
protectRow = i;
break;
}
}
var protection = sheetEntradas.getProtections(SpreadsheetApp.ProtectionType.RANGE);
//If protection exists, update else add new one.
if (protection.length > 0) {
var range = sheetEntradas.getRange(3, 1, protectRow, 10);
protection[0].setRange(range);
}
else {
sheetEntradas.getRange(3, 1, protectRow, 10).protect();
}
}
edit : if you want to add another criterion, you will have to protect each row (or group of rows) individually
function ProtectEntradas() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
const sheetEntradas = ss.getSheetByName('Entradas')
// dates
var dateRange = sheetEntradas.getRange(3, 1, sheetEntradas.getLastRow() - 2, 1); // column A
var val = dateRange.getValues().map(d => Utilities.formatDate(d[0], Session.getScriptTimeZone(), "yyyy-MM-dd"))
var date = new Date();
var protectDateRaw = new Date(date.getFullYear(), date.getMonth(), date.getDate() - 14);
var protectDate = Utilities.formatDate(protectDateRaw, Session.getScriptTimeZone(), "yyyy-MM-dd");
// other criteria
var crit = sheetEntradas.getRange(3, 17, sheetEntradas.getLastRow() - 2, 1).getValues().flat(); // column Q
// remove protections
sheetEntradas.getProtections(SpreadsheetApp.ProtectionType.RANGE)
.forEach(protection => {
if (protection && protection.canEdit()) {
protection.remove();
}
});
for (var i = 0; i < val.length; i++) {
if (val[i] <= protectDate && crit[i] != '') {
sheetEntradas.getRange(3 + i, 1, 1, 10).protect();
}
}
}

Set Value of checkbox

I want to uncheck a checkbox if an adjacent cell has a value input in it.
function onEdit(event) {
var eventRange = event.range;
if (eventRange.getColumn() == 3) { // 3 == column C
var columnFRange = SpreadsheetApp.getActiveSheet().getRange(eventRange.getRow(), 6, eventRange.getNumRows(), 6);
var values = columnFRange.getValues();
for (var i = 0; i < values.length; i++) {
values[i][0] = 'FALSE';
}
columnFRange.setValues(values);
}
}
This looks at a sheet called "Testing" and if there is a value in column A it will put "TRUE" in the adjacent cell to the right. I believe this is what you're going for?
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Testing");
var hasValue = sheet.getRange("A:A").getValues();
var value = '';
for(var i = 0; i < hasValue.length; i++){
if(hasValue[i][0].length > 0) {
sheet.getRange("B" + (i + 1)).setValue("TRUE");
}
else {
sheet.getRange("B" + (i + 1)).setValue("");
}
}
}

How do I get my google spreadsheet to open to today's date?

Here is a link to my document:
https://docs.google.com/spreadsheets/d/1wBpeCUTmePD3N5CDz57LeBBWZHnSwrX-5b6XscdbB4s/edit?usp=sharing
I want the document to open to today's date or to the Monday of each week.
Please help.
Thanks in advance.
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getRange("A:A");
var values = range.getValues();
var day = 24*3600*1000;
var today = parseInt((new Date().setHours(0,0,0,0))/day);
var ssdate;
for (var i=0; i<values.length; i++) {
try {
ssdate = values[i][0].getTime()/day;
} catch(e) { }
if (ssdate && Math.floor(ssdate) == today) {
sheet.setActiveRange(range.offset(i,0,1,1));
break;
}
}
}
The main issue in your attempt is that you grabbed column A, but your dates exist in row 2. Try this:
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("2018"); // Specifiy the sheet
var range = sheet.getRange("2:2"); // Row 2
var values = range.getValues()[0]; // This is a 2-dimensional array in the form [[row1-col1, row1-col2],[row2-col1,row2-col2]].
// Because we only pulled one row (Row 2), we can immediately select just that row by appending the [0]
var today = new Date();
var todayDate = today.getDate();
var todayMonth = today.getMonth();
var todayYear = today.getFullYear();
for (var i=0; i<values.length; i++) {
var columnDate = new Date(values[i]);
if (columnDate.getDate() === todayDate && columnDate.getMonth() === todayMonth && columnDate.getFullYear() === todayYear) {
sheet.getRange(1, i+1).activate();
break;
}
}
}

Google App Script to find a date across multiple Sheets

I have a Spreadsheet with many sheets inside it, Each sheet represents one month, and has dates in column B. I'm trying to create a function that searches for the current date and inserts the current time in column C. I've got a function to work by specifying the sheet, but I want it to find the sheets itself.
I've got the following code:
function insertTime() {
var date = new Date();
var hours = date.getHours()
var minutes = date.getMinutes()
var timeStamp = hours + ':' + minutes
var ss = SpreadsheetApp.getActiveSpreadsheet()//// get the sheet
var sheets = ss.getSheets();// get all the sheets
var today = new Date(); //get todays date
for (var sheetNum = 1; sheetNum < sheets.length; sheetNum++){
var sheet = ss.getSheets()[sheetNum]
var columnB = sheet.getRange(2, 2, sheet.getLastRow()-1, 1); // get all the rows
var bValues = columnB.getValues(); // get the values
for (var i = 0; i < bValues.length; i++) { // repeat loop
var fDate = new Date(bValues[i][0]);
if (fDate.getDate() == today.getDate() &&
fDate.getMonth() == today.getMonth() &&
fDate.getFullYear() == today.getFullYear()) { // if the date in the cell is today's date...
sheet.getRange(i + 2, 3, 1, 1).setValue(timeStamp);
}
}
}
}
Which is giving me the following error: "The coordinates or dimensions of the range are invalid. (line 16)"
At least one of your sheets is empty or has only 1 row of data.
In this case on line 16, sheet.getLastRow()-1 will be 0 or -1 which is creating the error.
I figured it out in the end, I used the forEach function:
function myFunction(){
var date = new Date();
var hours = date.getHours()
var minutes = date.getMinutes()
var timeStamp = hours + ':' + minutes
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheets = ss.getSheets();
sheets.forEach (function (sheet) {
var columnB = sheet.getRange(2, 2, 70, 1);
var bValues = columnB.getValues();
var today = new Date();
for (var i = 0; i < bValues.length; i++) {
var fDate = new Date(bValues[i][0]);
if (fDate.getDate() == today.getDate() &&
fDate.getMonth() == today.getMonth() &&
fDate.getFullYear() == today.getFullYear()) {
sheet.getRange(i + 2, 7, 1, 1).setValue(timeStamp);
}
}
}