[英]VBA change date text to date format
我有一個導出的 excel 日期格式24.12.2019
,我如何使用 VBA 並設置一個宏,以便當我單擊宏時它變為2019-12-24
。 我試圖在stackoverflow中找到相關的帖子,但沒有用。 兩者都是通用文本格式,我想保持這種格式。
由於您想將所有內容保留為文本,請查看以下代碼並嘗試將其調整為您的工作表。
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 以文本形式獲取結果
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
嘗試這個:
DateText = "24.12.2019"
DateArr = Split(DateText, ".")
MsgBox DateArr(2) & "-" & DateArr(1) & "-" & DateArr(0)
如果您希望 output 作為日期值:
DateValue(DateArr(2) & "-" & DateArr(1) & "-" & DateArr(0))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.