DateValue and Format in a single formula - excel

I've been banging my head against the wall trying to figure out a dynamic filename problem.
I'm trying to extract the 6-digit date from a cell(J2) that includes time data, and use it to save my filename. The cell is formatted as "General".
The only formula I can get to work is this manual formula using an unoccupied cell (W2), and then deleting (ugly, I know):
Range("W2").Formula = "=DateValue(J2)"
RefDate = Format(Range("W2"), "m-d-yy")
NameofFile = "On Time Departure " & RefDate
Range("W2").Delete
The cell data is this
1/8/2015 2:00:00.000000 AM
I've tried nesting a DateValue function inside a Format function, but can't get it to work.
Any ideas?

Try this:
Dim RefDate As Date
RefDate = Range("J2").Value
NameofFile = "On Time Departure " & Format(RefDate, "m-d-yy")
EDIT
If J2 contains a string and not a date, like Christmas007 noted, try this:
Dim curDate As String
Dim RefDate As Date
curDate = Range("J2").Value
RefDate = DateValue(Left(curDate, InStr(curDate, " ")))
NameofFile = "On Time Departure " & Format(RefDate, "m-d-yy")

Related

Create a folder name with year and two digit month

I'm trying to create a folder with a the year and month of my choosing. My issue is that the month name (in this case January) keeps appearing as 1 instead of 01. I've tried several variations of the Format function everywhere in my code but I still get 1 returned. See below for code
Sub CreateFolder()
Dim sMonthName As String
Dim iMonthNumber As Integer
sMonthName = ThisWorkbook.Worksheets("Overview").Range("C2")
iMonthNumber = Month(DateValue("01-" & sMonthName & "-1900"))
MkDir "FILE PATH" & ThisWorkbook.Worksheets("Overview").Range("C3") & "." & iMonthNumber
End Sub
Cell C2 in the Overview Tab is where I have the month name, while cell C3 in the same tab is where I have the year. Is there a way to return the month as two digits? Let me know if you need any more information
Thank you.
You can simplify a bit by creating a date containing both the month and year, and then using Format$:
With ThisWorkbook.Worksheets("Overview")
Dim dt As Date
dt = DateValue("01-" & .Range("C2").Value & "-" & .Range("C3").Value)
End With
MkDir "FILE PATH" & Format$(dt, "yyyy.mm")

How to count emails within an hourly range?

