Excel vba get month from Date object - vba

I have a cell that gets filled with a date value. I then store it in a variable.
Sub dateTest()
Dim min_date As Date
min_date = ThisWorkbook.Worksheets("setup").Cells(22, 5).value
MsgBox (min_date)
End Sub
However, I would like to get a month and a day separately from that object. How to do it?

Month() and Day() are the functions that you need:
MsgBox (Month(minDate))
MsgBox (Day(minDate))
Microsoft Month Reference
Microsoft Day Reference
Another way is to use the Format function:
MsgBox Format(minDate, "m")
MsgBox Format(minDate, "d")

Related

VBA filter to hide fdates in the past not working

This code seems to filter all dates
Sub AdDate()
On Error Resume Next
ActiveSheet.ListObjects("TableAOrders").Range.AutoFilter Field:=1, Criteria1:=">" & Date
On Error GoTo 0
End Sub
All I want filtered are all dates in the past.
Any suggestions?
You bring dates starting from today; in fact Date is not used that way.
For the past dates your filter must be:
Criteria1:="<" & Now()

Excel_VBA highlight cells which has current date and different time

Need help to highlight the cell which contains today's date and a different time. The code that I wrote is here, but it can only highlight the cells with the current date.
Sub Datechoose()
Dim rCell As Range
With Worksheets("owssvr")
For Each rCell In .Range("A2:M20")
If rCell.Value = Date Then
rCell.Interior.Color = vbGreen
End If
Next
End With
End Sub
enter image description here
My aim is to highlight the cells with the current date(6/22/2018 and time).
Please help me out...
Highlight your cells and give them a conditional format.
With A1 selected the condition below will return TRUE if the date portion of the date/time value is equal to todays date.
=INT(A1)=TODAY()
As #HarassedDad said - 12 noon will be 43273.5 for 22nd June 2018.
INT(43273.5) cuts off the time leaving just the date to compare against your date value.
Wrap the 2 comparison values in a format to ensure Excel reads them in the same manner.
if isdate(rCell) then
If format(rCell.Value, "mm/dd/yyyy") = format(Date, "mm/dd/yyyy") Then
rCell.Interior.Color = vbGreen
End If
end if
Edit 1
you'll get an overflow error if the cell value is a numeric value outside of valid date parameters. You can avoid this by using the 'isDate' function to verify the cell is a date and can handle the format.

VBA get the last day of the month

I am pretty new to VBA. I have a range of dates and I need to write a code that will change the date in the cell to the last day of the month, used in a cell.
For example, if the date in the cell is 28/03/2018 I want it to be replaced by 31/03/2018. Any idea how I can do that?
You can also get the result you need with one line of code thanks to the Eomonth formula:
Range("A1") = Excel.Application.WorksheetFunction.EoMonth(Range("A1").Value2, 0)
You can use a user-defined function GetLastDayOfMonth() and pass the range you are interested in:
Option Explicit
Public Function GetLastDayOfMonth(ByVal myDate As Date) As Date
GetLastDayOfMonth = DateSerial(Year(myDate), Month(myDate) + 1, 0)
End Function
Public Sub TestMe()
Range("A1") = DateSerial(2000, 11, 11)
If Range("A1") = GetLastDayOfMonth(Range("A1")) Then
Debug.Print "LAST DAY!"
End If
Range("A1") = DateSerial(2000, 12, 31)
If Range("A1") = GetLastDayOfMonth(Range("A1")) Then
Debug.Print "LAST DAY! " & Range("A1")
Range("A1") = DateAdd("d", 1, Range("A1"))
End If
End Sub
The function checks the month and the year of the date, which is passed and it returns a new date, which is the last day of the month for this specific month and year.
Then in the TestMe version, you can compare a given date with the last day of the month, generated by the function. If the dates are the same, then this date is the last day of the corresponding month. Using DateAdd() it is possible to get the next day of the lastDay.
In the example above, I have explicitly written Range("A1") 9 times, thus it is probably easier to follow.
To get it really short you can use:
Sub test()
Dim myDate As Date
myDate = #3/28/2018#
Debug.Print DateSerial(Year(myDate), Month(myDate) + 1, 0)
End Sub
First, if you just want the last day of the month in Excel, use the =EOMONTH function, or see this SO post for the vba code:
VBA Run Macro Last Day of the Month
Rolling your own date time code is a bad idea. Don't do it.
This VBA function will calculate the last day of the month:
Public Function LastDay(ByVal d As Date)
Dim returnDate As Date
'First day of current month
returnDate = DateSerial(Year(d), Month(d), 1)
'Forward a month
returnDate = DateAdd("m", 1, returnDate)
'back one day
returnDate = DateAdd("d", -1, returnDate)
LastDay = returnDate
End Function
Works by jumping to the beginning of the month, adding a month then subtracting a day (so 1st Feb->1st Mar->28 Feb)
Like this in VBA:
Sub LastDayOfMonth()
Dim dates As Range, dt As Range
Set dates = Range("A1") //Update as required
For Each dt In dates
dt = Application.WorksheetFunction.EoMonth(dt, 0) //e.g. 01/06/2018 ~~~> 30/06/2018
Next
End Sub
VBA way:
Function LastDayOfMonth(ByVal d As Date)
LastDayOfMonth = DateSerial(Year(d), Month(d), 1)
LastDayOfMonth = DateAdd("m", 1, LastDayOfMonth)
LastDayOfMonth = DateAdd("d", -1, LastDayOfMonth)
End Function
Construct new date:
year: from old date
month: from old date
day: 1
Add 1 month to new date.
Subtract 1 day from new date.
Steps 2 and 3 save you from all complexities of date calculations.
For Excel way, please refer to the other answer.

