首页 > 解决方案 > VBA 转换日期

问题描述

我究竟做错了什么 ?

在单元格 a2 中,我有一个日期(美国)格式 19790131。我想在 31.01.1979 中重写它enter code here但得到结果:1/31/1979

For i = 2 To z
DatText = Cells(i, x)
Cells(i, x) = CDate(Mid(DatText, 7, 2) & "." & Mid(DatText, 5, 2) & "." & Mid(DatText, 1, 4))
Cells(i, x).NumberFormat = "dd.mm.yyyy"
Next i

标签: excelvba

解决方案


您可以为此使用Format - 并包含IsDate以进行一些错误处理:

Public Function ConvertDate()
    
    Dim ThisCell    As Excel.Range
    
    Dim RowIndex    As Long
    Dim ColumnIndex As Long
    Dim DatText     As String
    
    ColumnIndex = 1

    For RowIndex = 2 To 10
        Set ThisCell = Cells(RowIndex, ColumnIndex)
        If Not IsDate(ThisCell.Value) Then
            DatText = Format(ThisCell.Value, "@@@@\/@@\/@@")
            If IsDate(DatText) Then
                ThisCell.Value = CDate(DatText)
            End If
        End If
    Next

End Function

推荐阅读