VBA 用字符串创建日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26422089/
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
VBA creating date with strings
提问by Dear Deer
I'm trying to do simple tasks with date type but what I'm getting is not what I want. I would like to Split some cell value with delimiter and return string values to DateValue method.
我正在尝试使用日期类型执行简单的任务,但我得到的不是我想要的。我想用分隔符拆分一些单元格值并将字符串值返回给 DateValue 方法。
My code
我的代码
Dim str2() As String
str2() = Split(Cells(ActiveCell.Row, 7).Value, ".")
Dim date1 As Date
date1 = DateValue(str(0) & "-" + str(1) & "-" & str(2))
What I'm trying to do is getting some specific date format. Date in the cell is formated like this : 26.05.14 (day.month.year) and I want to have format like this 2014-05-26(year-month-day). That's all. DateValue method returs me a date 2000-01-02. I don't knwo how can I look into the str2() array to see what values are there after Split method. How can I do that ?
我想要做的是获取一些特定的日期格式。单元格中的日期格式如下: 26.05.14 (day.month.year) 我想要这样的格式 2014-05-26(year-month-day)。就这样。DateValue 方法返回给我一个日期 2000-01-02。我不知道如何查看 str2() 数组以查看在 Split 方法之后有哪些值。我怎样才能做到这一点 ?
It seems VBA is completely different from VB.NET ... I'm not experienced with VBA. Thanks
似乎 VBA 与 VB.NET 完全不同......我对 VBA 没有经验。谢谢
回答by Matteo NNZ
You are storing the return of your split into "str2" but then using the variable "str" into the DateValue input, which is not defined in your code (so it's empty). Avoid this kind of mistakes by putting "Option Explicit" on top of the project, in VBA is not compulsory like VB.NET but, indeed, optional. Here is the working code:
您将拆分的返回存储到“str2”中,然后将变量“str”使用到 DateValue 输入中,该输入未在您的代码中定义(因此它是空的)。通过在项目顶部放置“Option Explicit”来避免这种错误,在 VBA 中不像 VB.NET 那样是强制性的,但实际上是可选的。这是工作代码:
Dim str2() As String
str2 = Split(Range("A2").Value, ".")
Dim date1 As Date
date1 = DateValue(str2(0) & "-" & str2(1) & "-" & str2(2))