How to make time as variable in VBA? - excel

I need to title graphs dynamically in following pattern:
date time symbol
I take these values as variables from certain cells in worksheet and I'm stuck with a time variable. It doesn't read hour as, for example 09:26:51 but as decimal value 0,3..etc
Last thing I came up to is:
Dim tim As Date
tim = TimeValue(Range("b2").Value)
I believe it's an easy one to solve.

You can use the Format() function for example:
MyNewTime = Format(MyTime, "h:m:s") ' Returns "17:4:23".
MyNewtime = Format(MyTime, "hh:mm:ss AMPM") ' Returns "05:04:23 PM".

Related

Using Unix US Formatted Date-time-year for calculations in Excel

I have dates that are formatting using the default time formats for Bash (echo $date) for example:
Fri Dec 24 07:35:41 EST 2021
I cannot change this behavior as I don't have permissions to alter our IT solution. I need to be able to load these dates into a UK localised Excel, but any attempts to use the usual Text To Columns DMY approach doesnt work due to the Day, time zone, time etc.
Is the only way to extract the data and re-assemble it or is there a simpler solution?
Try this function . write it to module and call from any cell . Like =makeDateFromStr(A1)
Function makeDateFromStr(ByVal someDate As String) As Date
On Error Resume Next
Dim var As Variant, Mu As Long
var = Split(someDate, " ") ' array to hold all parts of the string-date
Mu = (InStr("JanFebMarAprMayJunJulAugSepOctNovDec", var(1)) + 2) / 3 ' a way to make short string month (Dec) to number
makeDateFromStr = DateSerial(var(5), Mu, var(2)) & " " & TimeValue(var(3)) ' putting all together
On Error GoTo 0
End Function
As far as I can see, if we get rid of the EST and the week day FRI, we can get a valid date value. Note: If you want the weekday, you can use the function WEEKDAY() to get the value 6, which is Friday. (1 is Sunday).
So, to get rid of the weekday, you can use the RIGHT() function.
All weekdays are 3 letters and a space, so we need to get rid of the 4 first characters, like so:
=RIGHT(A1;LEN(A1)-4)
You can put this just underneath your example time, so place this in cell A2.
To remove the EST is a bit more tricky, we need to know where in the text EST is. For this, we use FIND():
=FIND("EST ";A2)
Now we know at which position the text "EST " appears in A2.
Then we can use a simple REPLACE() function, to replace "EST " with nothing. Like so:
=REPLACE(A2;FIND("EST ";A2);4;"")
Note: The 4 refers to the length of "EST ".
This worked for this example, so you can try it out with different data. Just comment below if it isn't working correctly, and with what data and I'll look into it.
Put a date in A1
Put =RIGHT(A1;LEN(A1)-4) in A2
Put =REPLACE(A2;FIND("EST ";A2);4;"") in A3
You could also merge it into 1 cell:
=REPLACE(RIGHT(A1;LEN(A1)-4);FIND("EST ";RIGHT(A1;LEN(A1)-4));4;"")
You could then place this next to the date in A1, so in B1, and drag this formula down for ALL your imported dates. Now it should work for all of your dates.
You could also copy their values and replace the original dates, then remove the formulas, and you will have the same layout and functionality you were expecting from the beginning!

VBA Date + TimeValue returns no time

I have a date and time which I assemble into a date + time from strings in the form
date_string = "2020-12-30" 'yyyy-mm-dd
date_code = CDate(date_string)
time_string = "00:00:00" 'hh:mm:ss
time_code = TimeValue(time_string)
date_time = date_code + time_code
Commonly the return looks like 05.01.2019 11:00:00, which is what I expect.
The returned values also all check out as TRUE if I test with IsDate(date_time)
Whenever the time is 00:00:00 however, I only get the date returned with no time appended. I dont quite understand this, since TimeValue(time_string)returns 00:00:00.
So it must be an issue when combining date and time to a date + time string.
Can someone please enlighten me why midnight somehow does no exist in Excel VBA or where my error in creating the time code is?
EDIT:
I try to explain my situation a bit better:
I do this date date/time stuff in code and then but the result in an array in a loop. Only later on it is written to a cell in a table.
By the time is is written into a cell, even custom formatting the cell to "DD.MM.YYYY hh:mm" does not show the time as it is completely missing from the cell value.
Do I neet to apply a format at the point of date_code + time_code?
Sometimes the answer can be so simple. Thanks to Variatus and Paul I checked formatting out.
I applied a date_time = Format(date_code + time_code, "dd.mm.yyyy hh:mm") in my code. Using this, my code runs as expected and 00:00:00 appears as expected, even in the cell values of the Excel table.
When you enter an integer, like 43930, in a cell Excel will record the number as an integer, just as you entered it. You can then proceed to format the cell as #,##0.000 and thereby make the number display as 43930.000. Or you can format that very same number as custom dd mmm yyy hh:mm:ss and display it as 09 Apr 2020 00:00:00. The point is that Excel chose to record the number in its most efficient way, as an integer.
So, if you enter a DateValue + TimeValue which, together, amount to an integer Excel will record the integer correctly. The format in which that integer is displayed in your worksheet is a matter for cell formatting.

Why is midnight added to my array instead of the date?

