Search code examples
sql-serverexcelvbaado

How to format date from Excel recordset?


I get data from SQL Server and now I want to copy it in Excel worksheet.

I tried to format "start_date" but it applied the format only on the first column, all others display as stored in 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

Solution

  • Problem solved by modifying of the SQL query, i request the date with convert(varchar,start_date,103)