无法在VBA,Excel 2012中正确格式化date

我正在使用Excel 2010中的VBA脚本,根据事件的date从MySQL数据库中获取某些事件。 数据库中的date存储在“yyyy-mm-dd hh:mm:ss”中。 我的用户将使用一个从date范围来过滤他们感兴趣的事件。为了使他们更容易,我使用两个日历控件(mscal.ocx)范围 – Calendar1 for和Calendar2 for。 我写了两个简单的子程序,以确保日历上的每一次点击都会自动更新从中为查询string获取数据的单元格,如下所示:

Private Sub Calendar1_Click() Dim date1, datetime1, time1 As Date Cells(29, 10) = CDbl(Calendar1.Value) Cells(29, 10).NumberFormat = "yyyy-mm-dd" Cells(30, 10).NumberFormat = "hh:mm:ss" Cells(31, 11).NumberFormat = "yyyy-mm-dd hh:mm:ss" date1 = Cells(29, 10) time1 = Cells(30, 10) datetime1 = date1 & " " & time1 Cells(31, 10) = datetime1 Cells(29, 10).Select End Sub Private Sub Calendar2_Click() Dim date2, datetime2, time2 As Date Cells(29, 11) = CDbl(Calendar2.Value) Cells(29, 11).NumberFormat = "yyyy-mm-dd" Cells(30, 11).NumberFormat = "hh:mm:ss" Cells(31, 11).NumberFormat = "yyyy-mm-dd hh:mm:ss" date2 = Cells(29, 11) time2 = Cells(30, 11) datetime2 = date2 & " " & time2 Cells(31, 11) = datetime2 Cells(29, 11).Select End Sub 

而且,它几乎做我想要它做的事情,它将日历控件给出的格式更改为dd / mm / yyyy到yyyy-mm-dd。 是的,差不多,因为只有当date值介于1和12之间时才起作用,那么我的date时间单元显示为“yyyy-mm-dd hh:mm:ss”。 对于13至31天的价值,我的date时间格没有格式化,而是显示为“dd / mm / yyyy hh:mm:ss”。

现在,值得注意的是,单元格29,10和29,11总是有适当的格式(yyyy-mm-dd),不pipedate如何,问题在单元格31,11和31,10。

现在,当我双击单元格时,让光标在其中闪烁,然后按回车,格式化将被执行,格式将更改为正确的格式(即使日间值介于13和31之间)。 然而,这样做的目的是尽可能地自动化所有的东西,所以这不是一个真正的解决scheme。 如果需要,我可以附加文件,因为我意识到这听起来有点可笑,它适用于某些值,而不是其他人。

请帮忙 !

编辑::

好的,再次感谢您的快速回答,我检查了您的解决scheme,并用它回到了开始阶段。 运用

 Private Sub CommandButton1_Click() Dim date1, date2, datetime1, datetime2, time1, time2, time3 As Date date1 = Cells(29, 10) time1 = Cells(30, 10) datetime1 = Format(date1, "dd/mm/yyyy") & " " & Format(time1, "hh:mm:ss") Cells(31, 10) = datetime1 End Sub 

很好的工作,但只有当date值从1到12,例如,单元格值才有效

date

2012-09-12

时间

15:00:00

答案是我想要的,这是

约会时间

2012-09-12 15:00:00

但是,当我把一天的价值超过12,这是13至31它停止工作正常(是的,我知道这是多么荒谬的声音),而我得到的结果是:

约会时间

13/09/2012 15:00:00

任何build议非常感谢…

使用Format()函数

 Format("17/07/2012", "yyyy-mm-dd") 

其结果是2012-07-17

我知道我太迟了,但是我认为你需要区分月份(MM)和分钟(mm)…所以试试这个…

 Format(yourDateObj, "yyyy/MM/dd hh:mm:ss"); 

希望这可以帮助..:)

 Private Sub testje() Dim date1, date2, datetime1, datetime2, time1, time2 As Date date1 = Cells(1, 1) time1 = Cells(1, 2) datetime1 = Format(date1, "dd/mm/yyyy") & " " & Format(time1, "hh:mm:ss") Cells(2, 1) = datetime1 End Sub 

似乎工作。 否则,将Excel中的范围格式设置为自定义,定义为“dd / mm / yyyy uu:mm:ss”。

尝试格式(“mm / dd / yyyy”)。

在VBA中,如果打算将date时间作为查询的一部分传递给SQL,则不要以date显示。 而是尝试昏暗string。

您应该可以使用此处build议的函数将string格式化为所需的格式。

例如:

 Dim date1 As String date1 = Cells(29, 10) date1 = Format(Date1, "yyyy-MM-dd hh:mm:ss") debug.print date1 

我认为这已经不再适用于你(一年前发布!),但我刚刚遇到同样的问题,这对我来说,也许会帮助别人。