I am creating a calendar/tracker where a user inputs values into the "Work" column and the spreadsheet should essentially count those cells and the blank cells afterward in order to output values into the "Start Day, End Day, Work Length, and Cycle Length" columns. I'm looking for formulas that can calculate each value in these 4 columns.
Spreadsheet Image
Start Day (Green) corresponds with the first non-blank cell in the column.
End Day (Red) corresponds with the last non-blank cell after the Start Day.
Work Length (Blue) should count from the Start Day to the End Day.
Cycle Length (Purple, Orange, Yellow, Pink) is the length of days from the start day to the day before the start day of the next month.
My formulas only work in certain scenarios, like if there is only 1 group of values in a column (January and February). They doesn't work for when there are 2 groups of values in a month (March) or when one group starts at the end of the month and continues into the beginning of the next month (March/April).
The April values should be:
Start Day: Apr 24
End Day: Apr 27
Work Length: 4 Days
Cycle Length: *This can't be determined unless there was a May month (User will input this cycle length)
Spreadsheet link with current formulas: https://docs.google.com/spreadsheets/d/1WceKBNbyrb2rSCiIfVVpdt9l1fKIpPkqqxPataNHgoY/edit?usp=sharing
Alternative Method
You can also try using a Google Sheet Custom Function formula made possible by the Sheet's built-in scripting via Apps Script for a cleaner usage of the sheet formula. Here are the details:
CUSTOM_FUNC(month,array)
month will be the sheet cell that contains the month name
The array will be the range that contains the data of every Work columns
This custom formula will return the Start Day, End Day & Work Length automatically. E.g. on your March data, where you have two ranges of Work:
Note: This will also dynamically work on any months & ranges you define. E.g. you can also use =CUSTOM_FUNC(LEFT(H1,3),I3:I33) for the February month on cell J3.
To add the script below as a custom bound script in your spreadsheet file, you may follow the official guide here.
Script
/**
* Computes the "Start Day", "End Day" & "Work Length".
*
* #param {month,array} input The month value, range.
* #return the "Start Day", "Last Day" & "Work Length".
* #customfunction
*/
function CUSTOM_FUNC(month,array){
var out = [];
for (var arr, i = 0; i < array.length; i++) {
if (array[i] == "") {
arr = null;
} else {
if (!arr) out.push(arr = []);
arr.push([array[i],i+1]);
}
}
var res = out.map(x => x.toString().split(","))
return res.map(y => { return [month+" "+y[1],month+" "+y[y.length-1],(y[y.length-1]-y[1])+1+" days"]});
}
This script was derived from this existing answer to process the range values.
Demonstration
References
Custom Functions in Google Sheets
try X3:
=ARRAYFORMULA(LEFT(V1, 3)&" "®EXEXTRACT(REGEXEXTRACT(QUERY(
IF((W3:W="")*(V3:V<>""), "×", V3:V),,9^9), "(.+ \d+)"), "× (\d+)"))
Y3:
=ARRAYFORMULA(LEFT(V1, 3)&" "®EXEXTRACT(REGEXEXTRACT(QUERY(
IF((W3:W="")*(V3:V<>""), "×", V3:V),,9^9), "(.+ \d+)"), "\d+$"))
Z3:
=ARRAYFORMULA(COLUMNS(SPLIT(REGEXEXTRACT(REGEXEXTRACT(QUERY(
IF((W3:W="")*(V3:V<>""), "×", V3:V),,9^9), "(.+ \d+)"), "× (\d+.+)"), " "))&" days")
Related
I am working on redoing a Google Sheets spreadsheet my wife uses for work. Each sheet has a section for Monday, Tues, Wed, Thurs, and Sat (no programs on Friday and Sunday). Starting with early next year, the first sheet has Monday, January 2, Tuesday, January 3, and so on through Sunday, January 7.
What I am trying to do (instead of manually editing 52 different sheets) is come up with a function that iterates so that the second weeks' spreadsheet will show Monday, January 9, Tuesday, January 10, and so on. Each week would iterate the previous sheets corresponding day by 7.
Now, this is easy enough with a simple function, but where it gets complicated is when we get to the end of the month. I want to see if it is possible to iterate months as well. So, the week towards the end of the month would have Monday 29, Tuesday 30, Wednesday 31, but then Thursday Feb 1, and Saturday Feb 3.
Any ideas?
You can use this formula to create a list of dates in the format you want of a whole year (365 days):
=ArrayFormula(LAMBDA(FIRSTOFYEAR,MONTHS,WEEKS,
LAMBDA(DATES,
{DATES,BYROW(DATES,LAMBDA(DATE,
{
INDEX(WEEKS,WEEKDAY(DATE)),
INDEX(MONTHS,MONTH(DATE)),
DAY(DATE),
INDEX(WEEKS,WEEKDAY(DATE))&", "&INDEX(MONTHS,MONTH(DATE))&" "&DAY(DATE)
}
))}
)(BYROW(SEQUENCE(365,1,0),LAMBDA(NUM,FIRSTOFYEAR+NUM)))
)(
DATE(2023,1,1),
{"January";"February";"March";"April";"May";"June";"July";"August";"September";"October";"November";"December"},
{"Sunday";"Monday";"Tuesday";"Wednesday";"Thursday";"Friday";"Saturday"}
))
Result:
Which you can than use a QUERY() to easily remove what you don't need, such as:
(Assume the list of dates are placed in A:E)
=QUERY({$A:$E},"SELECT Col5 WHERE Col1 IS NOT NULL AND Col2!='Friday' AND Col2!='Sunday'",0)
result in something like this:
You can also use limit and offset to define the range to be shown in a QUERY(), such as:
(Assume the result of the last query is placed in F:F)
=QUERY(F1:F,"LIMIT 5 OFFSET "&((1-1)*5))
results:
With this formula, you only need to change the number x in ((x-1)*5) to the week number you want, and that will returns you the 5 days in the format you requested.
You can combine everything above to form something like this:
=ArrayFormula(
LAMBDA(SHOWWEEK,
LAMBDA(FIRSTOFYEAR,MONTHS,WEEKS,
LAMBDA(DATES,
LAMBDA(DATA,
LAMBDA(RESULTS,
RESULTS
)(QUERY({DATA},"SELECT Col5 WHERE Col1 IS NOT NULL AND Col2!='Friday' AND Col2!='Sunday' LIMIT 5 OFFSET "&((SHOWWEEK-1)*5),0))
)(
{DATES,BYROW(DATES,LAMBDA(DATE,
{
INDEX(WEEKS,WEEKDAY(DATE)),
INDEX(MONTHS,MONTH(DATE)),
DAY(DATE),
INDEX(WEEKS,WEEKDAY(DATE))&", "&INDEX(MONTHS,MONTH(DATE))&" "&DAY(DATE)
}
))}
)
)(BYROW(SEQUENCE(365,1,0),LAMBDA(NUM,FIRSTOFYEAR+NUM)))
)(
DATE(2023,1,1),
{"January";"February";"March";"April";"May";"June";"July";"August";"September";"October";"November";"December"},
{"Sunday";"Monday";"Tuesday";"Wednesday";"Thursday";"Friday";"Saturday"}
)
)(1)
)
in which all you need to do is changing the number inside the last () to the number of week you want, the 5 dates in the format you requested will be returned.
don't forget that you can always use INDEX() to define which value of an array do you want to return for your final result.
Since you have mentioned that What I am trying to do (instead of manually editing 52 different sheets) is come up with a function that iterates so that...,
We can go one step further, add a simple apps-script to get the sheet number count, we assume that your file only have 52 sheets, 1 for a week, and the sheets are arranged in ascending order (otherwise you will need another method), add this script into your spreadsheet:
function getSheetNum() {
const sss = SpreadsheetApp.getActiveSpreadsheet();
const sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
for (const [index,sheet] of sheets.entries()) {
if(sheet.getName() === sss.getActiveSheet().getName()) return index;
}
}
This function returns the index of sheet you are currently working on, start from 0, you can call it from your spreadsheet by simply type in =getSheetNum() in any cell.
p.s. if you have no idea what is apps-script, you may want to read some documentation: https://developers.google.com/apps-script/overview
Combining this custom function with our formula, like this:
=ArrayFormula(
LAMBDA(SHOWWEEK,
LAMBDA(FIRSTOFYEAR,MONTHS,WEEKS,
LAMBDA(DATES,
LAMBDA(DATA,
LAMBDA(DATA,
DATA
)(QUERY({DATA},"SELECT Col5 WHERE Col1 IS NOT NULL AND Col2!='Friday' AND Col2!='Sunday' LIMIT 5 OFFSET "&(SHOWWEEK*5),0))
)(
{DATES,BYROW(DATES,LAMBDA(DATE,
{
INDEX(WEEKS,WEEKDAY(DATE)),
INDEX(MONTHS,MONTH(DATE)),
DAY(DATE),
INDEX(WEEKS,WEEKDAY(DATE))&", "&INDEX(MONTHS,MONTH(DATE))&" "&DAY(DATE)
}
))}
)
)(BYROW(SEQUENCE(365,1,0),LAMBDA(ROW,FIRSTOFYEAR+ROW)))
)(
DATE(2023,1,1),
{"January";"February";"March";"April";"May";"June";"July";"August";"September";"October";"November";"December"},
{"Sunday";"Monday";"Tuesday";"Wednesday";"Thursday";"Friday";"Saturday"}
)
)(GETSHEETNUM())
)
be noticed that, instead of ((SHOWWEEK-1)*5), we do (SHOWWEEK*5) in this version, because the custom function we created using Zero-based array indexing.
results:
It will return a different week of dates in format you requested in each sheet.
Update 2022-12-30:
While I don't really understand why your week 1 start from 2nd of Jan and last for 7 days, is it 1st of Jan considered as Week 0 in that case??
Anyway, I come up with this formula which gives you a list of week count with date range for your reference.
According to the comments, if all you need is the week count of the year, you can simply use WEEKNUM(DATE):
=ArrayFormula(
LAMBDA(FIRSTOFYEAR,
LAMBDA(DATES,
LAMBDA(WEEKS,
LAMBDA(DATA,
BYROW(ARRAY_CONSTRAIN(DATA,MAX(WEEKS),4),LAMBDA(ROW,JOIN(" ",ROW)))
)(TO_TEXT(QUERY(QUERY({WEEKS,"Week "&WEEKS&":",DATES,DATES},"SELECT Col2,MIN(Col3),'~',MAX(Col4),Col1 GROUP BY Col1,Col2",0),"OFFSET 1 FORMAT Col2'm/d',Col4'm/d'",0)))
)(WEEKNUM(DATES))
)(BYROW(SEQUENCE(365,1,0),LAMBDA(NUM,FIRSTOFYEAR+NUM)))
)(DATE(2023,1,1))
)
The formula works in the same concept as my other formulas.
I am working on adding the time I spend on my habits using google sheets. If you look at this example sheet, I am keeping my individual habits in columns 3-8 (see the offsets on the first row).
To add the food related habits times (columns 5 and 6), I can use the range in offset function (see formulae in D17 below "Food").
The question is: how do I add the numbers for exercise and sleep (column offsets 4, 7, and 8)? The number of columns here could be 2, 3, or more! And they might not be consecutive.
Thanks for any pointers.
To sum entries of the rows whose columns are in the given array, I would use
=SUMPRODUCT(COUNTIF({5,8,9},COLUMN(D3:J3))*(D3:J3))
This is the formula for E18 in your spreasheet.
Since the columns might not be consecutive and there can be a variable number of them, I think it is appropriate to use an Apps Script custom function, and use the spread syntax to account for the variable number of columns.
Just open the script bound to your file, copy this function and save the project:
function HABIT_TOTALS(...habitIndexes) {
const sheet = SpreadsheetApp.getActiveSheet();
const headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
let output = [];
for (let dayIndex = 0; dayIndex < 7; dayIndex++) {
let dayValue = 0;
habitIndexes.forEach(habitIndex => {
const columnIndex = headers.indexOf(habitIndex) + 1;
const dailyHabitValue = sheet.getRange(3, columnIndex).getValue();
const dayHabitValue = sheet.getRange(4 + dayIndex, columnIndex).getValue();
dayValue = Number(dayValue) + Number(dailyHabitValue) + Number(dayHabitValue);
});
output.push([dayValue]);
}
return output;
}
Notes:
This function can be used as any in-built formula from Sheets (e.g. =HABIT_TOTALS(4,7,8)).
This function gets, as arguments, the indexes of the habits to retrieve (in this case 4, 7, 8), to be found on the first row in the sheet.
It loops through all days of the week (dayIndex), returning the total amount for each day. Because of this, there's no need to drag the formula down.
For each day, it finds the column index based on the habit index provided as an argument, and adds the values for Daily and for the current day to the total value for the day.
After retrieving the total amount for the day, this value is pushed to output, the value returned by this function.
This function could be used for the Food habits, just changing the arguments: =HABIT_TOTALS(5,6), or for any other combination.
Reference:
Custom Functions in Google Sheets
Spread syntax (...)
For the calculation concerning food you can try in cell D18
=sum(filter(filter($D$3:$I$11, regexmatch($C$3:$C$11, "Daily|"&text($C18, "ddd"))), regexmatch($D$1:$I$1&"", "5|6")))
and fill down.
The numbers at the end refer to the colum numbers you have in row 1. So in E18 (Sleep and excercise) you would have
=sum(filter(filter($D$3:$I$11, regexmatch($C$3:$C$11, "Daily|"&text($C18, "ddd"))), regexmatch($D$1:$I$1&"", "4|7|8")))
Of course, it is also possible to write the last part in a cell and then refer to that cell. That would mean you can enter in E18
=sum(filter(filter($D$3:$I$11, regexmatch($C$3:$C$11, "Daily|"&text($C18, "ddd"))), regexmatch($D$1:$I$1&"", D$17)))
and fill down AND to the right.
See if that helps?
I have a basic spreadsheet to keep track of time spent on an activity.
The idea is to capture a time range per cell. E.g. 10:00 - 12:30 means 2 hours and 30 minutes.
Breaks can be taken during the day. On resuming, a new time range is entered in a new cell.
I want to calculate the total time per day. E.g. Mon Jun 15 is 2.5 + 4.5 = 7 hours.
The algorithm I'm thinking of is more or less
for each cell that contains time ranges for the given day
start, end = split(cell, " - ")
diff_decimal = (end - start) * 24
total += diff_decimal
But I'm not sure how to do this with spreadsheet functions.
The starting point I have is using =SPLIT(B2," - ") but I'm already blocked since I'm not sure how to handle the return value.
P.S. The problem could be simplified by having multiple "start" and "end" columns with one value per cell. But I want to try the given format, which I prefer, before trying another approach.
This is Google Sheets solution, as Excel does not have regex formulas.
Try this formula (place it in G1, column G:G formatted as number):
={
"Total";
ARRAYFORMULA(
IF(
A2:A = "",
"",
MMULT(
IFERROR(
( TIMEVALUE(REGEXEXTRACT(B2:F, "-\s+(\S+)"))
- TIMEVALUE(REGEXEXTRACT(B2:F, "(\S+)\s+-"))) * 24,
0
),
SEQUENCE(COLUMNS(B2:F), 1, 1, 0)
)
)
)
}
If you format G:G as Duration then you can remove * 24 part.
UPD
Added ignoring of the wrong formatted cells with IFERROR - just 0 in this case.
Better add this custom conditional formatting rule for B2:F to mark (in red on the screenshot) time periods in the wrong format and go fix them:
=AND(B2 <> "", NOT(IFERROR(REGEXMATCH(B2, "\b(\d|[01]\d|2[0-3]):[0-5]\d\s*-\s*(\d|[01]\d|2[0-3]):[0-5]\d\b"), False)))
I have a google spreadsheet that's tracking the duration of a particular activity over time. Imagine it looks something like this:
date | start time | end time | duration
5/21/18 10:00 AM 10:30AM 30
5/21/18 11:30 AM 12:30PM 60
5/21/18 2:00 PM 2:30PM 30
5/23/18 11:30 AM 12:30PM 60
5/24/18 9:30 AM 11:30AM 120
I want to make a chart with the dates along the X axis and the duration along the Y axis. However, I want each date to just be shown ONCE, with the TOTAL SUM duration for that date. So, the bar for 5/21/18 should be 120 min (i.e. the total of the three 5/21/18 entries), the bar for 5/22 should be 0 minutes (since there is no entry), and the bar for 5/23 should be 60 min.
If I make a chart as is, it treats each row as a separate entry (so there are three separate bars for each of the 5/21/18 entries), which doesn't work for my purposes since I want to combine entries with the same date, and have entries for in-between dates that have no entries.
Thank you!
You need to add any missing dates in the series.
In this case there is only one day but it could just as easily be two, three or a month's worth of dates.
Credit for missing dates in series: "--Hyde", Google Docs Help Forum Automatically Insert Missing Rows And Fill Values.
Assumption: the range shown in the question starts in cell A1 on a sheet named 'so_53684341'.
1) Create a new data series, including any missing values
a) Create a new sheet.
b) Cell A1, insert =arrayformula( { "Date"; datevalue("21/05/2018") + row(1:4) - 1 } ).
c) Cell B1, insert =arrayformula( {"Start time","End time","Duration"; if( len(A2:A), iferror( vlookup( A2:A, {datevalue(left(substitute(so_53684341!A2:A, " ", "-"), 10 ) ), so_53684341!B2:D }, column(so_53684341!B2:D2), false ), { "", "", 0 } ), iferror(1/0) ) } )
This creates data in columns B, C and D. It duplicates the existing data on the original range. and puts a zero value in the Duration column for any non-existing date(s).
You can format the date column as appropriate.
2) Create a query to be used as the basis for the chart
a) Cell F1, insert =query(A2:D5,"Select A, sum(D) group by A label (A) 'Date', sum(D) 'Duration' ")
This creates a range F1:G5
3) Create a chart using the range F1:G5
Something like this
I'm using Google sheets for data entry that auto-populates data from my website whenever someone submits to a form. The user's data imports into my sheet with a timestamp (column A).
Using the Arrayformula function, I'd like a column to autofill all the dates of a timestamp within that month. For example, if 1/5/2016 is entered as a timestamp, I'd like the formula to autofill in the dates 1/1/2016 - 1/31/2016.
Additionally, I'd like other months added in the Arrayformula column. For example, if both 1/5/2016 and 2/3/2016 are entered in column A, I'd like the formula to fill in the dates from 1/1/2016 - 2/29/2016.
I know I can manually write in the dates and drag them down the column, but I have a lot of sheets, and using an Arrayformula will save me a lot of time. I've tried a similar formula in column B, but it doesn't autofill in the date gaps. Is what I'm looking for possible?
Here's a copy of the editable spreadsheet I'm referring to: https://docs.google.com/a/flyingfx.com/spreadsheets/d/1Ka3cZfeXlIKfNzXwNCOWV15o74Bqp-4zaj_twC3v1KA/edit?usp=sharing
Short answer
Cell A1
1/1/2016
Cell A2
=ArrayFormula(ADD(A1,row(INDIRECT("A1:A"&30))))
Explanation
In Google Sheets dates are serialized numbers where integers are days and fractions are hours, minutes and so on. Once to have this in mind, the next is to find a useful construct.
INDIRECT(reference_string,use_A1_notation) is used to calculate a range of the desired size by given the height as a hardcoded constant, in this case 30. You should not worry about circular references in this construct.
ROW(reference) returns an array of consecutive numbers.
A1 is the starting date.
ADD(value1,value2). It's the same as using +. As the first argument is a scalar value and second argument is an array of values, it returns an array of the same size of the second argument.
ArrayFormula(array_formula) displays the values returned by array_formula
As A1 is a date, by default the returned values will be formatted as date too.
Increment by Month
If anyone wants to be able to increment by month, here's a way I've been able to accomplish that. Your solution #ptim got me on the right track, thanks.
Formula
Placed in B1
First_Month = 2020-11-01 [named range]
=ARRAYFORMULA(
IF(
ROW(A:A) = 1,
"Date",
IF(
LEN(A:A),
EDATE( First_Month, ROW( A:A ) -2 ),
""
)
)
)
Result
ID Month
1 2020-11-01
2 2020-12-01
3 2021-01-01
4 2021-02-01
5 2021-03-01
I have an alternative to the above, which allows you to edit only the first row, then add protection (as I like to do with the entire first row where I use this approach for other formulas):
=ARRAYFORMULA(
IF(
ROW(A1:A) = 1,
"Date",
IF(
ROW(A1:A) = 2,
DATE(2020, 1, 1),
DATE(2020, 1, 1) + (ROW(A1:A) - 2)
)
)
)
// pseudo code!
const START_DATE = 2020-01-01
if (currentRow == 1)
print "Date"
else if (currentRow == 2)
print START_DATE
else
print START_DATE + (currentRow - 2)
Notes:
the initial date is hard-coded (ensure that the two instances match!)
ROW(A1:1) returns the current row number, so the first if statement evaluates as "if this is Row 1, then render Date"
"if this is row 2, render the hard-coded date"
(nB: adding an integer to a date adds a day)
"else increment the date in A2 by the (adjusted) number of rows" (the minus two accounts for the two rows handled by the first two ifs (A1 and A2). Eg: in row 3, we want to add 1 to the date in row 2, so current:3 - 2 = 1.
Here's a live example (I added conditional formatting to even months to assist sanity checking that the last day of month is correct):
https://docs.google.com/spreadsheets/d/1seS00_w6kTazSNtrxTrGzuqzDpeG1VtFCKpiT_5C8QI/view#gid=0
Also - I find the following VScode extension handy for syntax highlighting Google Sheets formulas: https://github.com/leonidasIIV/vsc_sheets_formula_extension
The Row1 header trick is courtesy of Randy via https://www.tillerhq.com/what-are-your-favorite-google-spreadsheet-party-tricks/
nice. thanks.
To get the list length to adapt to the number of days in the selected month simply replace the static 30 by eomonth(A1;0)-A1. This accommodates for months with 31 days, and for February which can have either 28 or 29 days.
=ArrayFormula(ADD(A1,row(INDIRECT("A1:A"&eomonth(A1;0)-A1))))
Updated for 2022:
This can now be done pretty easily with the SEQUENCE function, it's also a bit more adaptable.
Below will list all of the days in columns but you can swap the first 2 values to place in rows instead:
=SEQUENCE(1,7,today()-7,1)
More specific to your example, below will take the date entered (via cell, formula, or named cell) and give you the full month in columns:
=SEQUENCE(1,day(EOMONTH("2016-1-5",0)),EOMONTH("2016-1-5",-1)+1,1)