2
我正嘗試使用VBA中的嵌入式SQL訪問SQL數據庫。問題在於定義我想訪問的條件(ID > @Identifie
是導致問題的部分)。當我運行代碼時,我得到必須聲明標量變量@Identifie
。但是,當我到我的本地窗口時,@Identifie被正確聲明並具有我在單元格K6中分配的值。此外,如果我將我的條件(ID > @Identifie
)中的@Identifie
替換爲某個值,我的代碼運行完美,因此沒有其他錯誤。看來我的問題來自append方法,但我無法弄清楚我做錯了什麼。使用參數化sql查詢時必須聲明標量變量
這裏是我的代碼:
(我刪除了這篇文章的連接字符串,但這顯然不是問題):
Option Explicit
Option Base 1
Sub LoadData()
Application.ScreenUpdating = False
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim cmd As New ADODB.Command
Dim lastID As Double
Dim parametre As New ADODB.Parameter
Dim Last_total_ID As Double
Last_total_ID = ActiveWorkbook.Worksheets("Consolidated").Range("K6").Value
cn.ConnectionString = ""
cn.Open
Set parametre = cmd.CreateParameter(Name:="@Identifie", Type:=adDouble, Direction:=adParamInput)
parametre.Value = Last_total_ID
cmd.Parameters.Append parametre
cmd.ActiveConnection = cn
cmd.CommandText = "Select ID, Issuer,LaunchDate,SettleDate,CADAmount,Description,Price,Currency, Maturity,IssuerID, Coupon FROM dbo.tblHistoricalIssuanceStats WHERE (IsProvy = 1) AND (ID > @Identifie)"
Set rs = cmd.Execute
它應該是'Set cmd.ActiveConnection = cn',因爲cn是一個對象 – barrowc