Google Spreadsheet Script - google-apps-script

I am working in a google document spreadsheet to make a list of active customers. I am attempting to create a script that when a completion date is entered, that row (all the customer info) is transfered to another sheet and/or deleted. I started a script but it isn't working properly.
function myFunction() {
'var ssdate = spreadsheet.column B'
// the "if" clause : if (date = 1) {
// the "then" clause : then ( move row to sheet 2)
}
Since this is my first time, I am sure this needs some work, but any help would be greatly appreciated.

It's much easier to read the Google Apps Script tutorials and guide first. They will give you a much better quick start.

Please try the following example:
var ddate = Utilities.formatDate(new Date(), "GMT", "MM-dd-yy");
function checkDate(){
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var rows = sheet.getDataRange();
var rowsNumber = rows.getNumRows();
var column = sheet.getDataRange();
var values = column.getValues();
for (var i = 1; i <= rowsNumber -1; i++){
var customerData = values[i];
var customerDate = customerData[2];
var myRow = Math.round(i) +1;
var conCustomerDate = Utilities.formatDate(new Date(customerDate), "GMT", "MM-dd-yy");
if (conCustomerDate > ddate){
sheet.getRange("D" + myRow).setValue("OK");
}
else {
sheet.getRange("D" + myRow).setValue("Old");
}
}
}

Related

Add events from Google sheets to google calendar

I am trying to write scirpt to add events from a spreadsheet to my google calendar. This is the script that I am using.
function addEvents() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = ss.getLastRow();
var cal = CalendarApp.getCalendarById("c_fe882662e583725f15fd4faa8c8fdf5124f3affe543778ecdcf0838d6eb17f26#group.calendar.google.com")
var data = ss.getRange("A3:D"+lr).getValues();
for(var i = 0;i<data.length;i++){
cal.createEvent(data[i][2],data[i][4],data[i][5],{location: data[i][6], description: data[i][7]});
}
}
When I run the script I am getting the following error. Error Exception: Invalid argument: startTime addEvents # Code.gs:10
This is the sheet that I am using with my dates.
https://docs.google.com/spreadsheets/d/1qG68-NLnq9LscPPzlnzRLCfHFIsN3v7V5zvWiVsG0qU/edit?usp=sharing
I want the title of the event to be column C, the start time to be Column E, the endtime to be Column F, Location G, and Description H.
Modification points:
In your script, in the for loop, data[i][4],data[i][5] is used as the start and end time. And also, data[i][7] is used. But, atvar data = ss.getRange("A3:D"+lr).getValues();, 4 columns of "A" to "D" are retrieved. I thought that this might be the reason for your issue. In this case, it is required to be var data = ss.getRange("A3:H" + lr).getValues().
But, when I saw your Spreadsheet, the start and end times don't have the year and month. In this case, 1899 year is used. Please be careful about this. From your Spreadsheet, I guessed that you might have wanted to use the year, month, and date from column "A".
When my understanding of your current issue and your goal, how about the following modification?
Modified script:
function addEvents() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = ss.getLastRow();
var cal = CalendarApp.getCalendarById("c_fe882662e583725f15fd4faa8c8fdf5124f3affe543778ecdcf0838d6eb17f26#group.calendar.google.com");
var data = ss.getRange("A3:I" + lr).getValues();
while (data[data.length - 1][0] == '') data.pop();
for (var i = 0; i < data.length; i++) {
var year = data[i][8].getFullYear();
var month = data[i][8].getMonth();
var date = data[i][8].getDate();
data[i][4].setFullYear(year);
data[i][4].setMonth(month);
data[i][4].setDate(date);
data[i][5].setFullYear(year);
data[i][5].setMonth(month);
data[i][5].setDate(date);
cal.createEvent(data[i][2], data[i][4], data[i][5], { location: data[i][6], description: data[i][7] });
}
}
When this script is run, the start and end times are retrieved from the columns "E" and "F", respectively. And also, the year, month, and date are retrieved from column "A". Using these values, the start and end date are created and they are used with createEvent.
When you want to use other values of year, month, and date instead of column "A", please tell me.
Note:
From your reply of This sounds promising, the sheet that I am using is actually setting up a mail merge as well and the date in column A is for the mail merge and not for the calendar. I would actually like column I to be the date for the calendar events. , I modified the above script.
From your reply of If I run this script twice (or multiple times) as I will continue to add events, it seems to duplicate the events that are already added. Any idea how to eliminate that?, I updated the above script as follows.
function addEvents() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var lr = ss.getLastRow();
var cal = CalendarApp.getCalendarById("c_fe882662e583725f15fd4faa8c8fdf5124f3affe543778ecdcf0838d6eb17f26#group.calendar.google.com");
var data = ss.getRange("A3:R" + lr).getValues();
while (data[data.length - 1][0] == '') data.pop();
var rangeList = [];
for (var i = 0; i < data.length; i++) {
if (data[i][17] == "created") continue;
var year = data[i][8].getFullYear();
var month = data[i][8].getMonth();
var date = data[i][8].getDate();
data[i][4].setFullYear(year);
data[i][4].setMonth(month);
data[i][4].setDate(date);
data[i][5].setFullYear(year);
data[i][5].setMonth(month);
data[i][5].setDate(date);
cal.createEvent(data[i][2], data[i][4], data[i][5], { location: data[i][6], description: data[i][7] });
rangeList.push(`R${i + 3}`);
}
if (rangeList.length == 0) return;
ss.getRangeList(rangeList).setValue("created");
}
Try changing this: cal.createEvent(data[i][2],data[i][4],data[i][5],{location: data[i][6], description: data[i][7]}); to this cal.createEvent(data[i][2],new Date(data[i][4]),new Date(data[i][5]),{location: data[i][6], description: data[i][7]});
Try changing this var data = ss.getRange("A3:D"+lr).getValues(); to this var data = ss.getRange("A3:H"+lr).getValues();
Try this:
function addEvents() {
const ss = SpreadsheetApp.getActive();
var sh = ss.getActiveSheet();
var cal = CalendarApp.getCalendarById("jimesteban#jimesteban.com")
var data = sh.getRange("A3:H" + sh.getLastRow()).getValues();
for (var i = 0; i < data.length; i++) {
cal.createEvent(data[i][2], data[i][4], data[i][5], { location: data[i][6], description: data[i][7] });
}
}

