Get row where certain date value occurs - google-sheets

I would like to persist the last row with yesterday's date.
My data looks like the following:
I have tried the following to persist the data, which works well.
function moveValuesOnly() {
var ss = SpreadsheetApp.getActive().getSheetByName('Store values');
Logger.log(ss.getName());
// get yesterday's date
var now = new Date();
var yesterday = new Date();
yesterday.setDate(now.getDate()-1);
yesterday = Utilities.formatDate(yesterday, "GMT+1", 'yyyy-MM-dd');
Logger.log("yesterday: " + yesterday);
var source = ss.getRange('4:4');
source.copyTo(ss.getRange('4:4'), {contentsOnly: true});
source.setFontWeight("bold");
}
Find below an example spreadsheet:
Sample Spreadsheet
As you can see I am getting yesterday's date correctly formatted in my script as in my Date column. I also can correctly 'persist' the data.
My problem is that I do not know how to get the range where yesterday's date occurs so that I can hand it over in my script to persist it.
Any suggestions how to get the row that matches yesterday's date.

not totally sure what you mean by "persist" but the function below returns the row number for the first row with yesterday's date in it:
function getYesterdayRow(yesterdayDate,columnRange) {
var displayValues = columnRange.getDisplayValues();
for (var i = 0; i < displayValues.length; i++) {
var displayValue = displayValues[i][0];
if (displayValue === yesterdayDate) return i + 1;
}
return 0;
}
You can call it like this in your code after you've defined yesterday:
var yesterdayRow = getYesterdayRow(yesterday,ss.getRange(A:A))
Note that this function quickly fixes your current need, but it uses getdisplayValues(), which is a quick cheat to not have to deal with processing the date. You should probably modify this function so that it would work with other date formats. (Use getValues(), get the day, time and month from yesterday, then the same from each value in the for loop, and make sure to account for any timezone offsets.)

Related

searchRecord isn't rendering correct info or takes several times to display

