数组输出中的日期格式异常

时间:2019-06-27 07:30:14

标签: arrays excel vba date format

我有一个2D数组,必须将其一部分打印到一张纸上, 当我将其打印到工作表上时,大多数日期与在本地窗口中显示的日期完全相同。 其中有些没有显示为美国日期

Sub ConvertDates()
 With Range("G1:G76")
   .NumberFormat = "dd/mm/yyyy"
   .TextToColumns Destination:=Range("G1"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, 
_
       Semicolon:=False, Comma:=False, Space:=False, Other:=False, 
FieldInfo _
    :=Array(1, 4), TrailingMinusNumbers:=True
End With

End Sub

如果我在excel中更改格式,则只是将日期重新排列为英国格式,但日期错误。 EG 11/06/2019从数组中转置为06/11/2019 但是从数组中将13/06/2019转换为应为13/06/2019。 重新格式化excel内部的单元格的效果为零,它只是更改格式 它已经决定的日期正确(美国格式)。

如果我运行VBA代码以更改格式,则它接受重新格式化并现在显示正确的日期。 WTF ??参见Convertdates() 但是,如果我将convertdates()代码更改为numberformat =“ dd / mm / yyyy” 它将显示不正确的日期?

如果需要数组代码,可以显示出来,但这很奇怪。

此异常发生的日期是10,11,12,超出了可能的范围 10,11,12,13,14,15,16

1 个答案:

答案 0 :(得分:0)

是的,我知道您对此感到无奈。我发现的解决方法如下。我将日期从一个范围存储到数组iArray中。将它们输出到指定范围时,请使用以下内容。

Sheet1.Cells(myRow, myCol).Value = Format$(iArray(aRow, aCol), "\ dd\/mm\/yyyy\")

此外,您需要运行以下内容的改编内容以进行清理。上面将在日期的前面保留一个空格,由于某种原因,当您在该日期运行VBA时,它会变回美国。

Sub CleanDates()

    'excel converting uk dates to us after performing action on it with VBA

    Dim strDate As String, strTrim As String
    Dim dRng As Range, dCol As Long, lRow As Long
    Dim i As Long, j As Long

    Set dRng = wsU.Rows(1).Find(What:="Start Dates", LookAt:=xlWhole)

    If Not dRng Is Nothing Then
        dCol = dRng.Column
    Else
        MsgBox "Failed to find the date columns to clean dates. Please consult the developer.", vbCritical
        Exit Sub
    End If

    lRow = wsU.UsedRange.Rows.Count

    For i = 2 To lRow
        For j = dCol To (dCol + 1)

            strDate = wsU.Cells(i, j).Text

            strTrim = Right(strDate, Len(strDate) - 1)

            wsU.Cells(i, j).Value = DateSerial(Year(strTrim), Month(strTrim), Day(strTrim))

        Next j
    Next i

End Sub

希望对您的问题有帮助。

相关问题