Copy rows that meet a date in Google Sheets - google-apps-script

I want to be able to copy rows from a source sheet to a destination sheet that is the date in a range equals a target date.
I am using the following script and works perfectly when the target is a 'text', but as soon as I try to use a 'date' I get the following error: TypeError: Cannot read property "length" from undefined.
function copyrange() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Source'); //source sheet
var testrange = sheet.getRange('F:F');
var testvalue = (testrange.getValues());
var csh = ss.getSheetByName('Destination'); //destination sheet
var data = [];
var j =[];
//Condition check in L:L; If true copy the same row to data array
for (i=0; i<testvalue.length;i++) {
if ( testvalue[i] == 'target') {
data.push.apply(data,sheet.getRange(i+1,1,1,45).getValues());
//Copy matched ROW numbers to j
j.push(i);
}
}
//Copy data array to destination sheet
csh.getRange(csh.getLastRow()+1,1,data.length,data[0].length).setValues(data);
}
Thanks
Simon

I wasn't sure what your target was so I assumed current date and proceeded anyway. If it's wrong let me know.
function copyrange() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Source');
var vA=sh.getRange(1,1,sh.getLastRow(),sh.getLastColumn()).getValues();
var csh=ss.getSheetByName('Destination');
var found=false;
var dt=new Date();
var today=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();//midnight
var output=[];
for (var i=0;i<vA.length;i++) {
var date=new Date(vA[i][4]);//can be a string the constructor recognizes or a date
var dv=new Date(date.getFullYear(),date.getMonth(),date.getDate()).valueOf();//midnight
if (dv==today) {
output.push(vA[i]);
var found=true;
}
}
if(found) {
csh.getRange(csh.getLastRow()+1,1,output.length,output[0].length).setValues(output);
}else{
SpreadsheetApp.getUi().alert('No matches');
}
}
The following function will get those rows that have todays date and this email email1#test.com.
function copyrange(target) {
var target=target||'email1#test.com';
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Source');
var vA=sh.getRange(1,1,sh.getLastRow(),sh.getLastColumn()).getValues();
var csh=ss.getSheetByName('Destination');
var found=false;
var dt=new Date();
var today=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();//midnight
var output=[];
for (var i=0;i<vA.length;i++) {
var date=new Date(vA[i][4]);//can be a string the constructor recognizes or a date
var dv=new Date(date.getFullYear(),date.getMonth(),date.getDate()).valueOf();//midnight
if (dv==today && vA[i][6]==target) {
output.push(vA[i]);
var found=true;
}
}
if(found) {
csh.getRange(csh.getLastRow()+1,1,output.length,output[0].length).setValues(output);
}else{
SpreadsheetApp.getUi().alert('No matches');
}
}
And you can change the target email by passing an email to the function.
This function covers dates that have occurred in the last week:
function copyrange(target) {
var target=target||'email1#test.com';
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Source');
var vA=sh.getRange(1,1,sh.getLastRow(),sh.getLastColumn()).getValues();
var csh=ss.getSheetByName('Destination');
var found=false;
var dt=new Date();
var today=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();//midnight
var sevendaysago=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()-7).valueOf();//midnight
var output=[];
for (var i=0;i<vA.length;i++) {
var date=new Date(vA[i][4]);//can be a string the constructor recognizes or a date
var dv=new Date(date.getFullYear(),date.getMonth(),date.getDate()).valueOf();//midnight
if (dv>=sevendaysago && dv<=today && vA[i][6]==target) {
output.push(vA[i]);
var found=true;
}
}
if(found) {
csh.getRange(csh.getLastRow()+1,1,output.length,output[0].length).setValues(output);
}else{
SpreadsheetApp.getUi().alert('No matches');
}
}
This function only copies B and G of the matching row.
function copyrange(target) {
var target=target||'email1#test.com';
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Source');
var vA=sh.getRange(1,1,sh.getLastRow(),sh.getLastColumn()).getValues();
var csh=ss.getSheetByName('Destination');
var found=false;
var dt=new Date();
var today=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();//midnight
var sevendaysago=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()-7).valueOf();//midnight
var output=[];
for (var i=0;i<vA.length;i++) {
var date=new Date(vA[i][4]);//can be a string the constructor recognizes or a date
var dv=new Date(date.getFullYear(),date.getMonth(),date.getDate()).valueOf();//midnight
if (dv>=sevendaysago && dv<=today && vA[i][6]==target) {
output.push([vA[i][1],vA[6]]);
var found=true;
}
}
if(found) {
csh.getRange(csh.getLastRow()+1,1,output.length,output[0].length).setValues(output);
}else{
SpreadsheetApp.getUi().alert('No matches');
}
}

