[英]VBA change date text to date format
I have an exported excel with date formated this way 24.12.2019
, how can i use VBA and set a macro so that when i click on macro it becomes 2019-12-24
.我有一个导出的 excel 日期格式
24.12.2019
,我如何使用 VBA 并设置一个宏,以便当我单击宏时它变为2019-12-24
。 I tried to find in stackoverflow for related post, but to unavail.我试图在stackoverflow中找到相关的帖子,但没有用。 Both are general text format and i want to keep it that way.
两者都是通用文本格式,我想保持这种格式。
As you want to keep everything as text have a look at the following code and try to adjust it to your sheet.由于您想将所有内容保留为文本,请查看以下代码并尝试将其调整为您的工作表。
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
And you could use this function to get the result as text您可以使用此 function 以文本形式获取结果
Function dtTxt(inpdte As String) As String
dtTxt = Format(inpdte, "YYYY-MM-DD")
End Function
Try the following:尝试以下操作:
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
Try this:尝试这个:
DateText = "24.12.2019"
DateArr = Split(DateText, ".")
MsgBox DateArr(2) & "-" & DateArr(1) & "-" & DateArr(0)
If you want the output as date value:如果您希望 output 作为日期值:
DateValue(DateArr(2) & "-" & DateArr(1) & "-" & DateArr(0))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.