Auto Move Data of Specific Date - javascript

Link of My sheet is :
https://docs.google.com/spreadsheets/d/1czJbRU5ELNft1IfGq1cABGe30j8BWjnffVCEa8A_AeY/edit?usp=sharing
I am trying to move data if N is equal to today. I have set the trigger. This script runs on time driven between 8 PM to 9 PM. It copies the data in Row 8 when column K onwards there is noting mentioned. In the current Payment Approval Sheet, while running the script it copies the data in 1500th row.
The script I am using is as below:
function copyrange() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Complete Invoice Sheet'); //source sheet
var testrange = sheet.getRange('N:N');
var testvalue = (testrange.setNumberFormat("#").getValues());
var ds = ss.getSheetByName('Payment Approval Sheet'); //destination sheet
var data = [];
var j =[];
var dt = new Date();
var today = Utilities.formatDate(new Date(), 'GMT-0', 'dd/MM/yyyy')
//Condition to check in N:N, if true, copy the same row to data array
for (i=0;i<testvalue.length;i++) {
if (testvalue[i] == today) {
data.push.apply(data,sheet.getRange(i+1,1,1,13).getValues());
//Copy matched ROW numbers to j
j.push(i);
}
}
//Copy data array to destination sheet
ds.getRange(ds.getLastRow()+1,1,data.length,data[0].length).setValues(data);
}

Issue:
Your current solution considers the last row of your destination
sheet Payment Approval Sheet. However, in that sheet, checkboxes
are populated in column N until the bottom of the sheet. Therefore,
getLastRow() returns the row at the bottom of column N which is not
what you want.
Explanation:
Instead of using getLastRow(), calculate the number of elements after cell A7 by using the filter() operation and then use this as a starting point when you copy & paste the data to the destination sheet:
var start_row=ds.getRange('A8:A').getValues().filter(String).length +7; //calculate max row
ds.getRange(start_row+1,1,data.length,data[0].length).setValues(data);
Solution:
function copyrange() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Complete Invoice Sheet'); //source sheet
var testrange = sheet.getRange('K:K');
var testvalue = (testrange.setNumberFormat("#").getValues());
Logger.log(testvalue);
var ds = ss.getSheetByName('Payment Approval Sheet'); //destination sheet
var data = [];
var j =[];
var dt = new Date();
var today = Utilities.formatDate(new Date(), 'GMT-0', 'dd/MM/yyyy')
//Condition to check in N:N, if true, copy the same row to data array
for (i=0;i<testvalue.length;i++) {
if (testvalue[i] == today) {
data.push.apply(data,sheet.getRange(i+1,1,1,13).getValues());
//Copy matched ROW numbers to j
j.push(i);
}
}
//Copy data array to destination sheet
var start_row=ds.getRange('A8:A').getValues().filter(String).length +7; //calculate max row
ds.getRange(start_row+1,1,data.length,data[0].length).setValues(data);
}

Related

How To Add Sheets Based on Cell Values?

I want to create a new worksheet each time I have a new user details in column 1 of my USERS sheet. Here is the code I have so far:
// Get the data from the sheet called CreateSheets
var sheetNames = SpreadsheetApp.getActive().getSheetByName("USERS").getDataRange().getValues();
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("USERS");
var data = ss.getDataRange().getValues();
var lr = ss.getLastRow();
var dataRange = ss.getRange(1, 1, lr, 1);
// Fetch values for each row in the Range.
var data = dataRange.getValues();
for (var i = 0; i < data.length; ++i) {
var row = data[i];
// For each row in the sheet, insert a new sheet and rename it.
sheetNames.forEach(function(row) {
var sheetName = data;
var sheet = SpreadsheetApp.getActive().insertSheet();
sheet.setName(sheetName);
});
}}
The code works but it is combining the data in the cells in column 1 into the name of the new spreadsheet. Thanks
function myfunc() {
const ss = SpreadsheetApp.getActive();
const ush = ss.getSheetByName("USERS");
const names = ush.getRange(1, 1, ush.getLastRow(), 1).getValues().flat();
const enames = ss.getSheets().map(s => s.getName());
names.forEach(n => {
if (~e.names.indexOf(n)) {
ss.insertSheet().setName(n);
enames.push(n); //add name to array to avoid duplicate names in column
}
});
}
Updated to account for existing sheet names and potential duplicate names in column 1.
I think this should do what you want. You should probably build in some sort of check to ensure the sheet doesn't already exist.
function makeSheetHappen() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var wsUser = ss.getSheetByName("USERS");//the sheet with users
//this gets all values in column 1 to end of spreadsheet (it might include blanks)
//flat function avoids having to pull 2-dim array (h/t COOPER!)
var sheetNames = wsUser.getRange(1, 1, wsUser.getLastRow(), 1).getValues().flat();
//mapping function to get an array of the spreadsheet's sheet names.
var theExistingNames = ss.getSheets().map(function (aSheet) {
return aSheet.getName();
});
//loops through the sheetNames and ensures not blank and not currently existing.
sheetNames.forEach(function (aName) {
if (aName != '' && !theExistingNames.includes(aName)) {
var newSheet = ss.insertSheet();
newSheet.setName(aName);
theExistingNames.push(aName); //add name to array to avoid duplicate names in column
}
});
}

