Get the month and year from today's date - excel

I am trying to get the month and year for today's date.
Sub automation()
Dim wsheet As Worksheet
Dim month As Integer
Dim year As Integer
Set wsheet = Application.Workbooks("try").Worksheets("try")
month = Application.WorksheetFunction.month(Date)
year = Application.WorksheetFunction.year(Date)
End Sub
My expected output is 5 for month and 2017 for year if today's date is 15/5/2017.

You may have some problem because you've shadowed some existing functions Month and Year with your variable names month and year. So, use different variable names:
Dim m As Integer
Dim y As Integer
And then either:
m = DatePart("m", Date)
y = DatePart("yyyy", Date)
Or:
m = month(Date)
y = year(Date)
In my Excel 2010 (not tested in 2013) while Month is a worksheet function, it's not exposed to VBA for some reason. If you want to use the WorksheetFunction instance of these, you can technically do it using the Application.Evaluate method, like so:
m = Evaluate("MONTH(""" & Date & """)")
y = Evaluate("YEAR(""" & Date & """)")
The built-in VBA.DateTime.Month and VBA.DateTime.Year functions, however, are available and that is what would be used in the second example above.
If you must for some reason retain the month and year variable names, then you need to fully qualify the function call to avoid error:
month = VBA.DateTime.Month(Date)
year = VBA.DateTime.Year(Date)

Change in your code like this:
Sub CurrentDate()
Dim currentMonth As Long
Dim currentYear As Long
currentMonth = Month(Date)
currentYear = Year(Date)
Debug.Print currentMonth; currentYear
End Sub
Month and Year are functions of the VBA.DateTime, do not use them for variable names.
In general, Application.WorksheetFunction does not have a function, related to current date, in contrast to VBA.DateTime.Month or VBA.DateTime.Year (or at least I did not find) any in the Excel Library.

dim this as date
this = Format(Date(), "yyyy")
this = Format(Date(), "mm")

Answering late but I wanted to reference the VBA documentation from microsoft's own page.
To get Month from date:
https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/month-function
Sample snippet:
Dim MyDate, MyMonth
MyDate = #February 12, 1969# ' Assign a date.
MyMonth = Month(MyDate) ' MyMonth contains 2.
To get Year from date:
https://learn.microsoft.com/en-us/office/vba/language/reference/user-interface-help/year-function
Sample snippet:
Dim MyDate, MyYear
MyDate = #February 12, 1969# ' Assign a date.
MyYear = Year(MyDate) ' MyYear contains 1969.

I like these answers, but I needed one that would contain both the month and year in the format (my use case is as an accountant). This was my solution:
Dim today As Date
today = Date ' Get the current date
Dim period As String
period = Format(today, "MM/YYYY") ' Convert the date to MM/YYYY

Related

DateDiff produces incorrect result when I set the dd value to 12 or less. The format of the date is mm/dd/yy

If the "dd" value of the date is "12" or less, on the StartDate variable, then the answer is incorrect.
Eg. When the StartDate is "03/12/19" and the EndDate value is "03/23/19", it yields -5573, which is obviously the incorrect answer.
If the "dd" value of the date is "13" or more, on the StartDate variable, then the answer is correct.
Eg When the StartDate is "03/13/19" and the EndDate value is "03/23/19", it yields 10, which is the correct answer.
I don't quite understand.
BTW the vba code is on a MacOS Excel Mac 2011.
Also, the weird thing is that this exact same workbook code works perfectly on my Win 7 PC Excel 2007 regardless of what value of the "dd" you use.!!!!
Sub DateDiffTest()
Dim StartDate As Date ' Declare variables.
Dim EndDate As Date ' Declare variables.
Dim Msg
StartDate = Format("03/12/19", "mm-dd-yy")
EndDate = Format("03/23/19", "mm-dd-yy")
Msg = "Days from today: " & DateDiff("d", EndDate, StartDate)
MsgBox Msg
End Sub
Your problems have to do with undeclared variables, and with VBA being US-Centric in its use of dates and with your Regional settings being inconsistent with what you are doing.
I suspect your Regional short date settings are YMD.
And what you think is dd, VBA thinks is mm.
So when the value is <= 12 it converts it to YMD
StartDate --> 2003-Dec-19
When it is >12, it cannot be a month, so VBA interprets it as a day, and converts it as a US-Centric date. So EndDate --> 2019-Mar-23
You should declare all variables, and also, when coding, use unambiguous dates.
eg:
Option Explicit
Sub DateDiffTest()
'OK to use US-centric MDY here
Const StartDate As Date = #3/12/2019#
Const EndDate As Date = #3/23/2019#
Dim Msg As String
Msg = "Days from today: " & DateDiff("d", EndDate, StartDate)
MsgBox Msg
End Sub
Another method of unambiguously declaring the dates:
Option Explicit
Sub DateDiffTest()
Dim StartDate As Date
Dim EndDate As Date
Dim Msg As String
StartDate = "2019-Mar-12"
EndDate = "2019-Mar-23"
Msg = "Days from today: " & DateDiff("d", EndDate, StartDate)
MsgBox Msg
End Sub
By the way, I don't understand why MS makes NOT requiring variable declaration the default. Select Tools/Options/Editor and check Require Variable Declaration. This will place Option Explicit at the start of any new module. To correct this module, enter it manually at the beginning.

Run code when the rows are between a date range

I want to run a code that transfers data from one sheet to another based on the year (eg 01/01/2018 - 31/1/2018).
The sheet contains 2 columns with dates, start_date and end_date stored as dates, so I did an If statement but it doesn't seem to "understand" the dates values that I stored previously.
'Dates columns
Dim fechaIniTarget As Variant
Dim fechaFinTarget As Variant
'Ini = start / Fin = end
Set fechaIniTarget = Range("D2")
Set fechaFinTarget = Range("E2")
If fechaIniTarget.Value = "01/01/2018" And fechaFinTarget.Value = "31/12/2018" Then
' function
MsgBox "PROCESO COMPLETO"
End If
I tried parsing the dates as integer but it still doesn't work.
You compare a date fechaIniTarget.Value against a string "01/01/2018". Use a real date with the DateSerial function instead to compare date against date.
If fechaIniTarget.Value = DateSerial(2018, 1, 1) And fechaFinTarget.Value = DateSerial(2018, 12, 31) Then
Also note that you used 2 times fechaIniTarget but I guess the second one should be fechaFinTarget.
Also don't use Variant if not necessary. Instead declare your variables As Range here:
Dim fechaIniTarget As Range
Dim fechaFinTarget As Range

VBA format date to get the previous month

I am fairly new at VBA and this seems like an easy task. I am just trying to get the current date substituting the current month for the previous one and a day constant as 21 so the result will have to be yyyy - (m-1) - 21
so far I had a couple of ideas and they work partially
Sub Test_Date()
Dim x As String
Dim p As String
p = Format(Date, "mm") - 1
x = Format(Date, "yyyy-" p "-21")
End Sub
if I MsgBx "p" comesback as what I want but, I dont know the correct syntax to concatenate them into one string
also
Sub Test_Date()
Dim x As String
x = Format(Date, "yyyy-(Format(Date, "mm") - 1)-21")
End Sub
You could also try this:
Function LastMonth() As Date
Dim d As Date
d = DateAdd("m", -1, Date)
LastMonth = DateSerial(Year(d), Month(d), 21)
End Function
Edit:
Format the returned date as needed:
Sub Test()
MsgBox Format(LastMonth, "yyyy-mm-dd")
End Sub
You could use DateSerial.
This accepts a year, month and day as its input and kicks out the date based on that.
So, DateSerial(2017,9,22) will give todays date.
To get the 21st of last month you'd use
DateSerial(Year(Date), Month(Date) - 1, 21)
Year(Date) returns 2017, Month(Date) returns 9.
Use the dateadd function (https://www.techonthenet.com/excel/formulas/dateadd.php):
DateAdd( interval, number, date )
or
DateAdd("m", 5, "22/11/2003")
Try
Sub Test_Date()
Dim d As Date
d = "22-09-2017"
d = DateSerial(Year(d), Month(d) - 1, 21)
End Sub

Compare dates with specific datetime format (VBA)

EDIT: Based on answers I was able to get min/max date from a range:
Dim dt As Date
dt = WorksheetFunction.Min(Range("D2:D300"))
But it's not enough. How do I use this function with an array instead of a range?
Original post:
I have the following columns:
The format is: DD/MM/YYYY HH:MM
I'm trying to get the soonest datetime from column one and the latest datetime from column two. In this case:
02/01/2017 6:07 (earlist datetime from the first column, 2nd of January)
02/02/2017 14:11 (latest datetime from the second column, 2nd of February)
I have a multidimensional array (myData) with the values from the cells and my functions are these ones:
Private Function GetLatestDateFromData() As String
Dim latestDate As String
Dim i As Long
latestDate = myData(1, ColumnsIndex(3) - 1)
For i = 1 To UBound(myData, 1) - 1
If latestDate < myData(i, ColumnsIndex(3) - 1) Then
latestDate = myData(i, ColumnsIndex(3) - 1)
End If
Next
GetLatestDateFromData = latestDate
End Function
Private Function GetEarliestDateFromData() As String
Dim earliestDate As String
Dim i As Long
earliestDate = myData(1, ColumnsIndex(2) - 1)
For i = 1 To UBound(myData, 1) - 1
If earliestDate > myData(i, ColumnsIndex(2) - 1) Then
earliestDate = myData(i, ColumnsIndex(2) - 1)
End If
Next
GetEarliestDateFromData = earliestDate
End Function
The problem is that my results are the following ones:
startingFrom = DateValue(GetEarliestDateFromData) 'returns 01/02/2017, 1st of February
untilDate = DateValue(GetLatestDateFromData) 'returns 01/06/2017, 1st of June
Seems I have a problem with the date formatting. Somehow, days and months are mixed. How do I fix it?
Thanks
EDIT: DateSerial (as suggested in a linked thread) does not apply here because I not only care about the date but the time as well. DateSerial only takes year-month-day as arguments.
To fix your dates use the format function, e.g.
date = Format(value, "MM\/DD\/YYYY")
More easily you could just compare the actual values (e.g. 02/01/2017 06:07 equals 42737,2548611111) which are independent of the displayed format.
Furthermore I'd suggest you use the WorksheetFunction.Max function which is the vba equvalent to excel Max-function, returning the greatest vaule in your range, something like:
date = WorksheetFunction.Max(your_used_range)

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

Resources