VBA cDate不适用于Mac excel 2011(14.7.1)

我正在尝试使用VBA脚本将date转换为长。 以下是代码片段

Sub test() Dim str as string Dim d as variant str="1/1/2016" d=cdate(str) end sub 

上面的代码片段在Windows上运行良好,但给我MACtypes不匹配错误。 是否有任何转换在date转换有效的string。

你的代码在我的本地OS X机器上用Excel工作。 不过,我有不同的地区设置。 我会build议尝试使用国际date格式(“YYYY-mm-dd”)。

 Sub Main Dim str as String Dim d as Variant str = "2016-01-01" d = CDate(str) End Sub 

或者,您可以尝试“2016年1月1日”。


PS:你可以在系统偏好设置 – >语言&地区 – >高级 – >date在OS X中看到你的date和时间设置:

OS X语言和地区日期设置

您的区域设置是根本原因。

你可以尝试修改它们吗?

 defaults write NSGlobalDomain AppleICUDateFormatStrings -dict 1 dd/MM/yyyy 

也许尝试在转换之前删除“/”? 我没有一个Mac来testing:

 Public Sub test() Dim str As String Dim d As Long 'should be Date, but your question states Long str = "1/1/2016" d = CDate(Replace(str, "/", "")) Debug.Print d End Sub 

另外,你有没有尝试检查缺less的参考? VBA的date不能在Excel 2011中工作?

您可以使用IsDate()函数在转换之前检查它是否是date。 否则使用一种解决方法:

 Sub test() Dim str as string Dim d as variant str = "1/1/2016" If IsDate(str) then d = CDate(str) Else Dim aDateParts() as String aDateParts() = Split(str, "/") ' DateSerial(Year, Month, Day) d = DateSerial(CInt(aDateParts(2)), CInt(aDateParts(0)), CInt(aDateParts(1))) End If end sub 

许多不同的答案,所以我不妨把它扔到这个圈子里,

 Sub test() Dim str As String Dim d As Variant str = "1/1/2016" d = CDate(Format(str, "dd/MM/yyyy")) Debug.Print d End Sub 

我没有发布这个最初,因为我觉得它没有解决问题的根源,但是,如果你想要一个解决方法,你可以像使用CDate一样使用下面的函数,通过调用ConDate("12/12/2016")

这就是我解决问题的方法:

 Sub MainTest() Dim InputString As String, OutputDate As Date InputString = "01/12/2016" OutputDate = ConDate(InputString) Debug.Print OutputDate, TypeName(OutputDate) End Sub Function ConDate(ByRef InputString As String) As Date Dim Day As Long, Month As Long, year As Long 'mmddyyyy format Month = CLng(Left(InputString, InStr(1, InputString, "/", vbTextCompare) - 1)) Day = CLng(Mid(InputString, InStr(1, InputString, "/", vbTextCompare) + 1, InStrRev(InputString, "/", , vbTextCompare) - InStr(1, InputString, "/", vbTextCompare) - 1)) year = CLng(Right(InputString, 4)) ConDate = DateSerial(year, Month, Day) End Function 

不希望sebifeixler的答案plagerise我保留我原来的左/中/右分开日/月/年,但我觉得它是更加干净利用他的分裂function来分隔date的“/”。 两者的组合将是一个很好的解决方法。