Converting timestamps to dates in Google sheet script

I am writing a code that targets a column with dates and I would like to get the dates and compare it to the current date so that I can get the difference between the two.
I ran into a problem I am having trouble solving. It seems that when I used .getValues in my range, it placed each timestamp in an array then those arrays in another array. Like this: [[(new Date(1539619200000))], [(new Date(1540396800000))], [(new Date(1540828800000))]]
I would like to place all the values in 1 array only so I can start solving how to convert the timestamps in to normal dates. I am also a beginner with this so I am sorry if this seems like an basic question.
function datesincolumn() //collects only the date values in range
{
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow(); //will identify last row with any data
entered
var range = sheet.getRange('D2:D' + lastRow); //will get range of cells
with data present
var dates = range.getValues();//gets all values in the range
var CurrentDate = new Date();
var timestamps = [];
for (i = 0; i <= dates.length; i++)
{
if (dates[i] >= i)
{
timestamps.push(dates[i]);
}
}
Logger.log(dates);
}
When you use .getValues(), you will always get a 2-dimensional array. The outer array represents the row, and the inner array represents the columns. Since you're only getting one column, you can simply append [0] to your dates[i].
function datesincolumn() { //collects only the date values in range
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow(); //will identify last row with any data entered
var range = sheet.getRange('D2:D' + lastRow); //will get range of cells with data present
var dates = range.getValues();//gets all values in the range
var CurrentDate = new Date();
var timestamps = [];
for (var i = 0; i <= dates.length; i++) {
var date = dates[i][0];
if (date >= i)
timestamps.push(date);
}
Logger.log(dates);
}

Google App Script - Insert Data Into Next Column

This script fetches the data from the sheet and insert it into a new sheet. I want the second function to insert into the third row each time.
I want the result to be -
Timestamp | Impressions | CTR
function AggregateData() {
Impressions();
CTR();
}
function Impressions() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Metrics");
var source = sheet.getRange("G16:H16");
var values = source.getValues();
var sheet = ss.getSheetByName("Aggregate");
values[0][0] = new Date();
sheet.appendRow(values[0]);
};
function CTR() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Metrics");
var source = sheet.getRange("F16:G16");
var values = source.getValues();
var sheet = ss.getSheetByName("Aggregate");
values[0][0] = new Date();
sheet.appendRow(values[0]);
};
This code appends the second function in the second column itself below the result of the first function.
This code will copy your data to a new sheet in the order you want. However, I have reduced it to one function. The reason your code puts the new data in a new row is this line:
Sheet.appendRow(data)
puts the data you supply to a new row which is empty. That is also the reason why i have combined the two functions into one.
function AggregateData() {
Impressions();
}
function Impressions() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Metrics");
var source = sheet.getRange("F16:H16");
var values = source.getValues();
var pasteValues = [] // create new array which will hold the data you need to be pasted into the aggregate Sheet
pasteValues[0] = [] // Adding a second dimesion to the array
var sheet = ss.getSheetByName("Aggregate");
// below 3 lines does the switch of data and adds the time stamp
pasteValues[0][0] = new Date();
pasteValues[0][1] = values[0][2] //Copy the col h (impressions value) value into the new array
pasteValues[0][2] = values[0][1] //Copy the col G (impressions value) value into the new array
sheet.appendRow(pasteValues[0]); //Append the new array into the sheet
};

