VBA将日期文本更改为日期格式

时间:2019-11-01 07:08:04

标签: excel vba

我有一个导出的Excel,其日期格式为24.12.2019,我该如何使用VBA并设置宏,以便当我单击宏时它变成2019-12-24。我试图在stackoverflow中找到相关的帖子,但是没有用。两者都是通用的文本格式,我想保持这种格式。

3 个答案:

答案 0 :(得分:2)

由于您希望将所有内容保留为文本,因此请查看以下代码,然后尝试将其调整为表格。

Sub Tester()

    Dim rg As Range
    Set rg = Range("A1:A4")

    Dim sngCell As Range
    For Each sngCell In rg
        ' This will set the format of the cell to text
        sngCell.NumberFormat = "@"

        ' This will change the format of the date
        ' Be careful there is a lot of internal casting going on
        sngCell.Value = Format(sngCell.Value, "YYYY-MM-DD")
    Next

End Sub

您可以使用此功能以文本形式获取结果

Function dtTxt(inpdte As String) As String
    dtTxt = Format(inpdte, "YYYY-MM-DD")
End Function

答案 1 :(得分:2)

尝试以下操作:

Sub Test()

Dim lr As Long
Dim rng As Range

With Sheet1 'Change according to your sheet's codename
    lr = .Cells(.Rows.Count, "A").End(xlUp).Row 'Change "A" to whichever column data is in
    Set rng = .Range("A1:A" & lr) 'Change accordingly again
    rng.TextToColumns Destination:=rng, DataType:=xlFixedWidth, FieldInfo:=Array(0, xlDMYFormat)
    rng.NumberFormat = "YYYY-MM-DD"
End With

End Sub

答案 2 :(得分:0)

尝试一下:

DateText = "24.12.2019"
DateArr = Split(DateText, ".")
MsgBox DateArr(2) & "-" & DateArr(1) & "-" & DateArr(0)

如果要将输出作为日期值:

DateValue(DateArr(2) & "-" & DateArr(1) & "-" & DateArr(0))