I'm running a Apps Script to create a data entry form. Sometimes my searchRecord function works if I run it several times. Sometimes it doesn't pull any info, but never gives me the warning screen, sometimes it pulls the info from the last search. I'm not sure where the problem is. I have copied the code below.
//Function to Search the record
function searchRecord(){
var myGoogleSheet=SpreadsheetApp.getActiveSpreadsheet(); //declare a variable and set with active Google Sheet
var shUserForm=myGoogleSheet.getSheetByName("User Form"); //declare a variable and set with the User Form reference
var datasheet=myGoogleSheet.getSheetByName("Existing Customers"); //declare variable and set the reference of database sheet
var str=shUserForm.getRange("B2").getValue(); //get data input for search button
var values=datasheet.getDataRange().getValues(); //getting the entire values from the used range and assigning it to values variable
var valuesFound=false; //variable to store boolean value
for (var i=0; i<values.length; i++)
{
var rowValue=values[i]; //declare a variable and storing the value
//checking the first value of the record is equal to search item
if(rowValue[6]==str){
shUserForm.getRange("B12").setValue(rowValue[0]);
shUserForm.getRange("B15").setValue(rowValue[1]);
shUserForm.getRange("B23").setValue(rowValue[2]);
shUserForm.getRange("B17").setValue(rowValue[3]);
shUserForm.getRange("E17").setValue(rowValue[4]);
shUserForm.getRange("B8").setValue(rowValue[6]);
shUserForm.getRange("E8").setValue(rowValue[7]);
shUserForm.getRange("B19").setValue(rowValue[8]);
shUserForm.getRange("E19").setValue(rowValue[9]);
shUserForm.getRange("B21").setValue(rowValue[10]);
shUserForm.getRange("E21").setValue(rowValue[11]);
shUserForm.getRange("E23").setValue(rowValue[12]);
shUserForm.getRange("E12").setValue(rowValue[13]);
shUserForm.getRange("B25").setValue(rowValue[14]);
shUserForm.getRange("E25").setValue(rowValue[15]);
shUserForm.getRange("B27").setValue(rowValue[16]);
shUserForm.getRange("E27").setValue(rowValue[17]);
shUserForm.getRange("B29").setValue(rowValue[18]);
shUserForm.getRange("E29").setValue(rowValue[19]);
shUserForm.getRange("B31").setValue(rowValue[20]);
shUserForm.getRange("E10").setValue(rowValue[21]);
shUserForm.getRange("B33").setValue(rowValue[22]);
shUserForm.getRange("B35").setValue(rowValue[23]);
shUserForm.getRange("B37").setValue(rowValue[24]);
shUserForm.getRange("E31").setValue(rowValue[25]);
shUserForm.getRange("E35").setValue(rowValue[26]);
shUserForm.getRange("B39").setValue(rowValue[27]);
shUserForm.getRange("E39").setValue(rowValue[27]);
shUserForm.getRange("B41").setValue(rowValue[29]);
shUserForm.getRange("E15").setValue(rowValue[30]);
shUserForm.getRange("B43").setValue(rowValue[31]);
shUserForm.getRange("E43").setValue(rowValue[32]);
shUserForm.getRange("B45").setValue(rowValue[33]);
shUserForm.getRange("E45").setValue(rowValue[34]);
shUserForm.getRange("B47").setValue(rowValue[35]);
shUserForm.getRange("B49").setValue(rowValue[36]);
shUserForm.getRange("B10").setValue(rowValue[37]);
shUserForm.getRange("E37").setValue(rowValue[5]);
valuesFound=true;
return;//come out from the loop
}
if(valuesFound=false){
//to create the instance of the user-interface environment to use the alert function
var ui=SpreadsheetApp.getui();
ui.alert("No Record Found");}
}
}
Solution
There are different points in your code that could be improved, I attach the updated function correcting the basics:
Indentation: This is easy to fix, just press ctrl + shft + i to correctly indent the code.
Break statement: Use the word break to break a loop.
Wrong comparison operator: The second if has only one = instead of two ==. Check Expressions and operators
Structural logic: Inside the for loop there are two ifs. Only the second one depends on the value of the valuesFound variable, which when modified breaks the loop, so it is not really doing anything.
Readability: It is difficult to understand what the code is doing and so many setValue boxes with no apparent connection is confusing.
In addition, it is difficult to offer help if the behavior of the function is variable and the reason is not known. Apparently, it should always give the same result.
Updated code
function searchRecord() {
var ss = SpreadsheetApp.getActiveSpreadsheet(); //declare a variable and set with active Google Sheet
var shUserForm = ss.getSheetByName("User Form"); //declare a variable and set with the User Form reference
var datasheet = ss.getSheetByName("Existing Customers"); //declare variable and set the reference of database sheet
var str = shUserForm.getRange("B2").getValue(); //get data input for search button
var values = datasheet.getDataRange().getValues(); //getting the entire values from the used range and assigning it to values variable
var valuesFound = false; //variable to store boolean value
var ui = SpreadsheetApp.getui();
for (var i = 0; i < values.length; i++) {
var rowValue = values[i]; //declare a variable and storing the value
//checking the first value of the record is equal to search item
if (rowValue[6] == str) {
shUserForm.getRange("B12").setValue(rowValue[0]);
shUserForm.getRange("B15").setValue(rowValue[1]);
shUserForm.getRange("B23").setValue(rowValue[2]);
shUserForm.getRange("B17").setValue(rowValue[3]);
shUserForm.getRange("E17").setValue(rowValue[4]);
shUserForm.getRange("B8").setValue(rowValue[6]);
shUserForm.getRange("E8").setValue(rowValue[7]);
shUserForm.getRange("B19").setValue(rowValue[8]);
shUserForm.getRange("E19").setValue(rowValue[9]);
shUserForm.getRange("B21").setValue(rowValue[10]);
shUserForm.getRange("E21").setValue(rowValue[11]);
shUserForm.getRange("E23").setValue(rowValue[12]);
shUserForm.getRange("E12").setValue(rowValue[13]);
shUserForm.getRange("B25").setValue(rowValue[14]);
shUserForm.getRange("E25").setValue(rowValue[15]);
shUserForm.getRange("B27").setValue(rowValue[16]);
shUserForm.getRange("E27").setValue(rowValue[17]);
shUserForm.getRange("B29").setValue(rowValue[18]);
shUserForm.getRange("E29").setValue(rowValue[19]);
shUserForm.getRange("B31").setValue(rowValue[20]);
shUserForm.getRange("E10").setValue(rowValue[21]);
shUserForm.getRange("B33").setValue(rowValue[22]);
shUserForm.getRange("B35").setValue(rowValue[23]);
shUserForm.getRange("B37").setValue(rowValue[24]);
shUserForm.getRange("E31").setValue(rowValue[25]);
shUserForm.getRange("E35").setValue(rowValue[26]);
shUserForm.getRange("B39").setValue(rowValue[27]);
shUserForm.getRange("E39").setValue(rowValue[27]);
shUserForm.getRange("B41").setValue(rowValue[29]);
shUserForm.getRange("E15").setValue(rowValue[30]);
shUserForm.getRange("B43").setValue(rowValue[31]);
shUserForm.getRange("E43").setValue(rowValue[32]);
shUserForm.getRange("B45").setValue(rowValue[33]);
shUserForm.getRange("E45").setValue(rowValue[34]);
shUserForm.getRange("B47").setValue(rowValue[35]);
shUserForm.getRange("B49").setValue(rowValue[36]);
shUserForm.getRange("B10").setValue(rowValue[37]);
shUserForm.getRange("E37").setValue(rowValue[5]);
valuesFound = true;
break
}
if (valuesFound == false) {
//to create the instance of the user-interface environment to use the alert function
ui.alert("No Record Found");
}
}
}