Related

how do I open my sheet automatically on next week's date?

I have used a code found in another post (thank you very much, see below), to make a sheet open on Today's date.
Please, could you advise where I would need to add "+7" (or something else) to make it open on the date a week from now (Today + 7 days)?
How do I get my google spreadsheet to open to today's date?
function onOpen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var range = sheet.getRange("1:1");
var values = range.getValues();
values = values[0];
var day = 24*3600*1000;
var today = parseInt((new Date().setHours(0,0,0,0))/day);
Logger.log(today);
var ssdate;
for (var i=0; i<values.length; i++) {
try {
ssdate = values[i].getTime()/day;
}
catch(e) {
}
if (ssdate && Math.floor(ssdate) == today) {
sheet.setActiveRange(range.offset(0,i,1,1));
break;
}
}
}
Try this:
function onOpen() {
var ss=SpreadsheetApp.getActive();
var sheet=ss.getActiveSheet();
var range=sheet.getRange("1:1");
var values=range.getValues()[0];
var today=new Date();
var nextweek=new Date(today.getFullYear(),today.getMonth(),today.getDate()+7);
for (var i=0;i<values.length;i++) {
var ssdate = values[i].getTime()/86400000;
if (ssdate && Math.floor(ssdate) == nextweek) {
sheet.setActiveRange(range.offset(0,i,1,1));
break;
}
}
}

How to get the cell position of a button or rather how to get a variable for the execution of a button?

