将字符串值转换为vba中的日期值

时间:2017-07-11 13:55:14

标签: excel-vba format-conversion vba excel

为了便于输入数据,我允许用户输入日期为“ddmmyyyy”而不是“/”,例如“12032017”。在输入之后我想要更新目标单元格,其值为“dd / mm / yyyy”,例如“12/03/2017”。
在开始时,目标单元格的格式设置为“常规”,但是一旦计算出日期值,单元格的格式就会自动更改为“dd / m / yyyy”。 我试图使用常规和日期格式。以下是VBA代码

    If Not Intersect(Target, Range("D11:D510")) Is Nothing Then
    If Not (Target.Value = "") Then
    Application.EnableEvents = False   ' very important
    Target.Value = Left(Target.Value, 2) & "/" & Mid(Target.Value, 3, 2) & 
    "/" & Right(Target.Value, 4)
    Application.EnableEvents = True   'very important
    End If
    End If

1 个答案:

答案 0 :(得分:1)

您仍然返回一个看起来像日期而不是实际日期的字符串,使用DateSerial:

If Not Intersect(Target, Range("D11:D510")) Is Nothing Then
    Target.NumberFormat = "@"
    If Not (Target.Value = "") Then
        Application.EnableEvents = False   ' very important
        Target.Value = DateSerial(Right(Target.Value, 4), Mid(Target.Value, 3, 2), Left(Target.Value, 2))
        Target.NumberFormat = "dd/mm/yyyy"
        Application.EnableEvents = True   'very important
    End If
End If