How Can I Paste A Google Sheets Range with everything except Values?

Trying to copy a range and paste only formulas, formatting, and data validation (no values) at the end of my sheet so I can enter new values in the freshly pasted range. All is working except I can't figure out how to exclude values when pasting.
Here is my code:
function addCue() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
// copy the first cue range as template
var copyCueRange = ss.getRange("A10:AA11");
// Find the end of the sheet and set pasteRange to match copyRange
var l = ss.getDataRange().getValues().length;
var pasteCueRange = ss.getRange( "A"+(l+1)+":AA"+(l+2) );
// This pastes all data, How do I paste without values?
copyCueRange.copyTo(pasteCueRange);
};
I am very new to coding and appreciate the help. Thank you.
Data Validation: the Range class has a couple of methods for getting and setting data validation rules, setDataValidations() and getDataValidations().
Formulas: just as data validation, Range also has get/set methods for formulas, setFormulas() and getFormulas().
Formatting: looks like the Range.copyTo() method has some options specified here. Try using the formatOnly additional parameter.
function addCue() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
// copy the first cue range as template
var copyCueRange = ss.getRange("A10:AA11");
// Find the end of the sheet and set pasteRange to match copyRange
var l = ss.getDataRange().getValues().length;
var pasteCueRange = ss.getRange( "A"+(l+1)+":AA"+(l+2) );
//Getting data validation and formulas
var dataValidationRules = copyCueRange.getDataValidations();
var formulas = copyCueRange.getFormulas()
//Setting formatting, data validations, and formulas
copyCueRange.copyTo(pasteCueRange, {formatOnly:true});
pasteCueRange.setDataValidations(dataValidationRules);
pasteCueRange.setFormulas(formulas);
}

Created Google Sheet Timezone

I have a script that converts and Excel file to a Google Sheet. However, the newly created Google Sheet defaults to the Pacific timezone. We already have our Company set to Eastern timezone in Google Admin. I also have the local machine that is executing the script set to Eastern timezone and the user is also set to Eastern timezone. The script project is set to Eastern timezone as well. If I goto Google Apps and create a sheet from scratch, it defaults to Eastern timezone as desired. But when the script creates the new sheet, it always defaults to Pacific timezone. Since it seems there's no way to set the timezone via a script function, is there anyway to make it default to Eastern timezone? Note as well that here in the Eastern timezone, we have the stupid daylight savings time. So it changes between -4 and -5, which is such a pain!
My reason for this is that after I convert the Excel to Google Sheet, I have to import the records into another import sheet. The imported data has dates and times that keep getting sku'd after or during the import. Since I import using the getRange.getValues function, it always performs the new Date(). I have tried the Utilities.format function as well. But I don't know if I can be sure that the timezone will stay the same. And since I can't read what timezone the created sheet has, it becomes a gamble.
I would appreciate any help that could be offered in the way of scripting fixes. It is not feasible for me to have to go in each time and change the timezone manually within the sheet itself.
Thanks for any help!
Doug
The conversion code:
function convertExceltoGoogleSheet(fileName, newFileName) {
try {
var fileName = fileName || "microsoft-excel.xlsx";
var excelFile = DriveApp.getFilesByName(fileName).next();
var fileId = excelFile.getId();
var folderId = Drive.Files.get(fileId).parents[0].id;
var blob = excelFile.getBlob();
//If no newFileName passed, create one
if (newFileName.trim() == '') {
//Generate formatted filename
var dateInfo = getDateInfo(-20);
var mo = dateInfo[2].toString();
if (mo.length < 2) {
var mo = "0" + mo;
}
var newFileName = dateInfo[0].toString() + "-" + mo + "-" + filename;
}
var resource = {
//title: excelFile.getName().replace(/.xlsx?/, ""), //use original filename
title: newFileName, //Use formatted filename from above
key: fileId,
parents: [{"id": folderId}]
};
var newFile = Drive.Files.insert(resource, blob, {
convert: true
});
return newFile.id;
} catch (f) {
Logger.log(f.toString());
}
}

Inserting into Array and comparing Dates Swift iOS Code

