Excel VBA - 将日期字符串转换为日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37139019/
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-08 10:24:30  来源:igfitidea点击:

Excel VBA - Convert Date String to Date

excelvba

提问by megatron77

I have a number of strings in cells which are dates but they need to be converted to date format.

我在单元格中有许多字符串是日期,但它们需要转换为日期格式。

They are in the following format:

它们采用以下格式:

mmm dd, yyyy

For Example:

例如:

Feb 10, 2016

So they can be 11 or 12 in length:

所以它们的长度可以是 11 或 12:

Feb 1, 2016

I have started writing a function to parse each part of the string individually (day as integer, month as integer and year as integer) to then convert into date format.

我已经开始编写一个函数来单独解析字符串的每个部分(日为整数,月为整数,年为整数),然后转换为日期格式。

Firstly, is there an easier/slicker way to do this than the above?

首先,有没有比上面更简单/更巧妙的方法来做到这一点?

If there isn't an easier way, what's the best was to convert the 3 letter month (e.g. Feb or Mar or Apr) into a month number (e.g. 2 or 3 or 4)? As that is the only bit I'm really stuck with.

如果没有更简单的方法,最好将 3 个字母的月份(例如二月或三月或四月)转换为月份数(例如 2 或 3 或 4)?因为这是我真正坚持的唯一一点。

回答by Darren Bartrup-Cook

In VBA you could use: cdate("Feb 10, 2016").
As a function this would be:

在 VBA 中,您可以使用: cdate("Feb 10, 2016").
作为一个函数,这将是:

Public Function ConvertToDate(rng As Range) As Date

    ConvertToDate = CDate(rng)

End Function

回答by John Coleman

Use a Datevariable to read the value and then use the Formatfunction to format the date as you see fit.

使用Date变量读取值,然后使用该Format函数按照您认为合适的方式格式化日期。

For example:

例如:

Sub test()
    Dim D As Date
    D = Range("A1").Value
    MsgBox Format(D, "mm/dd/yyyy")
End Sub

If I run the code with the string "Feb 10, 2016" in A1 then "02/10/2016" is displayed in the message box

如果我在 A1 中使用字符串“Feb 10, 2016”运行代码,则消息框中会显示“02/10/2016”

回答by Mrig

Try this:

尝试这个:

Sub test()
    MsgBox Month(Datevalue("Feb 10, 2016"))
End Sub

This will give: 2

这将给出: 2

回答by Robert Co

Do you really need VBA? Excel provides you with a Text to Date function =DATEVALUE()and it does recognize Feb 10, 2016.

你真的需要VBA吗?Excel 为您提供了一个 Text to Date 函数=DATEVALUE(),它可以识别Feb 10, 2016