使用 VBA 在 Access 中插入日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40805573/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 11:36:23  来源:igfitidea点击:

Inserting dates in Access using VBA

sqlvbadatems-accessformat

提问by Iván Gómez Brea

I have a date field in my table, with "dd/mm/yyyy" format.

我的表中有一个日期字段,格式为“dd/mm/yyyy”。

I am trying to insert into that field a variable through a form using VBA code. I have this:

我正在尝试通过使用 VBA 代码的表单将变量插入到该字段中。我有这个:

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?

它工作正常,但仅当一天超过 12 时。如果我尝试插入诸如“12/06/2016”之类的内容,它会显示它已反转,例如“06/12/2016”,并且该字段将该日期作为日期的第 6 个12 月而不是 6 月 12 日。我究竟做错了什么?我错过了什么?

I tried to parametize and the problem persists.

我试图参数化,但问题仍然存在。

回答by Iván Gómez Brea

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.

所以我一直在寻找解决方案,我找到了这个线程Inserting current DateTime into Audit table。显然,当您尝试通过 sql 语句插入日期值时,它会将不明确的日期格式转换为“mm/dd/yyyy”。我将变量格式化为“yyyy/mm/dd”,现在可以完美运行。

vardtedate = CDate(Format(Me.dtedate.Value, "dd/mm/yyyy"))
DoCmd.RunSQL "INSERT INTO table (dtedate) VALUES (#" & Format(vardtedate, "yyyy-mm-dd") & "#);"

回答by Iván Gómez Brea

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

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.

正如您所发现的,设置格式会强制修复。

回答by Mahdi Dhifi

CDate(Format(Date.Now, "MM/dd/yyyy"))

CDate(格式(Date.Now, "MM/dd/yyyy"))