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

2022-08-25 00:00:00 vba excel sql-server ado

我从SQL Server获取数据,现在我要将其复制到Excel工作表中。

我尝试设置"START_DATE"的格式,但它只在第一列应用了该格式,其他所有列都显示为存储在SQL Server中。

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

解决方案

修改SQL查询解决了问题,我用 convert(varchar,start_date,103)

相关文章