简体   繁体   English

Excel 中 SQL 存储过程的 Visual Basic 错误

[英]Visual Basic Bug For SQL Stored Procedure in Excel

I need to create an excel macro where people can put in their parameters from a stored proc in SQL server.我需要创建一个 excel 宏,人们可以在其中从 SQL 服务器中的存储过程中输入他们的参数。 There is a bug somewhere on line 13, but I am not sure what it is since I am very new to Visual Basic.第 13 行某处有一个错误,但我不确定它是什么,因为我对 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.如评论所述,考虑 Excel 工作簿连接支持的参数化,但初始设置需要通过 Excel 的用户界面。 See MSDN docs for Create a parameter query in Microsoft Query .有关在 Microsoft Query 中创建参数查询,请参阅 MSDN 文档。

During setup, be sure to include qmarks in your SQL command (ie, Command Text):在设置过程中,请确保在您的 SQL 命令(即命令文本)中包含 qmarks:

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:这将启用 Connection Properties 的 Definition 选项卡下的Parameters...按钮,您可以在其中按相应位置将 Excel 单元格值分配给每个 qmark 占位符:

  • Parameters ...参数 ...
    • Parameter 1 =Sheet1!B4参数 1 =Sheet1!B4
    • Parameter 2 =Sheet1!B5参数 2 =Sheet1!B5
    • Parameter 3 =Sheet1!B6参数 3 =Sheet1!B6

Then your VBA is just a simple refresh line with no messy concatenation or quotation with SQL:那么你的 VBA 只是一个简单的刷新行,没有凌乱的连接或 SQL 引用:

Private Sub CommandButton1_Click()
    ActiveWorkbook.Connections("nitro_price_check").Refresh
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM