I have the following unbound fields in a form:
txtCBDate - format "Medium Date" - My PC localization settings for date: "dd/mm/yyyy"
txtCBRemarks.
In VBA, for cmdSAVE_Click event, I have the following code:
Dim myDate as Date
Dim myRemarks as String
myDate = txtCBDate.Value
myRemarks = txtCBRemarks.Value
Sql = insert into CB (CBDate, CBRemarks) values (myDate, myRemarks)
db.Execute(SQL)
The values are inserted into the table, CB. However, the inserted date is a wrong date, i.e., not the date entered by me in the form. e.g., if I entered "20-02-2016", the date saved in the database is "11-07-1894". The other dates entered are also saved correspondingly with reference to the year 1894.
I tried "Compact and Repair Database" as well as deleting the textbox and re-designing the form, but to no avail. Where am I going wrong?
Usually there are different formats in your machine's date and time settings. For example, on my machine, short date is dd/MM/yyyy and long date is dd MMMM yyyy (I don't seem to have a medium date format visible in my settings).
I would suggest trying changing the format of the text box to short date, on the assumption that the date format in your settings is actually your short date format opposed to your medium date format.
While debugging the value of variable 'myDate', as suggested by Mark, I found that in the Insert statement, myDate was not enclosed in single quotes.
Sql = insert into CB (CBDate, CBRemarks) values (' " & myDate & " ', & " ' myRemarks & " ')
I only had the double quotes "" enclosing the variables. After enclosing the variables in single quotes as well, the issue got resolved.
I am sorry that I did not make a mention regarding the single/double quotes in my earlier post. Thanks in particular to Mark C, and, also to UberDoodles for their suggestions.
Related
My computer's regional date setting is dd/mm/yyyy. I am using MS Access. I would like to insert records into a database using the SQL INSERT INTO statement. When I try to insert a date using the #dd/mm/yyyy# syntax, and view the resulting record in the table after, it turns out the record displays the date in the format mm/dd/yyyy instead, but ONLY for the first 10 days of the month; if the day is 11 onwards, the record displays dd/mm/yyyy as intended.
For example if in SQL code I input #09/02/2022#, the table will display the record with the date 02/09/2022 instead. However if my SQL code is#11/02/2022#, then the correct order 11/02/2022 is shown in the record.
Please help.
Ok, the way this works?
You don't have to care, know, or think about the users regional format settings.
So, if you drop some control on a form? Just make sure that control is set to a date type format. Your done.
BUT ONE big whopper:
IN ANY AND ALL cases, your string based date format MUST be in USA format. Or you can use ISO date format.
dim MyDate as Date
MyDate = me.InvoiceDate
So, now we have a internal format date variable. How to insert into a table?
dim strSQL as string
strSQL = "INSERT INTO tblInvoice (InvoiceNum, InvoiceDate, InvoiceAmount " & _
"VALUES (1234, " & quDate(MyDate) & ",50)"
So, you ALWAYS format the date value into USA format.
You can type that format command over and over, but that fast becomes tiring.
so, I use a little helper function:
Public Function quDate(dt As Date) As String
quDate = "#" & Format(dt, "mm\/dd\/yyyy") & "#"
End Function
Public Function quDateT(dt As Date) As String
' return formatted date with time
quDateT = "#" & Format(dt, "mm\/dd\/yyyy HH:NN:SS") & "#"
End Function
So, you don't have to care about the date and regional format, but for a in-line SQL insert command that you build in code? Yes, you MUST convert to USA format of mm/dd/yyyy.
So, you can display dates in any format. For forms, for reports - not a problem.
However, the ONLY exception here is your code that builds a insert statement. That date string format must be #mm/dd/yyyy#.
Or, ISO:
#yyyy-mm-dd#
So, either format is fine, but it is a hard and fast rule that you must conform to.
So, from a text box on a form, if not data bound, then you want to ensure that the text box is set as a date type text box (fomrat date).
then in code:
dim strSQL as string
strSQL = "INSERT INTO tblFun (BirthDate) " & _
"VALUES (#" & format(txtDate,"mm/dd/yyyy") & "#)"
currentdb.Execute strSQL
Or, if you have that helper function, then this:
strSQL = "INSERT INTO tblFun (BirthDate) " & _
"VALUES (" & qudate(txtDate) & ")"
I have a date field in my table, with "dd/mm/yyyy" format.
I am trying to insert into that field a variable through a form using VBA code. I have this:
vardtedate = CDate(Format(Me.dtedate.Value, "dd/mm/yyyy"))
DoCmd.RunSQL "INSERT INTO table (dtedate) VALUES (#" & vardtedate & "#);"
It works fine, but only when the day is over 12.
If I try to insert something like '12/06/2016' it shows it reversed, like '06/12/2016', and the field takes that date as 6th of december instead of 12 of june. What am I doing wrong? What am I missing?
I tried to parametize and the problem persists.
So I was looking for solutions and I found this thread Inserting current DateTime into Audit table. Apparently when you try to insert a date value through a sql statement it converts ambiguous date formats to "mm/dd/yyyy". I formatted the variable to "yyyy/mm/dd" and now works perfectly.
vardtedate = CDate(Format(Me.dtedate.Value, "dd/mm/yyyy"))
DoCmd.RunSQL "INSERT INTO table (dtedate) VALUES (#" & Format(vardtedate, "yyyy-mm-dd") & "#);"
Yes, it has to do with the regional settings your desktop is set to. United States data conventions, are totally different from European, or some other standard. See the link below for details.
https://support.office.com/en-us/article/Set-default-values-for-fields-or-controls-99508d03-b28b-4057-9652-dac1c4c60d86
As you found out, setting the format forces a fix.
CDate(Format(Date.Now, "MM/dd/yyyy"))
I am stuck with something. I am trying to take a long column of dates of which are formated to show also hours and minutes and run a Group query to paste values at the date level without acknowledging the differences in hours and minutes.. Unfortunately I have no clue how to start. The code i put together so far which returns each grouped date with the hour and minutes is as follows:
st_sql = "INSERT INTO [tblSearchEngine03] ([Date])" & _
"SELECT [tblSearchEngine02].[Date]" & _
"FROM [tblSearchEngine02]" & _
"GROUP BY [tblSearchEngine02].[Date]" & _
"ORDER BY [tblSearchEngine02].[Date]"
Application.DoCmd.RunSQL (st_sql)
Im not sure the best way to truncate the date on table "tblSearchEngine02"..
Focus on the SELECT piece first. You can use DateValue() for your Date field values. Start with this as a new query in the Access query designer:
SELECT DateValue(se02.Date)
FROM tblSearchEngine02 AS se02
GROUP BY se02.Date
ORDER BY se02.Date
Or you could use DISTINCT instead of GROUP BY:
SELECT DISTINCT DateValue(se02.Date)
FROM tblSearchEngine02 AS se02
ORDER BY se02.Date
After you have the SELECT working correctly, you can convert it to an INSERT query (the Access query designer calls it an "append" query).
And when you later build the same statement in your VBA code, include Debug.Print st_sql so that you can view the completed statement text in the Immediate window and make sure it is what you expected. (You can use Ctrl+g to go to the Immediate window.)
One way of doing this is to format the date/time as a date string. If you use YYYY/MM/DD it will sort properly. Otherwise you can convert the date/time to an int to trim off the time and then convert back to a date/time type.
Here is an example of formatting as string:
Format([tblSearchEngine02].[Date], "yyyy/mm/dd")
Here is an exmple of converting to get to a date (the end result will be a date/time data type so it might render as 03/16/2014 00:00 depending on your locale info)
CDate(CInt([tblSearchEngine02].[Date]))
Access stores its dates as floating point numbers where the integer part is the number of days since Jan 1, 1900 and the fractional part is the fraction of the day (time of day). Access is quite happy to treat these dates as numbers without doing any conversions, so:
fix([tblSearchEngine02].[Date])
will trim the fractional part of the day and set the time back to midnight and allow you to group by day.
I'm having a hard time in converting the date from dd-mm-yyyy format to dd/mm/yyyy format.
For Example,
When i enter a date in excel as 25/02/2012 (dd/mm/yyyy), after entering the date if go in the next line it converts the date in the 25-02-2012 (dd-mm-yyyy) format.
what i want to do is that when i enter the date in (dd/mm/yyyy) format in excel it should keep it as it is and should not change it back to (dd-mm-yyyy) format when i go the next cell.
when i enter my date as the current system date my code gives me an error, i am having trouble validating the date i.e. is the date entered is a valid date or not
Sub valid_date()
' ---------------------------------------------------------------------
' Final Code - Trial
' ---------------------------------------------------------------------
Dim d1 As Variant
Dim IssueDate As Variant
Dim str As Variant
d1 = Worksheets("Sheet1").Cells(6, 1).value
MsgBox " The Issue Date format is " & d1
sysdate = Date
MsgBox "System Date is " & sysdate
If IsDateValid(d1) Then ' if date is in dd/mm/yyyy format then print this
If (d1 > sysdate) Then
MsgBox "Invalid date"
End If
End If
End Sub
Function IsDateValid(pdate) As Boolean
IsDateValid = False
Set RegExp = CreateObject("VBScript.RegExp")
' it only matches whether date is in dd/mm/yyyy format or not
'
' [1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1] ---> it allows the DATE from 01 to 31
' [1-9]|0[1-9]|1[0-2] ---> it allows the MONTH from 01 to 12
' 1[9][0-9][0-9]|2[0][0-9][0-9] ---> it allows the YEAR from 1900 to 2099
'
' below is the regular expression for checking the date in dd/mm/yyyy format
RegExp.Pattern = "^([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])[/]([1-9]|0[1-9]|1[0-2])[/](1[9][0-9][0-9]|2[0][0-9][0-9])$"
' check whether the date is in dd/mm/yyyy format or not....
tempdate = RegExp.Test(pdate)
If tempdate Then ' if tempdate is in dd/mm/yyyy format than proceed further
'If isdate(tempdate) Then ' if date is a valid date then proceed further
If isdate(pdate) Then
IsDateValid = True
Else
IsDateValid = False
End If
Else
IsDateValid = False
End If
End Function
i'm using the above mentioned code by using a regular expression to check whether the date is in dd/mm/yyyy format or not
but the problem which i'm facing is that it takes the date in excel as dd-mm-yyyy format whenever i enter the date in dd/mm/yyyy format.
i have updated my code a bit,
i also need one more help when i enter my date as the current system date it gives me error
for example,
when i enter my date as 09/09/2012 (suppose this your current system date) and when i check this date using IsDate method, it gives me an error
i have again edited my code,
Can anyone please help me on this
You don't need VBA/RegEx. Select the cells/columns where you input dates and create a Custom number format: dd/mm/yyyy. Now no matter how you type in a valid date (05-05-2000, 3-1-2010, 14/6-1990, etc.), it should be formatted as dd/mm/yyyy.
And, as Olle points out, you should use the Date object rather than Variant if you are going to be manipulating dates in VBA. This way you're working with the serial number and not a string with potential formatting issues.
First, I suggest you check the regional settings for dates on your computer. If you set it to use the "dd/mm/yyyy" format it will be used by Excel as well and hopefully remove the need for any RegEx VBA-code.
Second, if you do need to use VBA to reformat dates, I strongly suggest you use the Date data type instead of Variants. I also advise you to use Option Explicit at the top of your code and explicitly declare any variables in order to minimize typos and produce better quality code.
Third, I've looked through your code some more and it seems it will never work:
1. Because it is never declared, tempdate is a Variant
2. You assign tempdate to be a boolean, from the result of RegExp.Test(pdate)
3. So when you check IsDate(tempdate) it will always be false, since a boolean can never be a Date.
Again, if you use the Date data type, you can skip the RegEx... :)
I use Adobe online PDF to Excel and dates display correctly as MM/DD/YYYY but when extracting month (=Month()) it returns the DD portion. It is being interpreted as DD/MM/YYYY. I saved the file as a .csv closed and restarted excel and opened the .csv file and the dates were correct MM/DD/YYYY.
I am using Access 2010 as a front-end to a database on SQL Server 2008. I have a date field which is stored as a nvarchar(50). I have the following value in the text field DateHr 12/04/11 16:49:23 , which should translate to April 11, 2012 4:49 PM (As is the date and time the record was created.).
I cannot change the datatype of the field to DateTime as it messes up the dates even more (Ex. 12/4/2011 4:49:23 PM). I cannot change the way the record is entered.
I need to display this field in the format "mm/dd/yy" and be able to do where clause in this format.
I have tried the following just to see if it displaying correctly but dtDate is displaying 11/12/04:
Select (Format(CDate([DateHr]),"yy/mm/dd")) as dtDate
If you need to carry out the conversion in access then you can try either of these:
Select Mid([DateHr],4,2) & "/" & Mid([DateHr],1,2) & "/" & Mid([DateHr],7,2) as dtDate
This I think will give you the date in a string format, otherwise you could try the following to get it in a valid date format:
Select Format(DateSerial(Mid([DateHr],7,2),Mid([DateHr],4,2),Mid([DateHr],1,2)),"MM/DD/YYYY") as dtDate
Create a SQL Server view to expand the year component of the date text to 4 digits. Then SELECT CDate([DateHr]) AS dtDate FROM YourView should work from the Access side. However it might be better still to have the view cast the date text to an actual date type ... then you could use it directly from Access without the need for CDate().