Excel VBA - compare date in cell to current date - excel

(Excel 2010 VBA)
I have a cell (A1) containing a date in the format of mmm-yy ("Custom" category).
Foe example, if I enter 1/6/13 the cell shows June-13. That's fine.
In my VB macro I need to check this date whether the month is the current month and whether the year is the current year. I don't care about the day.

Does this help you:
Public Sub test()
d = Sheet1.Range("A1")
n = Now()
If Year(d) = Year(n) And Month(d) = Month(n) Then
MsgBox "It works"
End If
End Sub

Thanks to Dave and MiVoth I did :
Dim xdate As Date
xdate = Worksheets("sheet1").Range("A1")
If Month(Date) = Month(xdate) And Year(Date) = Year(xdate) Then
MsgBox "OK"
Else
MsgBox "not OK"
End If
That did the job!
Thank a lot to everyone,
Gadi

How about this:
Function MonthYear() As Boolean
MonthYear = False
If Not IsDate(Cells(1, 1)) Then Exit Function
If Month(Date) = Month(Cells(1, 1)) And Year(Date) = Year(Cells(1, 1)) Then
MonthYear = True
End If
End Function
The function returns true if month and year are the same as current date. If not it returns false.

Related

Excel Date to Text Day and Month always mix up

I'm exploring the use of Userform on my Excel VBA project and I want to create a form which will convert date from a DTPicker into text on a text box.
The reason for doing this is because I need the date to be in a specific format of yyyy/mm/dd to search an SQL query and the DTPicker value always default to dd-m-yyyy. Giving me no results in the query.
This is what I have so far:
Private Sub convertDate()
TextBox1 = DateFrmMac.Value
Me.TextBox1.Text = Format(Me.TextBox1.Text, "yyyy/mm/dd")
TextBox2 = DateToMac.Value
Me.TextBox2.Text = Format(Me.TextBox2.Text, "yyyy/mm/dd")
End Sub
During testing if the date is for example 29/1/2020, the conversion can work as intended. But if the day is below 12, like 8/11/2019, the day and month will mix up its values and give me the wrong date.
What can I do to prevent this from happening?
Private Sub convertDate()
Dim d As Date, strT1 As String, strT2 As String
strT1 = CStr(DateFrmMac.Value): Debug.Print strT1 'for 2019/12/5 use
d = DateSerial(Split(strT1, "/")(0), Split(strT1, "/")(1), Split(strT1, "/")
(2))
'for strT1 = "5/12/2019" use:
d = DateSerial(Split(strT1, "/")(2), Split(strT1, "/")(1), Split(strT1, "/")
(0))
Me.TextBox1.text = Format(d, "yyyy/mm/dd")
strT2 = CStr(DateToMac.Value)
d = DateSerial(Split(strT2, "/")(0), Split(strT2, "/")(1), Split(strT2, "/")(2))
Me.TextBox2.text = Format(d, "yyyy/mm/dd")
End Sub

Excel VBA - remove weekends from automatic timesheet print

I slightly amended some code I found online.
Purpose:
Click on a 'Print with Dates' button, then enter start date, and have Excel automatically generate/print a months worth of timesheets (much better than the previous spreadsheet having 6 weeks of pages to print, and you had to edit every date manually).
Issues:
It prints weekends, which wastes paper. Is there a way it can refer to a list of dates (weekends, public holidays), and not generate those for printing?
You'll see the date format is m/d/yyyy in the code, which strangely prints as dd/mm/yyyy (which is what I wanted). When the code was dd/mm/yyyy it was printing correctly (20/03/2019), but if it goes to the following month it was switching to American format m/d/yyyy (04/20/2019). I know it doesn't seem to make sense, but having it as m/d/yyyy actually prints as dd/mm/yyyy across any start/end dates. I'd like to know why, and also have dd/mm/yyyy in the code correctly printing across any date range.
CODE:
Sub PrintSheet()
Dim s As String
Dim d As Date
s = InputBox(Prompt:="Please enter the start date")
If Not IsDate(s) Then
MsgBox "Incorrect date", vbExclamation
Exit Sub
End If
For d = CDate(s) To DateAdd("m", 1, CDate(s)) - 1
Range("F2").Value = Format(d, "dddd")
Range("I2").Value = "" & Format(d, "m/d/yyyy")
ActiveSheet.PrintOut
Next d
End Sub
Cheers in advance :)
You can use the weekday function. It returns a number from 1 to 7. You can filter for 1-5 only for weekdays.
Sub PrintSheet()
Dim s As String
Dim d As Date
s = InputBox(Prompt:="Please enter the start date")
If Not IsDate(s) Then
MsgBox "Incorrect date", vbExclamation
Exit Sub
End If
For d = CDate(s) To DateAdd("m", 1, CDate(s)) - 1
If Weekday(d, vbMonday) < 6 Then
Range("F2").Value = Format(d, "dddd")
Range("I2").Value = "" & Format(d, "m/d/yyyy")
'MsgBox ("printing ") 'for testing
ActiveSheet.PrintOut
End If
Next d
End Sub

