Help with code.

  • Thread starter Thread starter myxmaster
  • Start date Start date
M

myxmaster

Thanks to Databasedev.co.uk I have the following code. However for
some reason the month portion does not work. Any ideas.

Private Sub cmdmonth_Click()
'Sets the Date From and Date To text boxes
'to show complete month (from start to end of current month)

Me!txtdatefrom = CDate("01/" & Month(Date) & "/" & Year(Date))
Me!txtDateTo = DateAdd("d", -1, DateAdd("m", 1, Me!txtdatefrom))

End Sub

Private Sub cmdyear_Click()
'Sets the Date From and Date To text boxes
'to show complete current year

Me!txtdatefrom = CDate("01/01/" & Year(Date))
Me!txtDateTo = DateAdd("d", -1, DateAdd("yyyy", 1, Me!
txtdatefrom))

End Sub
 
Hi

In the code you posted you a referencing other controls on your form
(txtdatefrom). You would be much better using your computor's date/time
setting like this.
The current month always finishes "now" and does the current year. There is
no need to over complecate things, so I have simply used Date() - which give
today's date (which "is" the end of the current month and year)


Private Sub cmdmonth_Click()
Me!txtdatefrom = DateSerial(Year(Date()), Month(Date()), 1)
Me!txtDateTo = Date()
End Sub

Private Sub cmdyear_Click()
Me!txtdatefrom = DateSerial(Year(Date())+0,1,1)
Me!txtDateTo = Date()
End Sub


Hope this helps
 
Where are you located? That code (which I consider to be bad code) assumes
that your regional settings are such that your Short Date format is
dd/mm/yyyy.

To be more universal, it should be:

Me!txtdatefrom = DateSerial(Year(Date), Month(Date), 1)

The line in cmdyear_Click will work, but only because 01/01 is January 1st
in both notations. For clarity, you might change it to

Me!txtdatefrom = DateSerial(Year(Date), 1, 1)
 
Actually, Wayne, what you're proposing doesn't do the same as the code
posted.

cmdmonth appears to set txtdatefrom and txtdateto to the beginning and end
of the current month, while cmdyear sets them to the beginning and end of
the current year. You're setting txtdateto to the current date, which isn't
the same.

Private Sub cmdmonth_Click()
Me!txtdatefrom = DateSerial(Year(Date()), Month(Date()), 1)
Me!txtDateTo = DateSerial(Year(Date()), Month(Date()) + 1, 0)
End Sub

Private Sub cmdyear_Click()
Me!txtdatefrom = DateSerial(Year(Date()),1,1)
Me!txtDateTo = DateSerial(Year(Date()), 12, 31)
End Sub
 
I was going along with the task that I thought they wanted. Maybe I should
just have corrected the code posted but it seemed a better idea to give the
correct code to do the job rather than trying to fix it.

The task I thought they wanted was

'Sets the Date From and Date To text boxes
'to show complete month (from start to end of current month)

'Sets the Date From and Date To text boxes
'to show complete current year

In both cases here "Me!txtDateTo" seemed (to me anyway) to be today, ie
Date().
 
Back
Top