使用vba将ddmmmyyyy转换为数字

时间:2018-05-31 08:46:43

标签: excel vba excel-vba date

我有一个包含一些信息的单元格,其中包含一个ddmmmyy格式的日期(排序为“16dec 21 hello”)。 我需要生成一封电子邮件,其中在电子邮件的某些部分包含日期但是以数字形式(即16122021,所以ddmmyyyy)。 我尝试首先使用left()函数提取日期,然后尝试通过.numbertype =“ddmmyyyy”和cdate函数将其转换为数据,但它似乎不起作用。以下是我的代码:

'Getting date
Dim expdt As Date
Dim dt As String
dt = Left(Range("A8").Value, 8)
expdt = CDate("dt")

[打印00:00:00]

3 个答案:

答案 0 :(得分:2)

尝试,

Dim expdt As Date
Dim dt As String

'your sample had a space between Dec and 21
dt = Left(Range("A8").Value2, 2) & "-" & mid(replace(Range("A8").Value2, chr(32), chr(45)), 3, 6)
expdt = datevalue(dt)
debug.print expdt 

答案 1 :(得分:1)

或者您可以在标准模块(如Module1)上具有以下两个功能,然后以ddmmyyyy格式获取日期,如测试宏中所示。

Function GetDate(str As String) As String
Dim dtStr As String, m As Long
With CreateObject("VBScript.RegExp")
   .Global = False
   .Pattern = "\d{1,2}\s?[a-zA-Z]{3}\s?\d{2}"
    If .Test(str) Then
        dtStr = .Execute(str)(0)
        m = GetMonth(dtStr)
        If m > 0 Then
            GetDate = Left(dtStr, 2) & m & Right(dtStr, 2)
        End If
    End If
End With
End Function

Function GetMonth(str As String) As Long
Dim m
With CreateObject("VBScript.RegExp")
   .Global = False
   .Pattern = "[a-zA-Z]{3}"
    If .Test(str) Then
        m = DateValue(.Execute(str)(0) & "-1-2018")
        If Not IsError(m) Then GetMonth = Month(m)
    End If
End With
End Function

然后您可以按照所需的日期格式从字符串中提取日期,如下所示......

Sub Test()
MsgBox GetDate("16dec 21 hello")
'OR
MsgBox GetDate(Range("A8").Value)
End Sub

答案 2 :(得分:0)

撇开您输入错误的事实 - 您希望CDate(dt) - CDate 支持缩写的月份名称。所以你需要写出代码。这是一个片段:

Public Function fConvertDate(strDate As String) As Date
Dim bytDay As Byte
Dim intYear As Integer
Dim strMonth As String
Dim bytMonth As Byte

bytDay = Val(Left$(strDate, 2))
intYear = CInt(Mid$(strDate, 6, 4))
strMonth = UCase$(Mid$(strDate, 3, 3))

bytMonth = Val(Switch(strMonth = "JAN", "1", strMonth = "FEB", "2", strMonth = "MAR", "3", _
               strMonth = "APR", "4", strMonth = "MAY", "5", strMonth = "JUN", "6", strMonth = "JUL", "7", _
               strMonth = "AUG", "8", strMonth = "SEP", "9", strMonth = "OCT", "10", strMonth = "NOV", "11", _
               strMonth = "DEC", "12"))

fConvertDate = DateSerial(intYear, bytMonth, bytDay)
End Function

代码取自https://bytes.com/topic/access/answers/969310-how-convert-text-ddmmmyyyy-format-date

相关问题