Taking user input to Google Sheets using Apps Script and process with queries

I created a spreadsheet for reporting students attendance that contains 8 sheets (each sheet named as a subject code). After completing a particular class, I go to the specific sheet (subject) and select all the rows of that particular date and press the button AfterClass-->Process Data (sorting, removing duplicates and protecting) using Google Apps Script/Macros. All working fine.
Now I created a DASHBOARD and I want that a teacher can do everything from the dashboard rather than going to individual sheet (subject). S/he can give two inputs - subject (sheetname) and Date from the Dashboard and then automatically process these specific dataset of that Sheet (Not all data of the sheet). Please note that date is in Column A and subject-code in Column F. The code I wrote as follows:
function AfterClass() {
var spreadsheet = SpreadsheetApp.getActive();
//Sorting and removing duplicates
var height = spreadsheet.getActiveSheet().getActiveRange().getHeight();
spreadsheet.getCurrentCell().offset(0, 0, height, 6).activate()
.sort({column: spreadsheet.getActiveRange().getColumn() + 2, ascending: true});
spreadsheet.getActiveRange().removeDuplicates([spreadsheet.getActiveRange().getColumn() + 2]).activate();
//Protecting data finally
//var lastRow = spreadsheet.getLastRow();
var timeZone = Session.getScriptTimeZone();
var stringDate = Utilities.formatDate(new Date(), timeZone, 'dd/MM/yy HH:mm');
var me = Session.getEffectiveUser();
var description = 'Protected on ' + stringDate + ' by ' + me;
var protection = SpreadsheetApp.getActiveSheet().getActiveRange().protect().setDescription(description);
//protection.setDomainEdit(false);
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
//Removing blank spacess in between data
var sheet = SpreadsheetApp.getActiveSheet();
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var rowsDeleted = 0;
for (var i = 0; i <= numRows - 1; i++) {
var row = values[i];
if (row[1] == '') {
sheet.deleteRow((parseInt(i)+1) - rowsDeleted);
rowsDeleted++;
}
}
//For Double periods in a class
//var ss = SpreadsheetApp.getActiveSpreadsheet()
//var database = SpreadsheetApp.openById("xxx");
//var source = ss.getSheetByName('yyy');
var dataToCopyRng = SpreadsheetApp.getActiveSheet().getActiveRange(); //Gets range object of all data on source sheet
var dataToCopy = dataToCopyRng.getValues(); //Gets the values of the source range in a 2 dimensional array
var copyToSheet = SpreadsheetApp.getActiveSheet();
var copyData = copyToSheet.getRange(copyToSheet.getLastRow()+1,1,dataToCopy.length,dataToCopy[0].length).setValues(dataToCopy);
//Calculate class attendance and signed
var height2 = spreadsheet.getActiveSheet().getActiveRange().getHeight();
SpreadsheetApp.getActiveSheet().getCurrentCell().offset(2*height2,1).activate();
SpreadsheetApp.getActiveSheet().getCurrentCell().setRichTextValue(SpreadsheetApp.newRichTextValue()
.setText(height2 + ' Students, SIGNED')
.setTextStyle(0, 12, SpreadsheetApp.newTextStyle()
.setBold(true)
.build())
.build());
spreadsheet.getCurrentCell().offset(0, -1, 1, 6).activate();
spreadsheet.getActiveRangeList().setBackground('#e6b8af');
//.setBackground('#d9d9d9')
}
[dashboard][1]
[1]: https://i.stack.imgur.com/cMtHC.png
How to run your script from Dashboard after selecting the specified sheet and time
Modify your function in a way that it takes input from the cells A2 and C2 and D2 from Dashboard
Replace all instances of getActiveSheet() through getSheetByName(name), whereby name is your input from A1
Replace all instances of getActiveRange() through sheet.getRange(), whereby you define the range as as subrange as defined by the dates you retrieved
In order to find the first occurrence of the start date and the last occurrence of the end date - use the methods indexOf() and lastIndexOf()
Make sure that your date notation in Dashboard is the same as in the sheets for correct functionality
Sample:
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('After Class')
.addItem('Process Data', 'AfterClass')
.addToUi();
}
function AfterClass() {
var spreadsheet = SpreadsheetApp.getActive();
var dashboard = spreadsheet.getSheetByName("Dashboard");
var sheetName = dashboard.getRange("A2").getValue();
//retrieve the start date to use as desired
var startDate = dashboard.getRange("C2").getDisplayValue();
var endDate = dashboard.getRange("D2").getDisplayValue();
var sheet = spreadsheet.getSheetByName(sheetName);
//chose the range within the specified dates, for this first locate the date column
var startRow = 2;
var dateColumn = sheet.getRange(startRow,1,sheet.getLastRow(), 1);
var dates = dateColumn.getDisplayValues().flat();
var firstRow = dates.indexOf(startDate)+startRow;
var lastRow = dates.lastIndexOf(endDate)+startRow;
//now get the range between (and including) those rows
var range = sheet.getRange(firstRow, 1, lastRow-firstRow+1, sheet.getLastColumn());
//Sorting and removing duplicates
// You need to specify by which column you want to sort your data, in this sample it it column 3 - that it column C
var column = 3;
range.sort({column: column, ascending:true});
range.removeDuplicates([column]);
//now delete empty rows if any
for (var i = range.getHeight(); i >= 1; i--){
if(range.getCell(i, 1).isBlank()){
sheet.deleteRow(range.getCell(i, 1).getRow());
}
}
//Protecting data
var timeZone = Session.getScriptTimeZone();
var stringDate = Utilities.formatDate(new Date(), timeZone, 'dd/MM/yy HH:mm');
var me = Session.getEffectiveUser();
var description = 'Protected on ' + stringDate + ' by ' + me;
var protection = range.protect().setDescription(description)
//protection.setDomainEdit(false);
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
protection.setDomainEdit(false);
}
}
Important
The sample above will work if your sheet is sorted by dates (ascending) - as you specified in the comments. However, once the data is sorted by column C and not dates anymore it might not work as intended.
Sidenote:
From your code I understand that you recorded it as a macro rather than writing it from scratch (visible by the (unnecessary) calls of activate()).
I very much recommend you to take some time to study Apps Script in roder to understand your code in depth and be able to perform modificaitons and adjustments according to your needs.
There is the basic tutorial for Apps Script in general, samples and explanations for Google Sheets in specific and the references for all available Apps Script methods, whereby most methods feature a code sample.

