Apologies for yet another date/time related post. I haven't got my head around this yet, so any comments welcome. Executive summary: Excel can be used to work with small elapsed times (athletic event times, and so on), but Sheets can't, because you need to write a script to display small times, and the script screws something up so that Sheets no longer treats the cell as a time when the time is later manually changed.
The times I need are normally short, in the region of a couple of minutes, with seconds to 2 decimal places. I have to do arithmetic on these times (normally only comparisons to another time).
We currently store everything in Excel, which works fine. If you define a custom display format in a range, and then enter times as something like 2:43.02
(2 mins, 43.02s), then the cell still contains a time, and Excel can do arithmetic on those times.
I then upload the Excel spreadsheet, and open it in Sheets. There is no built-in formatting extension, as there is in Excel, so I have to use an extension function to display the time as 2:43.02
, for example (see below; the function calls setNumberFormat
). In the new Sheets version of the document, Excel times are still times, and comparison works, and everything looks right.
Here's the problem. Everything only works until you manually enter a new time into a Sheets cell. If I enter 2:41.05
, for example, the cell no longer contains a time object, and all arithmetic is broken. So, I can't use Sheets to replace Excel. I have to keep everything in Excel and upload it occasionally, keeping the Sheets version as read-only.
There's some magic in Sheets which determines whether a cell contains a date or not. If I use a built-in time format, then Sheets knows it's a time, and can do arithmetic if the time is manually changed. If I change the time format using the function below (from here), then that magic is lost, and I can't manually change the time.
function EditFormat() {
var oldname = SpreadsheetApp.getActiveRange().getNumberFormat();
var name = Browser.inputBox("Current format (blank = no change):\r\n"+ oldname);
SpreadsheetApp.getActiveRange().setNumberFormat((name=="")?oldname:name);
}
Question: is setNumberFormat
broken? Is there a better way to do all this? Can I do something else in the script which retains the cell's magic status as a time? Or do I have to go back to Excel?
Thanks.