My team uses outlook to track completed work. All work needs to be completed within 48 hours of receipt and we need to keep strict track of it. I've managed to put together a function that counts the emails that have fallen outside of the 2 day range, but the track needs to be kept down to an hour.
No matter how many configurations I try I was unable to get my code to count within hourly range. This is what my current code looks like:
Dim OOSLAitms As Outlook.Items
Dim DateDiff As Long
Dim Filter As String
Dim i As Long
DateDiff = Now - 2
Filter = "[Received] < '" & Day(DateDiff) & _
"/" & Month(DateDiff) & _
"/" & Year(DateDiff) & "'"
Set OOSLAitms = itms.Restrict("[FlagStatus] = 0")
Set OOSLAitms = OOSLAitms.Restrict(Filter)
For i = OOSLAitms.Count To 1 Step -1
Worksheets("Sheet1").Range("F4").Value = OOSLAitms.Count
Next
This manages to count all the emails received within the calendar day, but does not take hours of the day into account. So for example if we received 300 cases on Sunday, it will count all of them up to midnight, instead of only counting ones up to current time (4pm for example).
I need help incorporating hour/minutes criteria into my code on top of day/month/year if it's possible.
There is no Received property, you must use the ReceivedTime instead.
And if you need to get hourly range only, you must specify boundaries for the search criteria:
Dim searchCriteria As String = "[ReceivedTime]<=""" + dateTimeEnd + """ AND [ReceivedTime]>=""" + dateTimeStart + """"
Okay after playing around with it some more (and a generous amount of debug messageboxes) I've managed to get it to work using the following trick:
Created an output cell 'A11' on the first sheet running a =NOW() function formatted to "ddd dd/mm/yyyy hh:mm"
Created a cell 'A1' on the processing sheet that was running 'Sheet1!A11 - 2' formula. The reason why is that for some reason when doing 'Now - 2' through VBA, even with formatting it was always giving midnight. Doing it through autocalc in cells gives correct deduction down to a second.
The reason for formatting "dd dd/mm/yyyy hh:mm" is that this is the format that the "Received" column in outlook stores the receive times. Not providing that 'ddd' in front of the datetime string results in an automation error.
Final code looks like this:
Dim OOSLAitms As Outlook.Items
Dim DateDiff As Long
Dim Filter As String
Dim Today As String
Today = Format(ThisWorkbook.Sheets("Sheet2").Range("A1"), "ddd dd/mm/yyyy hh:mm")
Filter = "[Received]" & "<" & Today
Set OOSLAitms = itms.Restrict("[FlagStatus] = 0")
Set OOSLAitms = OOSLAitms.Restrict(Filter)
Worksheets("Sheet1").Range("F4").Value = OOSLAitms.Count

How to display sub string in reverse order but read from left to right in VBA

I am processing a .txt file in VBA.
Amongst other tasks, I need to read in a string representing a date and display the actual date in Excel.
A date string in the .txt file looks like "190223"
This represents 23/02/2019
My challenge is to get this done.
What I have done so far is:
' ... loop
With ActiveWorkbook.Worksheets(1)
' Other statements here
' Event date time
.Range("N" & i).Value = StrReverse(Mid(.Range(keyword.Offset(0, 4).Address), 1, 2) & _
"/" & Mid(.Range(keyword.Offset(0, 4).Address), 3, 2) & _
"/" & Mid(.Range(keyword.Offset(0, 4).Address), 5, 2))
End With
But I get the undesired output:
32/20/91 ' For a date string 190223 the desired output should be 23/02/19
Any help would be much appreciated.
Thanks in advance.
Convert it into a real date
You must extract year, month and day of that string and then convert this into a real date.
Then you can format the date to what ever date format you like. The value that is saved in the cell is then a real date value (not a string!) so you can calculate with it.
I highly recommend to read How Dates Work in Excel – The Calendar System Explained + Video to understand the background and why real dates are so important.
Here is an example:
Option Explicit
Public Sub ConvertDateExample()
Const InputStr As String = "190223"
Dim InputYear As Integer
Dim InputMonth As Integer
Dim InputDay As Integer
'extract year, month and day
InputYear = Left(InputStr, 2)
InputMonth = Mid(InputStr, 3, 2)
InputDay = Right(InputStr, 2)
'put it together to a real date
Dim RealDate As Date
RealDate = DateSerial(InputYear, InputMonth, InputDay)
'write the date into a cell
Range("A1").Value = RealDate
'format that cell to your desired format
Range("A1").NumberFormat = "dd/mm/yyyy"
End Sub

VBA Dates: Cannot Get the Format Correct

I'm trying to convert a date from something like Month/Day/Year to fully spelled out, like May 31st, 2014.
I hit a roadblock. Currently, I'm using this, and when the Message Box pops up, if has the correct date (May 31st, 2014), but once I write it to a cell, it converts to a number (From 5/31/14 to 41790). I'm lost and would love some assistance. Thanks!
Dim whatever as String
whatever = Format("5/31/14","mmmm dd, yyyy")
MsgBox whatever
ActiveWorkbook.Activesheet.Cells(1,1) = whatever
I have a program that uses the data from the sheet to run a Mail Merge in word, so I'm trying to get the entire date written out and not just simply format the cell, because Word takes the raw data (from what I know.)
When you are trying to display your format in the cell the correct way is to change the cell's number format and then set the cell's value
e.g.
Cells(1,1).NumberFormat="MMM DD, YYYY"
Cells(1,1).Value2= Date
To get a date in ordinal format, consider:
Public Function OrdinalDate(d As Date) As String
Dim dy As Long, mnth As String, yr As Long
Dim s As String
ar = Array("th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th")
dy = Day(d)
mnth = MonthName(Month(d))
yr = Year(d)
If dy > 10 And dy < 20 Then
s = "th"
Else
s = ar(dy Mod 10)
End If
OrdinalDate = dy & s & " " & mnth & " " & yr
End Function
Of course to remove the ordinal designation does not require VBA. With the ordinal form in B1, use:
=DATEVALUE(SUBSTITUTE(B1,MID(B1,FIND(" ",B1)-2,2),""))
and we are back where we started.

Converting a date string to date type in vba excel

I have a column of dates that converted from MS Project into excel as strings.
The format that converted is similar to the following: "March 31, 2014 8:00AM"
I want to convert "March 31, 2014 8:00AM" into type Date but, since it isn't formated MM-DD-YYYY it is not letting me.
Any suggestions?
If the value is in cell A2, for example, you could do the following:
=DATE(YEAR(A2),MONTH(A2),DAY(A2))
For a pure VBA solution, expanding on #cirrusone's suggestion, try this:
Public Sub lime()
Dim dt As Date
' Convert the date string into a Date value.
' Assumes your date string is in cell A1 in the active worksheet of the active
' workbook.
dt = CDate(Cells(1, 1))
' This will print the date with ".." as separators to show that it worked, i.e.
' it should be able to understand every part of the date string passed to it
' after having converted it to a Date value.
MsgBox DatePart("d", dt) & ".." & DatePart("m", dt) & ".." & DatePart("yyyy", dt) & ".." & _
DatePart("h", dt) & ".." & DatePart("n", dt) & ".." & DatePart("s", dt)
End Sub
I put some comments to explain what it's doing. DatePart is a useful function to extract bits of the date (and useful to know in general).

Resources