Google Sheets - Delete Expired Rows Based On Date

I'm currently trying to make a script or literally anything that will be able to delete a row after the given date in Column C.
The site is a giveaway site so I need the rows/entries to delete themselves once the date specified on Column C is passed.
Eg: If one giveaway had an expiration date # 20/13/2016, once the date reaches this date of 20/13/2016 it will delete the row. I am following the metric system of dd/mm/yy as a note.
I saw a question similar to this at Google Sheets - Script to delete date expired rows but the code won't work for my needs.
Here is the code that was used in the other question.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Foglio1");
var datarange = sheet.getDataRange();
var lastrow = datarange.getLastRow();
var values = datarange.getValues();// get all data in a 2D array
var currentDate = new Date();
var oneweekago = new Date();
oneweekago.setDate(currentDate.getDate() - 7);
for (i=lastrow;i>=2;i--) {
var tempdate = values[i-1][2];// arrays are 0 indexed so row1 = values[0] and col3 = [2]
if(tempdate < oneweekago)
{
sheet.deleteRow(i);
}
}
}
If you could change it to work for my above needs it will be greatly appreciated!
Assuming your dates are in column C as stated, this should do it. The adjustment is just to the date to which we compare and to handle missing dates. I am also messing with the case on some names for readability.
function DeleteOldEntries() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Live Events");//assumes Live Events is the name of the sheet
var datarange = sheet.getDataRange();
var lastrow = datarange.getLastRow();
var values = datarange.getValues();// get all data in a 2D array
var currentDate = new Date();//today
for (i=lastrow;i>=3;i--) {
var tempDate = values[i-1][2];// arrays are 0 indexed so row1 = values[0] and col3 = [2]
if ((tempDate!=NaN) && (tempDate <= currentDate))
{
sheet.deleteRow(i);
}//closes if
}//closes for loop
}//closes function

Trouble with a simple GoogleScript code (google sheets + gmail integration)

function checkReminder() {
// get the spreadsheet object
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
// set the first sheet as active
SpreadsheetApp.setActiveSheet(spreadsheet.getSheets()[0]);
// fetch this sheet
var sheet = spreadsheet.getActiveSheet();
// figure out what the last row is
var lastRow = sheet.getLastRow();
// the rows are indexed starting at 1, and the first row
// is the headers, so start with row 2
var startRow = 2;
// grab column 10 (the 'date end' column)
var range = sheet.getRange(2,10,lastRow-startRow+1,1 );
var numRows = range.getNumRows();
var date_end_values = range.getValues();
// Now, grab the Event name data
range = sheet.getRange(2, 5, lastRow-startRow+1, 1);
var reminder_info_values = range.getValues();
var warning_count = 0;
var msg = "Send out a follow-up email asking how the event was!";
}
//Get today's date
var todaysDate = new Date();
var numRows = numRows
// Loop over the days left values
for (var i = 0; i <= numRows - 1; i++) {
var date_end = date_end_values[i][0];
//call setHours to take the time out of the comparison
if(date_end == todaysDate.setHours(0,0,0,0)) {
MailApp.sendEmail("max#xpogo.com",
"Reminder Spreadsheet Message", msg);
}
What I'm trying to do is have gmail send me a reminder when a certain column in my data set is equal to the present date. Im new to coding and am running into trouble. Please help?
I added the following after your variables were set, to determine whether they were commensurate for your comparison (hit ctrl+Enter after executing to view the log).
Logger.log(date_end);
Logger.log(todaysDate.setHours(0,0,0,0));
They weren't comparable at all. Here are the lines I changed to make this work:
var todaysDate = Utilities.formatDate(new Date(), "GMT+1", "MM/dd/yyyy");
var date_end = Utilities.formatDate(date_end_values[i][0], "GMT+1", "MM/dd/yyyy");
if(date_end == todaysDate) {
HTH

Categories