【问题标题】:type mismatch converting string to date类型不匹配将字符串转换为日期
【发布时间】:2021-07-15 16:24:44
【问题描述】:

发现问题:日期语言为俄语。然而下一个问题是 - 如何根据特定用户的日期格式转换日期字符串?

可能很简单的问题。把我的头撞在墙上。

我在 txt 文件中有日期,它被读取为 01-Sep-21。 VBA 中将其作为日期使用的任何操作都会导致类型不匹配 - Datevalue、CDate、CLng - 没有任何效果。我在哪里错过了这个问题?

对原始输入的测试看起来像这样,这不是我的代码相关问题(CDate 上的类型不匹配):

更新: 01.09.2021 - 作品 01-09-2021 - 作品 09 替换为 Sep/September - 不起作用

【问题讨论】:

  • CDate 在您提供的日期为我工作。也许您可以发布您的代码,以便我们更好地帮助您?
  • @Rosetta 太好了,你是对的。但是我的笔记本电脑是英文的,但看起来 dateformat 是俄文的,因为“01-Сен-21”有效。我该如何解决它的代码,因为它被多人使用。您可以根据语言进行转换吗?
  • 查看修改后的图像,如果您将DateProper 调暗为日期,则无需调用CDate...只需设置DateProper = strDate
  • 您可以在 VBA 中为特定语言和国家/地区设置日期/时间格式:codekabinett.com/… 对此进行了详细说明。

标签: vba


【解决方案1】:

CDate 使用计算机的当前区域设置。如果您需要在不同的语言环境中解析日期,请手动执行:

#If VBA7 Then
Private Declare PtrSafe Function VarDateFromStr Lib "OleAut32" (ByVal strIn As LongPtr, ByVal lcid As Long, ByVal dwFlags As Long, ByRef pdateOut As Date) As Long
#Else
Private Declare Function VarDateFromStr Lib "OleAut32" (ByVal strIn As Long, ByVal lcid As Long, ByVal dwFlags As Long, ByRef pdateOut As Date) As Long
#End If
Const LANG_EN_US as Long = &H409&
Const LANG_RU_RU As Long = &H419&

Dim s As String
Dim d As Date

s = "21-Sep-2021"
VarDateFromStr StrPtr(s), LANG_EN_US, 0, d
Debug.Print d
  
s = "21-" & ChrW$(1057) & ChrW$(1077) & ChrW$(1085) & "-2021"  ' 21-Сен-2021
VarDateFromStr StrPtr(s), LANG_RU_RU, 0, d
Debug.Print d

【讨论】:

    【解决方案2】:

    您可以轻松地将日期字符串更改为 VBA 中的实际日期:

    例如,在下图中,您可以看到strDateString,而datDateDate

    【讨论】:

      猜你喜欢
      • 2012-09-09
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 2014-11-17
      • 2020-09-06
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多