Textbox converts date into number

Private Sub TextBox1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
If Mid(TextBox1.Value, 4, 2) > 12 Then
MsgBox "Invalid date, please re-enter", vbCritical
TextBox1.Value = vbNullString
TextBox1.SetFocus
Exit Sub
End If
StartDate = DateSerial(Year(Date), Month(Date), Day(Date))
TextBox1.Value = Format(TextBox1.Value, "dd.mm.yyyy")
StartDate = TextBox1.Value
End Sub
This code works well for me and my colleagues to make sure the value entered in the textbox is a date. However, a colleague from a different country (but also with the dd.mm.yyyy date-format) gets weird results.
For example: If he enters 01.10.2017 the TextBox automatically format the date into 20.03.4917.
I suspect that in this case the entered value is not recognized as a date but as a number because 01102017 will transform into 20.03.4917 in Excel if you convert it as a date.
Does anyone have a suggestion or a guess how to work around this problem?
Thanks and best regards
You could split the date by . into an array ArrInput and then use DateSerial to make it a real date, that you can format.
Dim ArrInput As Variant
ArrInput = Split(TextBox1.Value, ".")
'StartDate = DateSerial(Year(Date), Month(Date), Day(Date)) 'I see no use in this at all
TextBox1.Value = Format$(DateSerial(ArrInput(2), ArrInput(1), ArrInput(0)), "dd.mm.yyyy")
StartDate = TextBox1.Value
The issue with Format(TextBox1.Value, "dd.mm.yyyy") is that here you let Excel guess which date format the string in TextBox1.Value is. It automatically casts into a number which is then converted into a string again.
To avoid date misunderstandings I recommend always to use the YYYY-MM-DD format according to ISO 8601. This is the only date format that is human readable and cannot be misunderstood. It also has benefits when sorting by dates that are actually strings.
To make your validation even more solid use something like:
Dim ArrInput As Variant
ArrInput = Split(TextBox1.Value, ".")
Dim ValidDate As Boolean
If UBound(ArrInput) = 2 Then 'make sure there are exactly two dots in the date
If ArrInput(1) > 0 And ArrInput(1) <= 12 And _ 'month <= 12
ArrInput(0) > 0 And ArrInput(0) <= 31 Then 'day <= 31
ValidDate = True
End If
Else
ValidDate = False
End If
If Not ValidDate Then
MsgBox "Invalid date, please re-enter in format dd.mm.yyyy", vbCritical
TextBox1.Value = vbNullString
TextBox1.SetFocus
Exit Sub
End If
TextBox1.Value = Format$(DateSerial(ArrInput(2), ArrInput(1), ArrInput(0)), "dd.mm.yyyy")
StartDate = TextBox1.Value
I do believe that your colleague enters the text string "01102017" without dots.
You might want to convert such kind of entries into a valid date:
' "01102017" => 01.10.2017 - 8 chars variant
' "011017" => 01.10.2017 - 6 chars variant
This needs to be done of cause prior to a date conversion.
Add a log of the input value to a free cell range and
have the workbook sent back to you:
...
Private Sub TextBox1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
Range("Z1").value = "'" & TextBox1.Value
If Mid(TextBox1.Value, 4, 2) > 12 Then
...
Check if only numbers are used:
How to check if a string contains only numbers?
and check the length of the string (6 or 8 chars variant) and check if the year part is within a valid range => try to convert to a date and offer it to the user.

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 date times chosen with date and time picker in Excel VBA

So i have a multi-page form that uses two "Date and time Picker" controls named StartDate and EndDate. I want to ensure that the user does not enter the StartDate later than the EndDate. I have the following questions. Is the StartDate.value initially "" or is it null? Is what's returned by StartDate a string or a date? Here is what I have so far.
As a side remark I am also somewhat confused by this line of code even after reading the documentation.
emptyRow = Application.WorksheetFunction.CountA(Range("A:A")) + 1
Private Sub StartDate_Change()
Dim emptyRow As Long
'Submits the date in the first empty row immediately since the form does not retain datepicker data after the page changes.
If (EndDate.Value) <> "" And CDate(StartDate.Value) >= CDate(EndDate.Value) Then
MsgBox ("Please enter a valid date")
MultiPage1.Value = 4
Else
Sheet1.Activate
emptyRow = Application.WorksheetFunction.CountA(Range("A:A")) + 1
Cells(emptyRow, 18).Value = StartDate.Value
End If
End Sub
DateTimePickers return Dates.
If you want to test that the EndDate is greater than StartDate, then code such as the following should do the trick:
(StartDate.Value < EndDate.Value)

Resources