Overflow when using DateAdd Excel VBA

I currently have an Excel sheet with a series of dates and a cell in a different sheet with the date when we last ran this macro.
I need to write a macro which checks if today's date is at least 32 days after the day we last ran the macro.
If so, I want to search the sheet with the series of dates and add 10-dates to a dates array.
The dates that we add represent each the closes n*30 days prior to today's date with n which goes from 1 to 10.
So basically 10-dates each representing a multiple of 30-days prior to todays date.
BUT, these dates must be present in the sheet with the series of dates mentioned above so if for example subtracting 30 days from today gives a date which does not exist in the series of dates above, we keep subtracting 1 additional day until we find a date which exists.
Hope this makes sense. I understand it is a bit confusing but I felt I had to give some context.
My code:
Sub date_diff()
Dim todDate
Dim dt
Dim diff As Long
Dim dates(0 To 9) As Date
Dim i As Long
todDate = Format(ActiveWorkbook.Sheets("Overview").Range("B6").Value, "mm/dd/yyyy")
' dt is the Date of last signaling
dt = ActiveWorkbook.Sheets("Overview").Range("B5").Value
diff = DateDiff("d", dt, todDate)
Dim rng As Range
Dim dtCell As Range
Dim currDt
If diff < 32 Then
MsgBox "Wait " & (32 - diff) & " days"
Else
For i = 1 To 10
currDt = Format(DateAdd("d", 20, todDate), "mm/dd/yyyy") ---> OVERFLOW HERE
Set rng = ActiveWorkbook.Sheets("US Stocks").Range("A:A")
' Find the day - Loop until you find one at least 30 days apart
Do While rng.Find(What:=currDt) Is Nothing
currDt = DateAdd("d", -1, currDt)
Loop
dates(i) = currDt
MsgBox i
Next i
End If
End Sub
Run-time error '6':
Overflow
I suppose the error is coming from how I handle or how the dates are interpreted in VBA. SEE CODE FOR OVERFLOW LINE. I am very new to VBA so am still learning these subtleties. FYI, the dates are in the "Short Date" format such as 1/13/15 (mm/dd/yy).

today's date, now function, macro variable

I currently have an input box for a variable that changes everymonth:
r_mo = Application.InputBox(prompt:="Enter the reporting month as YYYYMM (Eg:201604). Errors in this entry will result in errors in the results.")
This prompts an input box which one has to manually enter into... However, I want to automate this process and eliminate the need for an input box. Isn't there a now function in vba that will automatically generate today's date.
From a now, or system function all I want to do is extract the year in four digits and the month in two digits.
So for example, if we're in decemeber 2016
Sub asasdas ()
"Now function"
r_mo = YYYYMM ' automatically updated from "now function"
End Sub
I appreciate any help you can give me and thank you so much all.
Sub GetMonthYear
GetMonthYear = Year(Now) & Right("00" & Month(Now), 2)
End Sub
That'll do it. Returns the Year portion of Now() and concatenates it to the Month portion of Now(). Since Month will return a single digit for January to September, we wrap this by adding "00" to the Month and take the last two characters from the Right. For "9" we create "009" and take the last two characters for "09". For "10", we would create "0010" and take the last two characters for "10".
Sub GetYearMonthDay()
Dim GetYearMonthDay As String
GetYearMonthDay = Year(Now) & "-" & Right("00" & Month(Now), 2) & "-" & Right("00" & Day(Now), 2)
MsgBox GetYearMonthDay
End Sub
Please refer my answer given below
Sub UsingTheDateFunction()
'this is the standard 6/3/2021 format
Dim theDate As Date
theDate = Date
MsgBox theDate
End Sub