Day(Now) displaying January, 1900? - excel

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.

Related

Current date displayed in US rather than expected format as it was previously

This Excel VBA code does not work anymore.
Private Sub cmdAjouter_Click()
Dim ws As Worksheet
Dim lr As Integer
Set ws = ThisWorkbook.Sheets("Achats"
lr = ws.Range("A" & Rows.Count).End(xlUp).Row + 1
ws.Range("M" & lr).Value = Format(Date, "dd/mm/yyyy")
'[...]
End Sub
Today we are the 11th February 2020 , it should return the date as "11/02/2020" (French format) but it returns "02/11/2020" (US format).
It would be better to store it as the actual Date instead of a String and just use the .NumberFormat property instead to format it, that way is doesn't try to convert it again based on your regional settings.
ws.Range("M" & lr).NumberFormat = "dd/mm/yyyy"
ws.Range("M" & lr).Value = Date
Your way would probably work fine if the date was something like February 13, since then there is no way it would get confused about 13 being a month.

How to pass Access Column value in Holiday_array of Workday function in VBA?

How to pass the MS Access table column value in MS Excel 2010 Workday function in range list of holidays.
I have following table.
date_val
9/23/2016
9/24/2016
I want to use above list of dates in MS Excel 2010 Workday function in list of Holidays.
Example Workday(Today,addition of no of days, exclusion of Holidays)
As per above syntax of Workday function, I am looking
Workdays(Any Date, addition of one day, Exclude above listed MS Access Table column dates).
Can anyone assist how to pass MS Access Table column date value in holiday_array in Workday function?
Note : Code needs to implement in MS Access VBA environment.
As long as you pass an array to the Excel function you can call it from Access VBA.
General usage of function described here
Subroutine with Two examples
Public Sub TestWorkdayFunction()
Dim xlApp As Excel.Application
Dim startDate As Date
Dim numDays As Long
Dim arrDates As Variant
Dim nextDate As Date
Dim strDates As String
' Array of Holidays
arrDates = Array("1/1/2016", "3/25/2016", "3/28/2016")
Set xlApp = CreateObject("Excel.Application")
Debug.Print "Loading Array of Holidays From Preset List"
startDate = #12/30/2015#
Debug.Print startDate
numDays = 1
nextDate = xlApp.WorksheetFunction.WorkDay(startDate, numDays, arrDates)
Debug.Print "Next Work Day after " & numDays & ": " & Format(nextDate, "Long Date")
numDays = 2
nextDate = xlApp.WorksheetFunction.WorkDay(startDate, numDays, arrDates)
Debug.Print "Next Work Day after " & numDays & ": " & Format(nextDate, "Long Date")
Debug.Print "Loading Array of Holidays From Recordset"
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset("SELECT date_val FROM Table2", dbOpenSnapshot, dbReadOnly)
With rs
While Not .EOF
' Build comma separated list of dates (in Serial Date format)
' You could build date list with text format, enclosing in double quotes
strDates = strDates & DateSerial(Year(!date_val), Month(!date_val), Day(!date_val)) & ","
.MoveNext
Wend
.Close
End With
startDate = #3/24/2016#
Debug.Print startDate
' Remove Last comma
strDates = Left$(strDates, Len(strDates) - 1)
' Build Array of Holiday Dates
arrDates = Split(strDates, ",")
numDays = 1
nextDate = xlApp.WorksheetFunction.WorkDay(startDate, numDays, arrDates)
Debug.Print "Next Work Day after " & numDays & ": " & Format(nextDate, "Long Date")
numDays = 5
nextDate = xlApp.WorksheetFunction.WorkDay(startDate, numDays, arrDates)
Debug.Print "Next Work Day after " & numDays & ": " & Format(nextDate, "Long Date")
Set rs = Nothing
Set xlApp = Nothing
End Sub
Actual Debug Output
Loading Array of Holidays From Preset List
12/30/2015
Next Work Day after 1: Thursday, December 31, 2015
Next Work Day after 2: Monday, January 04, 2016
Loading Array of Holidays From Recordset
3/24/2016
Next Work Day after 1: Tuesday, March 29, 2016
Next Work Day after 5: Monday, April 04, 2016

How to get current month?

I can't get the current month.
It seems very simple to get the current year and day, as tested with the following:
MsgBox Year(Date)
MsgBox Day(Date)
MsgBox Year(Now)
MsgBox Day(Now)
How is it possible to show the current month as either a number (1, 2 etc.) or a full name?
I could use TODAY() in a cell and convert that in VBA with something like CurrentMonth = MonthName(Month(Sheet1.Range("A1"))) but I would like to do this directly in VBA for Excel.
Try,
debug.print Format(Date, "mmm") 'Mar
debug.print Format(Date, "mmmm") 'March
debug.print Format(Date, "m") '3
debug.print Format(Date, "mm") '03
Month(Now)
Returns the index number associated with the current month.
Jeeped's code below is the most compact, but to give you an idea of how indexes work, the following code will return the month name based on the index returned:
Dim months(11) As String
months(0) = "Jan"
months(1) = "Feb"
months(2) = "Mar"
months(3) = "Apr"
months(4) = "May"
months(5) = "Jun"
months(6) = "Jul"
months(7) = "Aug"
months(8) = "Sep"
months(9) = "Oct"
months(10) = "Nov"
months(11) = "Dec"
Dim nowMonth As Integer
nowMonth = Month(Now)
For i = 0 To 11
If nowMonth = (i + 1) Then
MsgBox (months(i))
End If
Next
Found an easier solution to get the current Month Name
Just use MonthName(Month(Now)) and assign it to a string.
Month(Now) gives you the month number and MonthName() uses that number to display the current month
A really helpful and simple way is to combine the format function together with date.
Examples (assuming today is Oct 23, 2019):
To get current month as a number as in original question:
MsgBox Format(Date, "mm")
^ Will return: 10
To get current month as short text:
MsgBox Format(Date, "mmm")
^ Will return: Oct
To get current month with full text:
MsgBox Format(Date, "mmmm")
^ Will return: October
You can combine these with days and years as well.
Additional examples:
MsgBox Format(Date, "dd-mmm-yyyy")
^ Will return 23-Oct-2019
MsgBox Format(Date, "dddd-mmmm-dd-yyyy")
^ Will return: Wednesday-October-23-2019
This is creating a custom format, so you can rearrange the dd, mm, yyyy areas as you see fit, such as:
MsgBox Format(Date, "yyyy/mm/dd")
^ Will return: 2019/23/10
Here is the best way I have found to do it:
Sub getMonth()
'MsgBox DatePart("m", Date)
'MsgBox Evaluate("MONTH(""" & Date & """)")
'MsgBox VBA.DateTime.Month(Date)
MsgBox Format(Date, "mmmm")
End Sub
Below is how I found the previous month based on the current month name, the assignment to monthNum is the piece needed to solve your question.
month = "February"
'****'
monthNum = Application.Evaluate("=MONTH(1&" & Chr(34) & month & Chr(34) & ")") 'Returns month #
'****'
If monthNum = 1 Then
monthNum = 12
Else
monthNum = monthNum - 1
End If
month = MonthName(monthNum) 'Returns January

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

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)

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