例:以下是一個Excel VBA巨集,可將儲存在工作表中的日期字串“20220101”轉換為日期格式“2022/01/01”
Sub ConvertDateFormat()
Dim cell As Range
For Each cell In Selection ' 遍歷所選範圍中的每個儲存格
If IsNumeric(cell.Value) And Len(cell.Value) = 8 Then ' 檢查是否為8位數字
cell.Value = Format(DateSerial(Left(cell.Value, 4), Mid(cell.Value, 5, 2), Right(cell.Value, 2)), "yyyy/mm/dd") ' 轉換日期格式
End If
Next cell
End Sub
Sub ConvertDateFormat()
Dim cell As Range
For Each cell In Selection ' 遍歷所選範圍中的每個儲存格
If IsNumeric(cell.Value) And Len(cell.Value) = 8 Then ' 檢查是否為8位數字
cell.Value = Format(DateSerial(Left(cell.Value, 4), Mid(cell.Value, 5, 2), Right(cell.Value, 2)), "yyyy/mm/dd") ' 轉換日期格式
End If
Next cell
End Sub