[英]How can I get the timestamp in “yyyy/MM/dd hh:mm:ss.fff"” format in VBA?
I want to get this output: 我想得到这个输出:
2018-09-02 00:00:00.000
I tried the below code: 我尝试了以下代码:
.Cells(LRS + 1, 15).Value = Format(.Cells(LRS + 1, "A").Value, "yyyy-MM-dd hh:mm:ss.fff")
And I got: 我得到:
2018-09-02 00:00:00.fff
The initial date in Excel has the following format yyyy/mm/dd
, no time included. Excel中的初始日期具有以下格式
yyyy/mm/dd
,不包括时间。 That's why the time part includes only zeros 00:00:00.000
. 这就是为什么时间部分仅包含零
00:00:00.000
。 The reason I want to include the time in the specific format is that I'm planning to import those dates into a SQL table with that format. 我想以特定格式包括时间的原因是,我计划将这些日期导入具有该格式的SQL表中。
Is there any solution? 有什么解决办法吗?
As you can see from the documentation fff
is not recognised as a formatting token in VBA. 从文档中可以看到,
fff
在VBA中未被识别为格式标记。
Helpfully, you can actually import your data into SQL without formatting it to add the time. 有用的是,您实际上可以将数据导入SQL而不用格式化它来增加时间。 If you import it into a
datetime
field the SQL engine will automatically default the time part of the field to midnight on the date you give it. 如果将其导入
datetime
字段,则SQL引擎会自动将字段的时间部分默认为您指定日期的午夜。
I think you can just change your format string to yyyy-MM-dd
by itself. 我认为您可以自行将格式字符串更改为
yyyy-MM-dd
。
However if you really want to do it like this, then since there's no time specified then just hard-code 000
instead of fff
. 但是,如果您真的想这样做,那么由于没有指定时间,因此只需硬编码
000
而不是fff
。 The rest of the time can be similarly hard-coded, since it never varies, so you end up with yyyy-MM-dd 00:00:00.000
. 其余时间可以类似地进行硬编码,因为它永远不会变化,因此您最终得到
yyyy-MM-dd 00:00:00.000
。 But as I said, I think it's a bit pointless. 但是正如我所说,我认为这没有意义。
After replacing the cell format with the corresponding format, it is likely that the value of the cell is imported as text, not as a value. 用相应的格式替换单元格格式后,单元格的值很可能作为文本而不是值导入。
Sub test()
Dim s As String, s1 As String, s2 As String
'First Cell format as your "yyyy-mm-dd hh:mm:ss.000"
Range("a2").NumberFormatLocal = "yyyy-mm-dd hh:mm:ss.000"
'In vb,This format("yyyy-mm-dd hh:mm:ss.000") is not recognized.
Range("b2") = Format(Range("a2"), "yyyy-mm-dd hh:mm:ss.000")
s1 = Format(Range("a2"), "yyyy-mm-dd hh:mm:ss.000")
's1 = "2018-09-03 01:24:33.000"
'Since you format a2 cell as "yyyy-mm-dd hh:mm:ss.000" you can get data as text
Range("b2") = Range("a2").Text
s2 = Range("a2").Text
's2= "2018-09-03 01:24:33.240"
End Sub
Sheet Data 图纸数据
Local Window 本地窗口
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.