I declare a date array as such:
Dim date_array() as Date
It's goal is to store dates found in a range.
Dim date_range As String
I declare it as a string because I have an input form where a user specifies the range of dates (e.g. A1:A5).
Then I calculate how many cells are in the range and specify the size of the date_array.
ReDim date_array(Range(date_range).Cells.count)
So far so good. I then loop through each element of date_array and add the date from the range.
Dim i As Long
i = 0
For Each r In ThisWorkbook.Worksheets("Name").Range(date_range)
date_array(i) = r.Value
i + i + 1
Next r
However, when I do a MsgBox(date_array(i)) during this loop, I get a value of 12:00:00 AM instead of the date I want (e.g. 2/2/2019) which tells me something is getting lost in translation.
I get the correct result if I do MsgBox(r.Value)... so it seems like something about the way I'm assigning the date to the array is wrong.
Has anyone run into an issue like this before? How can I fix it?
The larger goal is to map data between two files using date + a naming convention as a validation, so I need the array to store the correct date in a date format so it can be compared to a different cell value later.
Thank you,

Excel Substrings

I have two unordered sets of data here:
blah blah:2020:50::7.1:45
movie blah:blahbah, The:1914:54:
I want to extract all the data to the left of the year (aka, 1915 and 1914).
What excel formula would I use for this?
I tried this formula
=IF(ISNUMBER(SEARCH(":",A1)),MID(A1,SEARCH(":",A1),300),A1)
these were the results below:
: blahblah, The:1914:54::7
:1915:50::7.1:45:
This is because there is a colon in the movie title.
The results I need consistently are:
:1914:54::7.9:17::
:1915:50::7.1:45::
Can someone help with this?
You can use Regular Expressions, make sure you include a reference for it in your VBA editor. The following UDF will do the job.
Function ExtractNumber(cell As Range) As String
ExtractNumber = ""
Dim rex As New RegExp
rex.Pattern = "(:\d{4}:\d{2}::\d\.\d:\d{2}::\d:\d:\d:\d:\d:\d:\d)"
rex.Global = True
Dim mtch As Object, sbmtch As Object
For Each mtch In rex.Execute(cell.Value)
ExtractNumber = ExtractNumber & mtch.SubMatches(0)
Next mtch
End Function
Without VBA:
In reality you don't want to find the : You want to find either :1 or :2 since the year will either start with 1 or 2This formula should do it:
=MID(A1,MIN(IFERROR(FIND(":1",A1,1),9999),IFERROR(FIND(":2",A1),9999)),9999)
Look for a four digit string, in a certain range, bounded by colons.
For example:
=MID(A1,MIN(FIND(":" &ROW(INDIRECT("1900:2100"))&":",A1 &":" &ROW(INDIRECT("1900:2100"))&":")),99)
entered as an array formula by holding down ctrl-shift while hitting Enter would ensure years in the range 1900 to 2100. Change those values as appropriate for your data. The 99 at the end represents the longest possible string. Again, that can be increased as required.
You can use the same approach to return just the left hand part, up to the colon preceding the year:
=LEFT(A1,-1+MIN(FIND(":" &ROW(INDIRECT("1900:2100"))&":",A1 &":" &ROW(INDIRECT("1900:2100"))&":")))
Here is a screen shot, showing the original data in B1:B2, with the results of the first part in B4:B5, and the formula for B4 showing in the formula bar.
The results for the 2nd part are in B7:B9

How to convert and compare a date string to a date in Excel

= "7/29/2011 12:58:00 PM" > NOW()
I'd like this expression to return FALSE and yet it returns TRUE.
I know I can break apart my datetime into a date and a time and add them together as follows:
= DateValue("7/29/2011") + TimeValue("12:58:00 PM") > NOW()
But, this seems inelegant to me. I want a simple function or approach that looks nice and I feel certain that it's out there but I just can't find it.
I also know there is a VBA function called CDate which can typecast the string into a datetime and that would be perfect. But, I don't see how to call a VBA function in an excel cell.
Multiply the string by one and the comparison function will work:
= 1*"7/29/2011 12:58:00 PM" > NOW()
The answer to your question is tightly related to #Jean-François's comment: Why is the date being interpreted by Excel as a Text and not by a date?
Once you find it out, you'll be able to do the comparison.
If that's because the string is being retrieved as a text, you can simply multiply it by one and the comparison function will work, then. But it applies only in case the string format is a valid date/time format in your regional settings.
You could wrap the VBA call in a custom function:
Function ReturnDate(ByVal datestr As String) As Date
ReturnDate = CDate(datestr)
End Function
which you can use just like a formula in your sheet.
I'm upgrading the following from a comment to an answer:
Unless you have a very specific reason to do so (and right now I can't think of any), dates (and other values) really shouldn't be "hard-coded" in cells as strings like you show. Hard-coding the string like that makes it invisible and inflexible. The user will just see TRUE or FALSE with no indication of what this means.
I would just put your date 7/29/2011 12:58:00 PM in a cell on its own e.g. A1, and set the cell's format to some date format. Then you can say = A1 > NOW().
Contrary to #jonsca's and #Tiago Cardoso's answers, this answer doesn't address your specific question, but then again, what you are asking seems like really bad practice to me!
The simplest way to do this is to make a VBA function that uses CDATE and return your comparison. Then, call the function from an excel cell.
The VBA Function
Public Function compareDate(ByVal inputDate As String) As Boolean
compareDate = CDate(inputDate) > Now()
End Function
Then in your spreadsheet, just do
=compareDate("YOUR DATE")
The function will return "FALSE" if it is older and "TRUE" if it is newer than Now()

Resources