如何格式化 Excel 记录集中的日期?

How to format date from Excel recordset?

我从 SQL 服务器获取数据,现在我想将其复制到 Excel 工作表中。

我尝试格式化 "start_date" 但它只在第一列应用了格式,所有其他列显示为存储在 SQL 服务器中。

Sub ReadMBDataFromSQL()
    Dim Server_Name, Database_Name, User_ID, Password, SQLStr As String

    Set Cn = CreateObject("ADODB.Connection")
    Set RS = New ADODB.Recordset

    Server_Name = ""
    Database_Name = ""
    User_ID = ""
    Password = ""
    SQLStr = "SELECT lot, po, start_date, input_sponge_type, input_sponge_type FROM PalladiumNitrateMB WHERE start_date >= '" & Format(Range("start"), "mm-dd-yyyy") & "' AND start_date < '" & Format(Range("end"), "mm-dd-yyyy") & "' ORDER BY lot ASC"

    Set Cn = New ADODB.Connection
    Cn.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
    ";Uid=" & User_ID & ";Pwd=" & Password & ";"

    RS.Open SQLStr, Cn, adOpenKeyset, adLockBatchOptimistic

    With Worksheets("PdNitrateMassBalance").Range("A5:N600")
        RS("start_date") = Format(RS("start_date"), "dd/mm/yyyy")
        .ClearContents
        .CopyFromRecordset RS
    End With

    RS.Close
    Set RS = Nothing
    Cn.Close
    Set Cn = Nothing
End Sub

尝试更换这部分

With Worksheets("PdNitrateMassBalance").Range("A5:N600")
    RS("start_date") = Format(RS("start_date"), "dd/mm/yyyy")
    .ClearContents
    .CopyFromRecordset RS
End With

有了这个

With Worksheets("PdNitrateMassBalance")
    With .Range("A5:N600")
        .ClearContents
        .CopyFromRecordset RS
    End With
    FixDatesFromYYYY_MM_DD .Range("A:A"), "dd/mm/yyyy"
End With

还有附加子:

Sub FixDatesFromYYYY_MM_DD(DatesRange As Range, Format As String)
Dim r As Range
Dim firstDash As Integer, secondDash As Integer, i As Integer

For Each r In DatesRange
    If Not r.Value = "" Then
        firstDash = 0
        secondDash = 0
        For i = 1 To Len(r.Text)
            If Mid(r.Text, i, 1) = "-" Then
                If Not firstDash = 0 Then
                    secondDash = i
                    Exit For
                Else
                    firstDash = i
                End If
            End If
        Next

        With r
            .Value = DateSerial(Left(r.Text, 4), Mid(r.Text, firstDash + 1, IIf(secondDash = 7, 1, 2)), Mid(r.Text, secondDash + 1))
            .NumberFormat = Format
        End With
    End If
Next

End Sub

更新
添加了一个从 "yyyy-mm-dd" 文本格式转换日期的子项。

通过修改 SQL 查询解决了问题,我请求日期 convert(varchar,start_date,103)