Google Sheets - Script to move rows to different tab depending on a key word

I have been working on a google sheet that that receives a form submission.
Once the submission comes in I need a script to move the rows of data to different tabs depending on the name shown in column C.
I have extensively searched for solutions on stack overflow and I am very close to a solution right now through the code I have found and edited.
I have a script that will move historic dates to a different tab and leave all future dates in the original tab based in the logic of the date being older than today.
All I need to do now is modify this to move the rows with the name "John" in column C to the John tab and ignore the date.
Once I can get one name to work I am confident I can make this work for multiple names and multiple tabs.
Please feel free to create a copy of the following test sheet I have been working on.
link:
https://docs.google.com/spreadsheets/d/1zJpylrD_5hzScW3lIjIQQSKiY0Aan6Wkm_h_IbVrVXM/edit#gid=0
function MovePastDates() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var entrySheet = ss.getSheetByName("Entry Sheet");
var franksSheet = ss.getSheetByName("Franks Sheet");
var lastColumn = entrySheet.getLastColumn();
for(var i = entrySheet.getLastRow(); i > 0; i--){
var dateCell = entrySheet.getRange(i, 1).getValue();
var today = new Date();
var test = new Date(dateCell);
// If the value is a valid date and is a past date, we remove it from the sheet to paste on the other sheet
if(test < today){
var rangeToMove = entrySheet.getRange(i, 1, 1, entrySheet.getLastColumn()).getValues();
franksSheet.getRange(franksSheet.getLastRow() + 1, 1, 1, entrySheet.getLastColumn()).setValues(rangeToMove);
entrySheet.deleteRow(i);
}
}
}
The final result should be a google sheet that receives form entries.
Each entry will be allocated to a specific person who will only have edit permissions to there own tab only where they can approve/decline requests submitted through the form.
All other users of the sheet will have view only access.
I wanted two scripts:
1) Script to move form submission rows to a specific tab dependent on person’s name
(I was going to set up a trigger every minute for this)
2) Script to move past dates into an historic sheet
(I was going to set up a trigger every night for this)
I have been able to modify your code to achieve the desired function, it may not be the most efficient but it appears to work well.
Script One is:
function moveRowsToNamesSheets() { //Name of function
var sObj={John:'Johns Sheet',Frank:'Franks Sheet',David:'Davids Sheet'}; // Put key work and sheet name here in format eg.( keyWord1: 'sheet name to move keyWord1 to')
var ss=SpreadsheetApp.getActive(); // ??
var esh=ss.getSheetByName('Entry Sheet'); //Sheet data is being pulled form
var fsh=ss.getSheetByName('Franks Sheet'); //unsure why one of the sheets is named here
var erg=esh.getDataRange(); // Not sure of function now that I am not using dates
var evA=erg.getValues(); // ??
var d=0; //??
//var today=new Date(new Date().getFullYear(),new Date().getMonth(),new Date().getDate()).valueOf(); // Didnt need this line
for(var i=1;i<evA.length;i++) { //??
if(/*new Date(evA[i][0]).valueOf() < today*/ evA[i][2]=='John' ||evA[i][2]=='Frank' ||evA[i][2]=='David') { //Keywords used go here, what does the [2] mean?
ss.getSheetByName(sObj[evA[i][2]]).appendRow(evA[i]); //??
esh.deleteRow(i+1-d);
d++; //increments d by one
}
}
}
Script Two is:
function HistoricDates() {
// Initialising
var ss = SpreadsheetApp.getActiveSpreadsheet();
//--------------- Franks Sheets --------------------
var franksSheet = ss.getSheetByName("Franks Sheet");
var PastSheet = ss.getSheetByName("Historic Requests");
var lastColumn = franksSheet.getLastColumn();
// Check all values from your "Franks Sheet" sheet
for(var i = franksSheet.getLastRow(); i > 0; i--){
// Check if the value is a valid date
var dateCell = franksSheet.getRange(i, 4).getValue(); //Dates in column 4
if(isValidDate(dateCell)){
var today = new Date();
var test = new Date(dateCell);
// If the value is a valid date and is a past date, we remove it from the sheet to paste on the other sheet
if(test < today){
var rangeToMove = franksSheet.getRange(i, 1, 1, franksSheet.getLastColumn()).getValues();
PastSheet.getRange(PastSheet.getLastRow() + 1, 1, 1, franksSheet.getLastColumn()).setValues(rangeToMove);
franksSheet.deleteRow(i);
}
}
}
//---------------------- Johns Sheets -------------------------
var johnsSheet = ss.getSheetByName("Johns Sheet");
var pastSheet = ss.getSheetByName("Historic Requests");
var lastColumn = johnsSheet.getLastColumn();
// Check all values from your "Johns Sheet" sheet
for(var i = johnsSheet.getLastRow(); i > 0; i--){
// Check if the value is a valid date
var dateCell = johnsSheet.getRange(i, 4).getValue(); //Dates in column 4
if(isValidDate(dateCell)){
var today = new Date();
var test = new Date(dateCell);
// If the value is a valid date and is a past date, we remove it from the sheet to paste on the other sheet
if(test < today){
var rangeToMove = johnsSheet.getRange(i, 1, 1, johnsSheet.getLastColumn()).getValues();
pastSheet.getRange(pastSheet.getLastRow() + 1, 1, 1, johnsSheet.getLastColumn()).setValues(rangeToMove);
johnsSheet.deleteRow(i);
}
}
}
//--------------- Davids Sheets --------------------
var davidsSheet = ss.getSheetByName("Davids Sheet");
var pastSheet = ss.getSheetByName("Historic Requests");
var lastColumn = davidsSheet.getLastColumn();
// Check all values from your "Davids Sheet" sheet
for(var i = davidsSheet.getLastRow(); i > 0; i--){
// Check if the value is a valid date
var dateCell = davidsSheet.getRange(i, 4).getValue();//Dates in column 4
if(isValidDate(dateCell)){
var today = new Date();
var test = new Date(dateCell);
// If the value is a valid date and is a past date, we remove it from the sheet to paste on the other sheet
if(test < today){
var rangeToMove = davidsSheet.getRange(i, 1, 1, davidsSheet.getLastColumn()).getValues();
pastSheet.getRange(pastSheet.getLastRow() + 1, 1, 1, davidsSheet.getLastColumn()).setValues(rangeToMove);
davidsSheet.deleteRow(i);
}
}
}
}
// Check is a valid date
function isValidDate(value) {
var dateWrapper = new Date(value);
return !isNaN(dateWrapper.getDate());
}
The working spreadsheet is located here:
https://docs.google.com/spreadsheets/d/1VCONRkBpkva-KrFDO2bFV8ZTp1U168QWAGavcKCa_uQ/edit?usp=sharing
I think this is what you want:
function movePastDatesOrJohn() {
var sObj={John:'Johns Sheet',Frank:'Franks Sheet',David:'Davids Sheet'};
var ss=SpreadsheetApp.getActive();
var esh=ss.getSheetByName('Entry Sheet');
var fsh=ss.getSheetByName('Franks Sheet');
var erg=esh.getDataRange();
var evA=erg.getValues();
var d=0;
var today=new Date(new Date().getFullYear(),new Date().getMonth(),new Date().getDate()).valueOf();
for(var i=1;i<evA.length;i++) {
if(new Date(evA[i][0]).valueOf() < today || evA[i][2]=='John') {
ss.getSheetByName(sObj[evA[i][2]]).appendRow(evA[i]);
esh.deleteRow(i+1-d);
d++;
}
}
}
So Franks Sheet and Davids Sheet only get the rows that are older than today. But Johns Sheet gets all of the row that are Johns and disregards the date. I think that's what you wanted.
By the way, did you know that if you more that one form attached to your spreadsheet you can tell which response sheet the formSubmit trigger is writing too, with the event object range? Using sheet name = e.range.getSheet().getName();