I am attempting to create an array that will store 365 integers, it must be filled completely. I am using Healthkit to figure out the users steps from a year back, hence the array size. Every integer represents 1 day.
I have done this in android already and it worked perfectly, I got 365 integers back with 0's for the days with no steps, however, the problem is with iOS health kit I get nothing from days with no data, which I need. In order to do this I thought I would compare the date variable I get with the date of the current day + 1 and loop through the array to see if it find any matching cases, if not put a 0 into it at the end.
So in order to do this I created an array of 365, at the line var ID = 0 is where I attempt to store the integers correctly into the array. I am using Swift 4.
struct stepy {
static var step = [365]
}
This is where I enumerate through the stepData, first at var ID I attempt to compare the date I get in the enumerate loop with the current date (basically index 0 in the array, which represents the first day, the current day).
However I got a problem, currently I believe I would overwrite the days which already has been inputted into the date at the second step enumeration? Also I can't get the date code to compile properly, I just get the Date has no valid member called "add"
stepsQuery.initialResultsHandler = { query, results, error in
let endDate = NSDate()
let startDate = calendar.date(byAdding: .day, value: -365, to: endDate as Date, wrappingComponents: false)
if let myResults = results{
myResults.enumerateStatistics(from: startDate!, to: endDate as Date) { statistics, stop in
if let quantity = statistics.sumQuantity(){
var date = statistics.startDate
let steps = quantity.doubleValue(for: HKUnit.count())
var id = 0
var dateToInsert = date
var today = Date()
var todaytwo = Date()
for index in 0..<stepy.step.count {
if dateToInsert != today {
id = index + 1
today.(Calendar.current.date(byAdding: .day, value: -1, to: today)
stepy.step.append(0)
}
if date == dateToInsert as Date {
today.add(Calendar.current.date(byAdding: .day, value: -1, to: today)
stepy.step.append(Int(steps))
id = index + 1
}
}
}
}
}
}
static var step = [365]
The above doesn't make sense. It does not create an array of 365 integers, it creates an array with one integer in it that is 365. What you need is
static var step: [Int] = []
which creates an empty array you can just append your results to
currently I believe I would overwrite the days which already has been inputted into the date at the second step enumeration?
because your code appends to the array, which is the same as in Java: myArrayList.add(element), this is not a problem.
Also I can't get the date code to compile properly, I just get the Date has no valid member called "add"
Correct, it doesn't. Also this line:
today.(Calendar.current.date(byAdding: .day, value: -1, to: today)
does not make any sense. That should be causing a compiler error to.
Anyway, I don't see what the point of all that is. Your outer loop presumably loops through the statistics, one per day, so just do your calculation and append to the array. It'll be oldest first, but you can then just reverse the array to get newest first.

How to order by time and time only in C#?

I have this recorded in SQL Server:
1- startTime (datetime): 5/2/2009 08:30 (brazilian time format: d/m/y)
2- startTime (datetime): 4/2/2009 14:30 (brazilian time format: d/m/y)
My application just records time... the date it's SQL that generates by itself be getting the date of today.
When I ask VS 2008 to order this datetime fields, it returns me that code #2 is before #1, because 4/2/2009 comes before 5/2/2009.
But, actually I want it to order by time only and ignore the date.
Is it possible??
Thanks!!
André
from d in dates
orderby d.TimeOfDay
select d;
or
dates.OrderBy(d => d.TimeOfDay);
Note: This will work as long as this is plain LINQ and not LINQ-to-SQL. If you're using LINQ-to-SQL to query your database, you'll need something that will translate to SQL.
You might also try fixing your app so it always saves the same base date with the time (like '01/01/1900' or whatever) and then you do not have to do all these slow and inefficient date stripping operations every time you need to do a query.
Or as Joel said, truncate or strip off the date portion before you do the insert or update.
Well, you can't really store a datetime without a date, but you could just store the total seconds as an double (using #florian's method).
You'd have to add a second method to convert this back to a date in your object, if you still need a date, such as:
public class BusinessObjectWithDate
{
private string _someOtherDbField = "";
private double _timeInMS = 0; // save this to the database
// sort by this? in sql or in code. You don't really need this
// property, since TimeWithDate actually saves the _timeInMS field
public double TimeInMS {
get { return _timeInMS; }
}
public DateTime TimeWithDate { // sort by this too, if you want
get { return (new DateTime(1900,1,1).AddMilliseconds(_timeInMS)); }
set { _timeInMS = value.TimeOfDay.TotalMilliseconds; }
}
}
var f = new BusinessObjectWithDate();
MessageBox.Show( f.TimeWithDate.ToString() ); // 1/1/1900 12:00:00 AM
f.TimeWithDate = DateTime.Now;
MessageBox.Show( f.TimeWithDate.ToString() ); // 1/1/1900 1:14:57 PM
You could also just store the real date time, but always overwrite with 1/1/1900 when the value gets set. This would also work in sql
public class BusinessObjectWithDate
{
private DateTime _msStoredInDate;
public DateTime TimeWithDate
{
get { return _msStoredInDate; }
set {
var ms = value.TimeOfDay.TotalMilliseconds;
_msStoredInDate = (new DateTime(1900, 1, 1).AddMilliseconds(ms));
}
}
}
Try this in your sql:
ORDER BY startTime - CAST(FLOOR(CAST(startTime AS Float)) AS DateTime)

Resources