Не удается изменить формат даты с VBA в некоторых версиях Excel - PullRequest
0 голосов
/ 10 февраля 2019

В некоторых версиях Excel у меня половина дат в формате март / 31/2018, форматирование ячейки общее, а другая половина - формат даты и 31.03.2008.Они экспортируются откуда-то, поэтому я не могу это изменить.Эти даты используются в сводной таблице.

Я пытался

Range("C2:C200").NumberFormat = "m/dd/yyyy"

переопределить формат и сопоставить их все с тем же форматом, но в сводной таблице всегда отображается март 31/2018 вместо 03/31 /2018 год для верхней половины.И дата марта / 31/2018 выравнивается по левому краю, а другая половина - по правильному формату 31.03.2008.

Range("C2:C200").Value.NumberFormat = "m/dd/yyyy" does not work either. 

For i = 2 to lastRow Step 1
dateString = Cells(i, 3).Value
Cells(i, 3).Value = DateValue(dateString) only works for the cells that are already in custom or date format and not for the general format cells.

Я бы хотел иметь возможность переопределить общий формат на правильный формат даты.

Ответы [ 2 ]

0 голосов
/ 10 февраля 2019

enter image description here

Option Explicit

Sub Convert2Date()
    Dim iCt As Integer
    Dim lastRow As Long
    Dim dateStr As Variant
    Dim dateArr() As String
    Dim YearInt As Integer, MonInt As Integer, dayInt As Integer
    'Range("C2:C200").Value.NumberFormat = "m/dd/yyyy" 'does not work either.
    'For i = 2 To lastRow
        'dateString = Cells(i, 3).Value
        'Cells(i, 3).Value = DateValue(dateString) 'only works for the cells that are already in custom or date format and not for the general format cells.


    lastRow = Range("C1").SpecialCells(xlCellTypeLastCell).Row
    For iCt = 2 To lastRow
        dateStr = Cells(iCt, 3).Value
        If Not (dateStr = "") Then
            If IsDate(dateStr) Then
                Cells(iCt, 5) = "isdate = OK!"
                Cells(iCt, 4) = CDate(dateStr)
            Else
                'Cells(iCt, 4) = CDate(dateStr)
                dateArr = Split(dateStr, "/")
                MonInt = ConvertMonth(dateArr(0))
                dayInt = CInt(dateArr(1))
                YearInt = CInt(dateArr(2))
                Cells(iCt, 4).Value = DateSerial(YearInt, MonInt, dayInt)
                Cells(iCt, 5) = "CONVERTED"
                Cells(iCt, 5).Interior.Color = vbYellow
            End If
        End If
    Next iCt
End Sub

Function ConvertMonth(MonthStr As String) As Integer
    Dim tempStr As String
    Dim tempInt As Integer
    tempStr = LCase(MonthStr)
    Select Case tempStr
        Case "jan"
            tempInt = 1
        Case "feb"
            tempInt = 2
        Case "mar"
            tempInt = 3
        Case "apr"
            tempInt = 4
        Case "may"
            tempInt = 5
        Case "jun"
            tempInt = 6
        Case "jul"
            tempInt = 7
        Case "aug"
            tempInt = 8
        Case "sep"
            tempInt = 9
        Case "oct"
            tempInt = 10
        Case "nov"
            tempInt = 11
        Case "dec"
            tempInt = 12
        Case Else
            Debug.Print "undefined month string"
            tempInt = 0
    End Select
End Function
0 голосов
/ 10 февраля 2019

Возможно, что некоторые из ваших "дат" на самом деле Текст значений.Чтобы преобразовать их в общий «настоящий» формат.Выберите ячейки и запустите:

Sub DateUnifier()
    Dim r As Range, d As Date, s As String, nf As String, arry
    nf = "m/d/yyyy"
    For Each r In Selection
        s = r.Text
        If s <> "" Then
            arry = Split(s, "/")
            If UBound(arry) = 2 Then
                If IsNumeric(arry(0)) Then
                    r.Clear
                    r.Value = DateValue(s)
                    r.NumberFormat = nf
                Else
                    r.Clear
                    r.Value = DateSerial(CInt(arry(2)), konvert(arry(0)), CInt(arry(1)))
                    r.NumberFormat = nf
                End If
            End If
        End If
    Next r
End Sub

Public Function konvert(st As Variant) As Integer
    mnths = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
    i = 1
    For Each mn In mnths
        If st = a Then
            konvert = i
            Exit Function
        End If
    Next mn
End Function

ИСПРАВЛЕНИЕ:

В функции konvert () есть ошибки, используйте вместо этого:

Public Function konvert(st As Variant) As Integer

    mnths = Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
    i = 1
    For Each mn In mnths
        If st = mn Then
            konvert = i
            Exit Function
        End If
        i = i + 1
    Next mn
End Function
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...