Struggling with an If / Else Script

Struggling beginner here, trying to get my script done and I'm just lost at this point. Let me start by posting my script.
function dailyclear(e)
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Today');
sheet.copyTo(ss)
var nusheet = ss.getSheetByName('Copy of Today')
var value = nusheet.getRange("B2").getCell(1,1).getValue()
SpreadsheetApp.setActiveSheet(nusheet)
Logger.log("Current index of sheet: %s", nusheet.getIndex())
ss.moveActiveSheet(2);
nusheet.setName(value);
//Clear "Today"
var lastrow = sheet.getLastRow()
sheet.deleteRows(8, lastrow-7)
//Set Date Value for "Today"
var dd = Utilities.formatDate(new Date(), "GMT-5", "MM/dd/yy");
sheet.getRange("B2").getCell(1,1).setValue(dd);
}
What I want my script to do is before the //Clear line have an If/else statement that goes like this..."IF there is any text in A8 THEN run sheet.deleterows(8, lastrow-7), ELSE skip to setting the date." I hope that makes sense. Basically I want to to delete all rows except the top 7 based off if any data has been entered in A8, otherwise don't try to delete anything because it will just error on me and lock up.
I have been trying for days to figure this out on my own just by reading on the net and I am throwing in the towel. Any help would be appreciated. The link to my sheet is https://docs.google.com/spreadsheets/d/1NZxXjMptx6ldzL2CKk6OwJcq_heIv995ZGVeIE59xNc/edit?usp=sharing
Thanks for anything and everything offered!
I think this is what you're looking to achieve:
function dailyclear() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ui = SpreadsheetApp.getUi();
var sheet = ss.getSheetByName('Today');
var getB2 = sheet.getRange("B2").getValue();
sheet.copyTo(ss).setName(getB2);
var nusheet = ss.getSheetByName(getB2);
Logger.log("Current index of sheet: %s", nusheet.getIndex());
ss.setActiveSheet(nusheet);
ss.moveActiveSheet(2);
var getA8 = sheet.getRange('A8').getValue();
if (getA8) {
var numRows = sheet.getMaxRows();
if (numRows > 8) {
sheet.deleteRows(8, numRows - 8);
} else {
sheet.deleteRow(8);
}
} else {
var newDate = Utilities.formatDate(new Date(), "GMT-5", "MM/dd/yy");
sheet.getRange("B2").setValue(newDate);
}
}

