I need to create an excel macro where people can put in their parameters from a stored proc in SQL server. There is a bug somewhere on line 13, but I am not sure what it is since I am very new to Visual Basic.
Any help would be very appreciated.
Private Sub CommandButton1_Click()
Dim TransTime As Date 'Declare the SellStartDate as Date
Dim StoreNumber As Integer 'Declare the SellEndDate as Date
Dim Product As Integer 'Declare the SellEndDate as Date
TransTime = Sheets("Sheet1").Range("B4").Value 'Pass value from cell B3 to SellStartDate variable
StoreNumber = Sheets("Sheet1").Range("B5").Value 'Pass value from cell B4 to SellEndDate variable
Product = Sheets("Sheet1").Range("B6").Value 'Pass value from cell B4 to SellEndDate variable
'Pass the Parameters values to the Stored Procedure used in the Data Connection
With ActiveWorkbook.Connections("nitro_price_check").ODBCConnection
CommandText = "EXEC maverik.nitro_price_check '" & TransTime & "','" & StoreNumber & "'" & Product & "'"
ActiveWorkbook.Connections("nitro_price_check").Refresh
End With
End Sub
As commented, consider parameterization which is supported with Excel workbook connections but initial setup requires going through Excel's user interface. See MSDN docs for Create a parameter query in Microsoft Query .
During setup, be sure to include qmarks in your SQL command (ie, Command Text):
EXEC maverik.nitro_price_check ?, ?, ?
This will enable Parameters...
button under Definition tab of Connection Properties, where you can assign Excel cell values to each qmark placeholder by corresponding position:
=Sheet1!B4
=Sheet1!B5
=Sheet1!B6
Then your VBA is just a simple refresh line with no messy concatenation or quotation with SQL:
Private Sub CommandButton1_Click()
ActiveWorkbook.Connections("nitro_price_check").Refresh
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.