我有一个导出的Excel,其日期格式为24.12.2019
,我该如何使用VBA并设置宏,以便当我单击宏时它变为2019-12-24
。我试图在stackoverflow中找到相关的帖子,但是没有用。两者都是通用的文本格式,我想保持这种方式。
尝试一下:
DateText = "24.12.2019"
DateArr = Split(DateText, ".")
MsgBox DateArr(2) & "-" & DateArr(1) & "-" & DateArr(0)
如果要将输出作为日期值:
DateValue(DateArr(2) & "-" & DateArr(1) & "-" & DateArr(0))
由于您希望将所有内容保留为文本,请查看以下代码,并尝试将其调整为您的工作表。
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
尝试以下操作:
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