je le code suivant qui fonctionne quand je rentre dans un numéro de client de l'exemple Northwind DB dans la cellule Excel D2 (par exemple) ALFKI:Comment puis-je transmettre le paramètre date de début et date de fin à SQL à l'aide d'Excel VBA?
C'est mon code Excel VBA qui fonctionne jusqu'à présent:
Dim con As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim WSP1 As Worksheet
Set con = New ADODB.Connection
Set cmd = New ADODB.Command
Set rs = New ADODB.Recordset
Application.DisplayStatusBar = True
Application.StatusBar = "Contacting SQL Server..."
' Remove any values in the cells where we want to put our Stored Procedure's results.
Dim rngRange As Range
Set rngRange = Range(Cells(8, 2), Cells(Rows.Count, 1)).EntireRow
rngRange.ClearContents
' Log into our SQL Server, and run the Stored Procedure
con.Open "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;Trusted_Connection=Yes;"
cmd.ActiveConnection = con
' Set up the parameter for our Stored Procedure
' (Parameter types can be adVarChar,adDate,adInteger)
cmd.Parameters.Append cmd.CreateParameter("CustomerID", adVarChar, adParamInput, 10, Range("D2").Text)
Application.StatusBar = "Running stored procedure..."
cmd.CommandText = "SP_GetOrdersForCustomer"
Set rs = cmd.Execute(, , adCmdStoredProc)
' Copy the results to cell B7 on the first Worksheet
Set WSP1 = Worksheets(1)
WSP1.Activate
If rs.EOF = False Then WSP1.Cells(8, 2).CopyFromRecordset rs
rs.Close
Set rs = Nothing
Set cmd = Nothing
con.Close
Set con = Nothing
Application.StatusBar = "Data successfully updated."
La procédure stockée est SP_GetOrdersForCustomer qui est:
CREATE PROCEDURE [dbo].[SP_GetOrdersForCustomer]
@CustomerID nchar(5)
AS
BEGIN
SELECT cst.[CustomerID],
cst.[CompanyName],
cst.[ContactName],
ord.[OrderID],
ord.[EmployeeID],
emp.[FirstName],
emp.[LastName],
ord.[ShippedDate],
prd.[ProductName],
od.[UnitPrice],
od.[Quantity]
FROM [Customers] cst,
[Orders] ord,
[Order Details] od,
[Employees] emp,
[Products] prd
WHERE ord.[CustomerID] = cst.[CustomerID]
AND emp.[EmployeeID] = ord.[EmployeeID]
AND od.[OrderID] = ord.[OrderID]
AND prd.[ProductID] = od.[ProductID]
AND cst.[CustomerID] = @CustomerID
ORDER BY cst.[CustomerID], emp.[EmployeeID], ord.[ShippedDate] DESC
END
Je dois maintenant faire la procédure stockée "Ventes par année" dans Northwind qui a deux paramètres de date @Beginning_Date et @Ending_Date sont tous les deux datatypes datetime.
Si je mets la date 1996-07-01 dans la cellule F1 et F2 1996-08-01 dans la cellule puis appelez le paramètre:
' Set up the parameter for our Stored Procedure
' (Parameter types can be adVarChar,adDate,adInteger,etc)
cmd.Parameters.Append cmd.CreateParameter("@Beginning_Date", adDate, adParamInput, 10, Range("F1").Text)
cmd.Parameters.Append cmd.CreateParameter("@Ending_Date", adDate, adParamInput, 10, Range("F2").Text)
il ne fonctionne pas.
C'est la procédure stockée avec les dates:
USE [Northwind]
GO
/****** Object: StoredProcedure [dbo].[Sales by Year] Script Date: 30/01/2017 22:04:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER procedure [dbo].[Sales by Year]
@Beginning_Date DateTime, @Ending_Date DateTime AS
SELECT Orders.ShippedDate, Orders.OrderID, "Order Subtotals".Subtotal, DATENAME(yy,ShippedDate) AS Year
FROM Orders INNER JOIN "Order Subtotals" ON Orders.OrderID = "Order Subtotals".OrderID
WHERE Orders.ShippedDate Between @Beginning_Date And @Ending_Date
Et ceci est le VBA Excel qui ne fonctionne pas. J'ai essayé de modifier ce que j'ai montré ci-dessus et je pense que je devrais avoir adDBDate au lieu de adDate mais il échoue avec « erreur d'application 3421 utilise une valeur de type incorrect pour l'opération en cours »:
Sub Button1_Click()
Dim con As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim WSP1 As Worksheet
Set con = New ADODB.Connection
Set cmd = New ADODB.Command
Set rs = New ADODB.Recordset
Application.DisplayStatusBar = True
Application.StatusBar = "Contacting SQL Server..."
' Remove any values in the cells and clear a space where we want to dump and put our Stored Procedure's results.
Dim rngRange As Range
Set rngRange = Range(Cells(8, 2), Cells(Rows.Count, 1)).EntireRow
rngRange.ClearContents
' Log into our SQL Server, and run the Stored Procedure
con.Open "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;Trusted_Connection=Yes;"
cmd.ActiveConnection = con
' Set up the parameter for our Stored Procedure
' (Parameter types can be adVarChar,adDate,adInteger,etc)
cmd.Parameters.Append cmd.CreateParameter("@Beginning_Date", adDate, adParamInput, 10, Range("J1").Text)
cmd.Parameters.Append cmd.CreateParameter("@Ending_Date", adDate, adParamInput, 10, Range("J2").Text)
'Show some text at the bottom on the status bar
Application.StatusBar = "Running stored procedure..."
'run the stored procedure name in SQL and drop the prefix dbo. it's not needed
cmd.CommandText = "Sales by Year"
'Execute it
Set rs = cmd.Execute(, , adCmdStoredProc)
' Copy the results to cell B7 on the first Worksheet
Set WSP1 = Worksheets(1)
WSP1.Activate
If rs.EOF = False Then WSP1.Cells(8, 2).CopyFromRecordset rs
'clean terminate
rs.Close
Set rs = Nothing
Set cmd = Nothing
'close off the connection to the SQL database
con.Close
Set con = Nothing
'Did it work ? Then display message at the bottom status bar
Application.StatusBar = "Data successfully updated."
End Sub
Pouvez-vous définir "ne fonctionne pas"? Avez-vous un message d'erreur? Les données retournées ne sont-elles pas ce que vous pensez qu'elles devraient être? Léger détour, vous ne devriez pas utiliser le préfixe sp_ (ou mieux encore aucun préfixe). http://sqlperformance.com/2012/10/t-sql-queries/sp_prefix –
J'ai ajouté l'autre procédure stockée pour montrer les dates, et le code de VBA que je ne peux pas obtenir au travail, les dates sont dans des cellules J1 et J2, j'ai essayé adDBdate et adDate mais j'ai la même erreur pour les deux? – ChrisR