Reputation: 113
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
Upvotes: 0
Views: 2017
Reputation: 1162
Try replacing this part
With Worksheets("PdNitrateMassBalance").Range("A5:N600")
RS("start_date") = Format(RS("start_date"), "dd/mm/yyyy")
.ClearContents
.CopyFromRecordset RS
End With
With this
With Worksheets("PdNitrateMassBalance")
With .Range("A5:N600")
.ClearContents
.CopyFromRecordset RS
End With
FixDatesFromYYYY_MM_DD .Range("A:A"), "dd/mm/yyyy"
End With
And additional sub:
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
Update
Added a sub to convert dates from "yyyy-mm-dd" text format.
Upvotes: 2
Reputation: 113
Problem solved by modifying of the SQL query, i request the date with
convert(varchar,start_date,103)
Upvotes: 1