简体   繁体   English

Excel VBA 将文本转换为日期

[英]Excel VBA to convert text to date

I have my dates in "yyyy.mm.dd" format text, and I'd like to convert them to dates.我的日期是“yyyy.mm.dd”格式的文本,我想将它们转换为日期。
This code works:此代码有效:

x = "2012.01.01"
d = DateSerial(Left(x, 4), Mid(x, 6, 2), Right(x, 2))

But is there a simpler way to do it?但是有没有更简单的方法呢?
I thought this would work (this should be straightforward), but it does not:我认为这会起作用(这应该很简单),但它没有:

d = Format(x, "yyyy.mm.dd")

For your specific example, try the following:对于您的具体示例,请尝试以下操作:

d= Replace(x, ".", "/")
d= Format(CDate(d),"yyyy/mm/dd"))

The actual function doing the conversion to Date:实际 function 转换为日期:

CDate(d)

From: https://www.techonthenet.com/excel/formulas/cdate.php来自: https://www.techonthenet.com/excel/formulas/cdate.php

The Microsoft Excel CDATE function converts a value to a date. Microsoft Excel CDATE function 将值转换为日期。

The CDATE function is a built-in function in Excel that is categorized as a Data Type Conversion Function. CDATE function 是 Excel 中的内置 function 被归类为数据类型转换 Z7256400ZDF。 It can be used as a VBA function (VBA) in Excel.它可以用作 Excel 中的 VBA function (VBA)。 As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.作为 VBA function,您可以在通过 Microsoft Visual Basic 编辑器输入的宏代码中使用此 function。

So to summarize: CDATE is the actual method converting to Date , but it has a problem with periods.总结一下: CDATE 是转换为 Date 的实际方法,但它有句点问题。

The format is for performing string formatting - but the actual conversion is done with CDATE .该格式用于执行字符串格式化 - 但实际转换是使用CDATE完成的。

Format is for formatting date values as text, not to convert to date values. Format用于将日期值格式化为文本,而不是转换为日期值。 Thus:因此:

Dim d As Date

x = "2012.01.01"
d = CDate(Replace(x, ".", "/"))

Then apply a date format to the cells where these values are to be displayed.然后将日期格式应用于要显示这些值的单元格。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM