Date formatting - making dd/m/yyyy into dd/mm/yyyy - excel

I got a pretty simple question (but yet I've been stuck at it for some time now). Does anyone know how to make the date value from dd/m/yyyy into dd/mm/yyyy in a variable?
dim lastdaylastmonth as date
lastdaylastmonth = DateSerial(Year(Date), Month(Date), 0)
So this code, as of now, would return the last day of last month, so it will be 31/5/2015. For the sake of formatting, and a MID() down along the code to pull out the month string "05", I will need to convert the date to dd/mm/yyyy or 31/05/2015. Does anyone know the simple solution for this? I've tried:
lastdaylastmonth = format(DateSerial(Year(Date), Month(Date), 0), "dd/mm/yyyy")
and it still returns the same value! Any heroes out there? :D

Use String
Sub dural()
Dim lastdaylastmonth As String
lastdaylastmonth = Format(DateSerial(Year(Date), Month(Date), 0), "dd/mm/yyyy")
MsgBox lastdaylastmonth
End Sub

See this:
lastdaylastmonth = DateSerial(Year(Date), Month(Date), 0)
?lastdaylastmonth
31.05.2015
? format(lastdaylastmonth,"dd.mm.yyyy")
31.05.2015
? format(lastdaylastmonth,"mm")
05
The last output is a string, ready to be used in your code.

I prefer this method simply due to the fact that I have to deal with many different Excel versions around the world. Using format with "mm/dd/yyyy" will only work in the US (or whereever English is the defined language). In other counries the below code will still work.
Dim lastdaylastmonth As Date
'Last day of last month
lastdaylastmonth = Date - Day(Date) - 1
'Formatting it US-style regardless of international Excel or Windows settings
Debug.Print Right("0" & Day(lastdaylastmonth), 2) & "/" & Right("0" & Month(lastdaylastmonth), 2) & "/" & Year(lastdaylastmonth)

Related

Excel VBA not reading Date data the way I want

I have a program that is supposed to read the date from a cell. In that cell, I have given it the value of =NOW() just by typing it into the cell outside of VBA. The cell is formatted as a date and the format is: dd-month (for example; 28-Jan). When VBA reads the cell, it reads it as mm/dd/yyy 00:00:00 AM/PM. Is there a way to make my code read the month from the format I set? A section of my code is below:
dashpos = InStr(1, ThisWorkbook.Worksheets("Main").Cells(2, 15), "-")
curmonth = Right(ThisWorkbook.Worksheets("Main").Cells(2, 15).Value, dashpos + 1)
The cell containing the date is Cell(2,15). I then go on to use the three letters on the month to determine the following month using a Select Case curmonth.
If your format is mm/dd/yyy 00:00:00 AM/PM in the worksheet, then the month will always have two digits. Therefor:
curmonth = CLng(Left(ThisWorkbook.Worksheets("Main").Cells(2, 15).Text, 2))
Sub testDateExtraction()
'Next day in the format you use in the sheet (no matter, in fact...):
Debug.Print Format(ThisWorkbook.Worksheets("Main").Cells(2, 15).Value + 1, "dd-mmm")
'Next month
Debug.Print MonthName(Month(ThisWorkbook.Worksheets("Main").Cells(2, 15).Value) + 1, True)
'If you insists to use the string type data:
Dim strDate As String, strMonth As String
strDate = CStr(Format(ThisWorkbook.Worksheets("Main").Cells(2, 15).Value + 1, "dd-mmm"))
strMonth = Right(strDate, 3)
Debug.Print MonthName(Month(DateValue(Day(Date) & "-" & strMonth & "-2020")) + 1, True)
End Sub
I then go on to use the three letters on the month to determine the following month
If you want to determine the next month, you can just use DateAdd and Month. The cell format is irrelevant.
The following returns the month number:
Month(DateAdd("m", 1, Cells(2,15)))
If you want it as a three letter string, for some reason, then
Format(DateAdd("m", 1, Cells(2,15)), "mmm")

Day(Now) displaying January, 1900?

For whatever reason, everytime I try to use the Day(Now) function in VBA, it keeps displaying "1/9/1900". The Date function displays correctly, so I'm not sure what the issue here is.
Sub Test()
Dim datDay As Date
datDay = Day(Now)
MsgBox datDay
End Sub
Here's an image of the error.
The Day will be an integer somewhere between 1 and 31, depending on, well, the "day" part of the date returned by the DateTime.Now function.
The way dates are stored, they're essentially Double values, with the integer part being a number of days, and the decimal part being the time of day.
Debug.Print Format(CDate(0), "yyyy-mm-dd")
Output: 1899-12-30
We are June 10th, so the date value of 10 corresponds to January 9, 1900.
You want to store the value returned by Day, Month, and Year functions, into Long integer variables; not Date.
Dim datDay As Long
datDay = DateTime.Day(DateTime.Date) ' datDay is 10 because DateTime.Date is 2019-06-10.
Note: while unqualified Day, Date, Month, and Year (and others) functions work perfectly fine, it's probably a good idea to qualify them with the module they are declared in (VBA.DateTime), to avoid potentially confusing ambiguities, e.g. Date is both the name of a property of the DateTime module, and it's also a data type (Dim foo As Date), and the two have very different meanings.
Try:
Option Explicit
Sub Test()
Dim datDay As Date
datDay = Date
MsgBox "Whole date: " & datDay & vbNewLine & _
"Month: " & Month(Date) & " (" & Format(Date, "mmmm") & ")" & vbNewLine & _
"Day: " & Day(Date) & " (" & Format(Date, "dddd") & ")"
End Sub
Result:
Replace
datDay = Day(Now)
with
datDay = Day(Now())
Not sure if this will fix the problem, but =Day(Now()) works correctly when typed directly into a cell.
Your problem is datDay is typed as a Date. =Day(Now()) returns just 10, as today is June 10th. As a full Date value, this is 1/10/1900, since Excel indexes day 0 as 1/0/1900.

Finetuning how the date is displayed after adding it to a cell

Just starting to write VBA here, raw beginner.
I'm looking for help in fine-tuning my displayed date. With the help of examples I found online, I have a module to put the name of the last month, and year, into a cell in my Totals worksheet, and it does what I need to get by.
To make it perfect, though, I'd like to change what date info is displayed.
This is Excel in Office 365. I've searched for examples online and read tutorials about using DateAdd but can't find this anywhere. (Part of the problem is I'm so new, I don't know how to phrase things in vba-speak to find good answers!)
What I use now:
Sub PreviousMonthBasedOnCurrentMonth()
Dim ws As Worksheet
Set ws = Worksheets("Totals")
ws.Range("A1") = Format(DateAdd("m", -1, Date), "mmmm yyyy")
End Sub
This now inserts "February 1, 2019" into the cell - which is enough data for me to confirm which month I'm looking at. But ideally I'd like "February 1-28, 2019" (Or, say, "October 1-31, 2019" if I'm running this while in Nov).
How do I get the 'first day of month - last day of month' portion to display? Is that part of DateAdd, or more coding from scratch?
Not sure how to write something like that myself. Pointers to where to start would be great.
Try something like this:
Dim dt, dt2
dt = DateAdd("m", -1, Date) 'this time last month
dt2 = DateSerial(Year(Date), Month(Date), 1) - 1 'last day of previous month
Debug.Print Format(dt2, "mmmm") & " 1-" & Day(dt2) & " " & Format(dt2, "yyyy")
Note Excel will not see this as a date though...
You can also do it on one line this way:
Debug.Print Format(DateAdd("m", -1, Date), "mmmm") & " 1-" & Format(CDate(WorksheetFunction.EoMonth(DateAdd("m", -1, Date), 0)), "dd, yyyy")
OR
Debug.Print Format(DateAdd("m", -1, Date), "mmmm") & YourPartialDateVariableHere & Format(CDate(WorksheetFunction.EoMonth(DateAdd("m", -1, Date), 0)), "dd, yyyy")

Formatting a number to two digits even if the first is a 0 vba

I would like to be able to use VBA to display any number between 1-24 as a 2 digit number. Obviously the only ones that have a problem with this are 1-9 which I would like displayed as 01, 02, 03, etc. Is there a way to perform this?
You cannot format an integer variable, you need to use a string variable for formatting.
You can convert the day part of a date to a format with leading zeros using the Day function to extract the day number from the date, and then using the Format function with a "00" format to add a leading zero where necessary
Format(Day(myDate), "00")
myDate is a Date variable containing the full Date value
The following macro can be used as a working sample
Sub Macro1()
Dim myDate As Date
myDate = "2015-5-1"
Dim dayPart As String
dayPart = Format(Day(myDate), "00")
MsgBox dayPart
End Sub
Sure you can format an integer, you just convert it to string within the format command:
formattedIntAsString = Format(Cstr(intValue), "00")
I did it like this:
number_item = 2
number_item = WorksheetFunction.Text(number_item, "00")
This will do the job.
I know it's old, but, to answer the question as clarified, I would use in the built in date formatting functionality.
To modify DeanOC's answer:
Sub Macro1()
Dim dateDate As Date
Dim strDate As String
Dim strDay As String
dateDate = "2015-5-1"
strDate = Format(dateDate, "mm/dd/yy") ' = "05/01/15"
strDay = Format(dateDate, "dd") ' = "01"
MsgBox "The two digit day of """ & strDate & """ is """ & strDay & ""."
End Sub

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