With the function I woud like to do the following:
Flow
1.) Get the current User ID
2.) Finding the user's lines where the states are on the alert icon
3.) Change the date in column K to the current date using the format "dd.MM.yyyy"
4.) Generate a time stamp in column L using the format "HH:mm:ss"
5.) Generate a time stamp in the column P using the format "dd.MM.yyyy' 'HH:mm"
Therefore I used the code below.
Unfortunately the code doesn't work. I did not got any error.
What am I doing wrong?
function CheckAll(){
var userID=getUserId();
if(userID) {
var timezone = "GMT+2";
var TimestampFormat1 = "dd.MM.yyyy' 'HH:mm";
var TimestampFormat2 = "HH:mm:ss";
var ss=SpreadsheetApp.getActiveSpreadsheet();
var tickerCheck=ss.getSheetByName('WATCHLIST-Pflege');
var State=tickerCheck.getRange("O1:O2").getCell(2,1).getValues();
var startRow=16;
var lastRow=tickerCheck.getLastRow()-startRow+1;
var rngStateCheck=tickerCheck.getRange(startRow,15,lastRow,1);
var StateCheck=rngStateCheck.getValues();
var userIds=tickerCheck.getRange(startRow,1,lastRow,1).getValues();
var rngLastCheck=tickerCheck.getRange(startRow,11,lastRow,1);
var rngTimeStamp1=tickerCheck.getRange(startRow,12,lastRow,1);
var rngTimeStamp2=tickerCheck.getRange(startRow,16,lastRow,1);
var date=new Date();
for(var i=0;i<StateCheck.length;i++){
if(StateCheck[i][14]==State && userIds[i][0]==userID){
rngLastCheck.getCell(i+1, 1).setValue(date);
rngTimeStamp1.getCell(i+1, 1).setValue(Utilities.formatDate(date, timezone, TimestampFormat2));
rngTimeStamp2.getCell(i+1, 1).setValue(Utilities.formatDate(date, timezone, TimestampFormat1));
}
}
}else{
SpreadsheetApp.getUi().alert('Falsche User ID');
}
}
function getUserId() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Startseite');
var rg=sh.getRange(35,3,sh.getLastRow()-3,3);
var vA=rg.getValues();
var userEmail=Session.getEffectiveUser().getEmail();
for(var i=0;i<vA.length;i++) {
if(vA[i][0]==userEmail) {
return vA[i][1];
break;
}
}
return null;
}
I solved the problem by adding the variable var StateToCheck=StateCheck[i][0] to the for loop.
Now the code looks like this:
function CheckAll(){
var userID=getUserId();
if(userID) {
var timezone = "GMT+2";
var TimestampFormat1 = "dd.MM.yyyy' 'HH:mm";
var TimestampFormat2 = "HH:mm:ss";
var ss=SpreadsheetApp.getActiveSpreadsheet();
var tickerCheck=ss.getSheetByName('WATCHLIST-Pflege');
var State=tickerCheck.getRange("O1:O2").getCell(2,1).getValues();
var startRow=16;
var lastRow=tickerCheck.getLastRow()-startRow+1;
var rngStateCheck=tickerCheck.getRange(startRow,15,lastRow,1);
var StateCheck=rngStateCheck.getValues();
var userIds=tickerCheck.getRange(startRow,1,lastRow,1).getValues();
var rngLastCheck=tickerCheck.getRange(startRow,11,lastRow,1);
var rngTimeStamp1=tickerCheck.getRange(startRow,12,lastRow,1);
var rngTimeStamp2=tickerCheck.getRange(startRow,16,lastRow,1);
var date=new Date();
for(var i=0;i<StateCheck.length;i++){
var StateToCheck=StateCheck[i][0]
if((StateToCheck==State)&&(userIds[i][0]==userID)){
rngLastCheck.getCell(i+1, 1).setValue(date);
rngTimeStamp1.getCell(i+1, 1).setValue(Utilities.formatDate(date, timezone, TimestampFormat2));
rngTimeStamp2.getCell(i+1, 1).setValue(Utilities.formatDate(date, timezone, TimestampFormat1));
}
}
}else{
SpreadsheetApp.getUi().alert('Falsche User ID');
}
}
function getUserId() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Startseite');
var rg=sh.getRange(35,3,sh.getLastRow()-3,3);
var vA=rg.getValues();
var userEmail=Session.getEffectiveUser().getEmail();
for(var i=0;i<vA.length;i++) {
if(vA[i][0]==userEmail) {
return vA[i][1];
break;
}
}
return null;
}
You could use this approach:
function CheckAll1(){
var userID=getUserId();
if(userID) {
var ss=SpreadsheetApp.getActive();
var tsh=ss.getSheetByName('Tickerprüfung');
var startRow=12;
var lastRow=tsh.getLastRow()-startRow+1;
var range=tsh.getRange(startRow,12,tsh.getLastRow()-startRow+1,1);
var tvA=range.getValues();
var userIds=tsh.getRange(startRow,1,tsh.getLastRow()-startRow+1,1).getValues();
var lcrg=tsh.getRange(startRow,9,tsh.getLastRow()-startRow+1,1);
var tsrg=tsh.getRange(startRow,10,tsh.getLastRow()-startRow+1,1);
var today=new Date();
var dateInMs=new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime();
for(var i=0;i<tvA.length;i++){
var nextDate=new Date(tvA[i][0]);
if(Object.prototype.toString.call(nextDate) === '[object Date]' && userIds[i][0]==userID) {
if(dateInMs>=nextDate.getTime()){
lcrg.getCell(i+startRow, 1).setValue(today);
tsrg.getCell(i+startRow, 1).setValue(new Date().toLocaleTimeString());
}
}
}
}else{
SpreadsheetApp.getUi().alert('Invalid UserId');
}
}
function getUserId() {
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Startseite');
var rg=sh.getRange(20,2,sh.getLastRow()-19,2);
var vA=rg.getValues();
var userEmail=Session.getEffectiveUser().getEmail();
for(var i=0;i<vA.length;i++) {
if(vA[i][0]==userEmail) {
return vA[i][1];
break;
}
}
return null;
}
And then in the Startseite sheet you could associate user emails with UserId's in this way.
Look closely at the code as I have corrected some errors pertaining to the calculation of rows that did not account for startRow=12 also third parameter in a range is the number of rows not the last row.