move a row in google spreadsheet based on todays date

I'm trying to move a row of data from one sheet to another in the same spreadsheet based on a value of today's date.
In column "A", I have a date. I want to move the row if the date entered in column "A" is older than today's date. (it's a flight schedule for aircraft and I want to move flights that have already occured onto a sheet called "Past Flights".) The name of the active sheet is "Flight Schedule".
After the row is moved, I want it to delete off the "Flight Schedule" sheet. I know where to add scripts, but have no idea how to make this happen.
Here is what I have tried. I think on line "If (data.link >1..." data.link isn't the right one to use. But I can't find something for indicating older than todays date.
function approveRequests() {
var ss = SpreadsheetApp.getActiveSpreadsheet()
sheet = ss.getActiveSheet(),
sheetName = sheet.getName(),
data = sheet.getDataRange().getValues();
if (sheetName == "Flight Shedule") {
var range = sheet.getActiveRange(),
startRow = range.getRowIndex(),
numRows = range.getNumRows(),
numCols = range.getNumColumns()
if (numCols == 9) {
if (data.length > 1) {
var values = range.getValues(),
nextSheet = ss.getSheetByName("Past Flight"),
lastRow = nextSheet.getLastRow();
nextSheet.getRange(lastRow+1,1,numRows,3).setValues(values);
sheet.deleteRows(startRow,numRows);
}
}
}
}
Any help would be huge!
Thanks!
Ok, I will go in with some general tips based on your current code first.
In your function you do a sheet = ss.getActiveSheet() which is redundant because you already have SpreadsheetApp.getActiveSpreadsheet().Also I would recommend to avoid this
var ss = SpreadsheetApp.getActiveSpreadsheet()
sheet = ss.getActiveSheet(),
sheetName = sheet.getName(),
data = sheet.getDataRange().getValues();
in favour of this:
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var sheetName = sheet.getName();
var data = sheet.getDataRange().getValues();
which is much more easy to read and change without making mistakes.
data.length has nothing to do with current date, it will simply be the length of the array. So if you select 1 row of data, it will be 1, if you select 2 rows it will be 2 etc. .getValues() will return an array where data[row][col]. What you are looking for is getting the value of the flight time, converting it into a date object (not a google specific thing, just general javascript). Then use var now = new Date() and compare the two.
I would also recommend to re-think your if statements. There are a lot of better ways to grab the row data than selecting the row manually and then running the function. You can save a lot of lines of code should you decide to actually make this run automatically, because as it is, it will run only when called manually.
This sample is working:
function approveRequests() {
// Initialising
var ss = SpreadsheetApp.getActiveSpreadsheet();
var scheduleSheet = ss.getSheetByName("Flight Shedule");
var pastSheet = ss.getSheetByName("Past Flight");
var lastColumn = scheduleSheet.getLastColumn();
// Check all values from your "Flight Schedule" sheet
for(var i = scheduleSheet.getLastRow(); i > 0; i--){
// Check if the value is a valid date
var dateCell = scheduleSheet.getRange(i, 1).getValue();
if(isValidDate(dateCell)){
var today = new Date();
var test = new Date(dateCell);
// If the value is a valid date and is a past date, we remove it from the sheet to paste on the other sheet
if(test < today){
var rangeToMove = scheduleSheet.getRange(i, 1, 1, scheduleSheet.getLastColumn()).getValues();
pastSheet.getRange(pastSheet.getLastRow() + 1, 1, 1, scheduleSheet.getLastColumn()).setValues(rangeToMove);
scheduleSheet.deleteRow(i);
}
}
}
}
// Check is a valid date
function isValidDate(value) {
var dateWrapper = new Date(value);
return !isNaN(dateWrapper.getDate());
}
So yes, It's not the optimized solution (cause of the use of several sheet.getRange() method), but it's working and allowing to have a clear code.