请使用下一个功能:
Function makeDate_(strD) As Date
Dim d As Date
d = DateSerial(left(strD, 4), Mid(strD, 5, 2), Right(strD, 2))
makeDate_ = Format(d, "dd/mm/yyyy")
End Function
它可以被测试为:
Sub testMakeDate()
Dim x As String, y As Long
x = "20230118"
y = 20220227
Debug.Print makeDate_(x)
Debug.Print makeDate_(y)
End Sub
该值可以是数字或字符串。该函数可以用作 UDF(用户定义函数)并作为公式调用:
=makeDate_(A2)
或者更快,将要处理的范围放在一个数组中,在代码末尾返回处理结果:
Sub testMakeDate_()
Dim sh As Worksheet, lastR As Long, rng As Range, arr, i As Long
Set sh = ActiveSheet
lastR = sh.Range("A" & sh.rows.count).End(xlUp).Row 'the column where the custom Date/number to be processed
Set rng = sh.Range("A2:A" & lastR)
arr = rng.Value
For i = 1 To UBound(arr)
arr(i, 1) = makeDate_(arr(i, 1))
Next i
With rng
.NumberFormat = "dd/mm/yyyy"
.Value = arr
End With
End Sub
如果您的数据不在 A:A 中,请使用您的真实列标题调整两条代码行 lastR = sh.Range("A" & sh.... 和 Set rng = sh.Range("A2:A" & lastR)...