Date compare If statement not working, see what is wrong

I want to compare two dates and see what is similar but the if doesn't
work. I want to create a comparison with a cell value and a column of values.
function jobLogSchedule () {
var ss = SpreadsheetApp.getActiveSpreadsheet();/// Activate Sheet Application
var formSS = ss.getSheetByName("Form"); //Form Sheet
var dataBase = ss.getSheetByName("Data"); //Data Sheet
var viewSchedule = formSS.getRange("H2").getValue();
var firstDate = new Date(viewSchedule);
formSS.getRange("H2").setValue(firstDate);
formSS.getRange("H4").setValue(firstDate);
var lastRow = dataBase.getLastRow();
for(i=1; i<lastRow; i++){
var workingCell = dataBase.getRange(i,6,lastRow);
var dateDataBase = workingCell.getValue();
if (dateDataBase == viewSchedule) {
}
else {
}
}
}
try this:
function jobLogSchedule () {
var ss=SpreadsheetApp.getActive();
var fsh=ss.getSheetByName("Form");
var dsh=ss.getSheetByName("Data");
var lastRow=dsh.getLastRow();
var drg=dsh.getRange(1,6,lastRow,1);
var vA=drg.getValues();
var firstDate = new Date(fsh.getRange("H2").getValue());
fsh.getRange("H2").setValue(firstDate);
fsh.getRange("H4").setValue(firstDate);
for(i=0;i<vA.length;i++){
if (new Date(vA[i][0]).valueOf()==firstDate.valueOf()) {
//true
}
else {
//false
}
}
}

Google App Script, Moving row onto another sheet if date has passed

I've been working on this code and doing some research the last couple of weeks and not having much luck. I'm looking to setup a trigger that will scan Col C of dates and if the date has passed move that specific row to another sheet.
Below is where I'm currently at.
Note that I have today's date stored in cell 'O2' of the 'Contract Language' sheet.
I've gotten this code to work with text, but not with dates.
Any advise is greatly appreciated!
function MovetoPastShows2() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Confirmed Deals'); //source sheet
var testrange = sheet.getRange('C:C');
var testvalue = testrange.getValues();
var todaysheet = ss.getSheetByName('Contract Language');
var todaycol = todaysheet.getRange('O2');
var today = todaycol.getValues().valueOf();
var csh = ss.getSheetByName('Confirmed (Past)'); //destination sheet
var data = [];
var j =[];
for (i=0; i<testvalue.length;i++) {
if ( testvalue[i] = today) {
data.push.apply(data,sheet.getRange(i+1,1,1,187).getValues());
j.push(i);
}
}
csh.getRange(csh.getLastRow()+1,1,data.length,data[0].length).setValues(data);
for (i=0;i<j.length;i++){
var k = j[i]+1;
sheet.deleteRow(k);
if (!(i == j.length-1)) {
j[i+1] = j[i+1]-i-1;
}
}
};
Move Past Rows to Destination Sheet
function MovetoPastShows2() {
var ss = SpreadsheetApp.getActive();
var sh=ss.getSheetByName('Confirmed Deals');
var rg=sh.getDataRange();
var vA=rg.getValues();
var today=new Date(ss.getSheetByName('Contract Language').getRange('O2').getValue()).valueOf();
var dsh=ss.getSheetByName('Confirmed (Past)');
var d=0;
for(var i=0;i<vA.length;i++) {
if (new Date(vA[i][2]).valueOf()<=today) {
dsh.appendRow(vA[i])
sh.deleteRow(i+1-d);
d++;
}
}
}

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;
}
}
}