0

我正在为 Excel 2007 中的特定单元格在 VBA 中开发一个更改事件。我想将在这些单元格中输入的两种不同格式的日期(带时间)转换为一种格式(美式)。

这是我的代码,用于检查输入的日期是否为两种所需格式之一。crmdate 是 ActiveCell 的字符串值:

    If RegexServiceManager.test(crmdate) Then
        outputDate = Format(CDate(crmdate), "MM/dd/yyyy hh:mm")
        Application.EnableEvents = False
        ActiveCell.Value = outputDate
        ActiveCell.NumberFormat = "MM/dd/yyyy hh:mm"
        Application.EnableEvents = True
    ElseIf RegexSiebel.test(crmdate) Then
        outputDate = CDate(crmdate)
        Application.EnableEvents = False
        ActiveCell.Value = outputDate
        ActiveCell.NumberFormat = "MM/dd/yyyy hh:mm"
        Application.EnableEvents = True
    Else
        MsgBox "Inapropriate date and time format"
    End If

RegexServiceManager 检查日期是否为 YYYY/MM/DD HH:MM:SS 格式,这可以正常工作。RegexSiebel 检查日期是否为 int DD-MMM-YYYY HH:MM 格式,这就是麻烦的开始。

我在线收到“类型不匹配”错误outputDate = CDate(crmdate)。我已经删除了类似于上方“If”中的 Format 方法,以验证错误来自 CDate。

有人可以就此提出建议吗?也许 CDate 无法识别 DD-MMM-YYYY(例如:01-Jan-2013)格式?如果是这样,有人可以提出解决方法吗?

目标格式为 MM/DD/YYYY HH:MM。

谢谢您最好的问候,

马切伊

编辑:

outputDate 是日期格式!

4

1 回答 1

0

我想我找到了答案。这有点傻,但上面的代码不适用于波兰区域设置。它适用于美国(也可能是英国)区域设置。

我还将 outputDate 更改为 Variant 类型。

我最终得到了这个:

    If RegexServiceManager.test(crmdate) Then
        MsgBox "otputDate: " & TypeName(outputDate) & vbCrLf & "crmdate: " & TypeName(crmdate)
        outputDate = CDate(crmdate)
        MsgBox "otputDate: " & TypeName(outputDate) & vbCrLf & "crmdate: " & TypeName(crmdate)
        Application.EnableEvents = False
        ActiveCell.Value = outputDate
        ActiveCell.NumberFormat = "MM/dd/yyyy hh:mm"
        Application.EnableEvents = True
    ElseIf RegexSiebel.test(crmdate) Then
        MsgBox "otputDate: " & TypeName(outputDate) & vbCrLf & "crmdate: " & TypeName(crmdate)
        outputDate = CDate(crmdate)
        MsgBox "otputDate: " & TypeName(outputDate) & vbCrLf & "crmdate: " & TypeName(crmdate)
        Application.EnableEvents = False
        ActiveCell.Value = outputDate
        ActiveCell.NumberFormat = "MM/dd/yyyy hh:mm"
        Application.EnableEvents = True
    Else
        MsgBox "Inapropriate date and time format"
    End If

消息框仅用于调试目的。

在程序开始时检测区域设置可能是明智的,或者以更好的方式编写它来避免这种情况。:)

希望这可以帮助某人。

谢谢您最好的问候,

于 2013-04-05T09:36:38.353 回答