问题
I am facing an issue with date parameters passed to SQL Server stored procedure from EXCEL VBA code.
The stored procedure taking two date parameters @FromDate
and @ToDate
. From Excel I want to execute this procedure with the date values taken from cells.
The issue is that, the dates from cells to procedure are passed in the format "dd/mm/yyyy"
irrespective of any format changes I do in excel cell. Whereas the SQL procedure is accepting the formats "yyyy-mm-dd"
or "yyyy-mon-dd"
or "yyyy/mm/dd"
or "dd-mon-yyyy"
.
The procedure is throwing an error :
"Conversion failed when converting date and/or time from character string" for the dates passed from excel (in the format "dd/mm/yyyy"
The vba code I used is (reference https://www.mssqltips.com/sqlservert...to-sql-server/)
Private Sub CommandButton1_Click()
Dim FromDate As Date
Dim ToDate As Date
FromDate = Format(Sheets("Sheet1").Range("B1").Value, "yyyy-mm-dd") 'Pass value from cell B1 to SellStartDate variable
ToDate = Format(Sheets("Sheet1").Range("B2").Value, "yyyy-mm-dd") 'Pass value from cell B2 to SellEndDate variable
MsgBox FromDate
MsgBox ToDate
'Pass the Parameters values to the stored procedure used in the data connection
With ActiveWorkbook.Connections("TestConnection").OLEDBConnection
.CommandText = "EXEC dbo.spr_TestProcedure '" & FromDate & "','" & ToDate & "'"
ActiveWorkbook.Connections("TestConnection").Refresh
End With
End Sub.
Is there any way to pass the dates in the format that SQL Server procedure accepts? If there is no other option, then I will have to take the option to make my procedure parameters type to varchars and convert them to date.
Appreciating your help on this!
来源:https://stackoverflow.com/questions/39961565/vba-passing-date-parameters-to-sql-server-stored-procedure