0
我想用ADODB運行參數化的SQL查詢,但我得到錯誤消息「必須聲明標量變量@Id」。VBA:使用ADODB參數
我是VBA的完整noob,我已經嘗試閱讀它是如何完成的以及遵循一個示例,但無濟於事。
有沒有人有我的代碼可能是錯誤的想法?
Public Function IndataTest()
Dim conn As ADODB.Connection
Dim ConnString As String
ConnString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=DB;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=B5037093;Use Encryption for Data=False;Tag with column collation when possible=False;Initial Catalog=DB"
Dim sqlstr As String Dim rs As Object Dim cmd As Object Dim ParamId As Object Dim Id As String
Id = 1084924
sqlstr = sqlstr & "use DB " sqlstr = sqlstr & "Select * " & vbCrLf sqlstr = sqlstr & "From tblA" & vbCrLf sqlstr = sqlstr & "where fldA = @Id"
Set conn = New ADODB.Connection conn.Open ConnString
Set cmd = CreateObject("ADODB.Command") cmd.ActiveConnection = conn cmd.CommandText = sqlstr
Set ParamId = cmd.CreateParameter("@Id", 129, 1, 52, Id) cmd.Parameters.Append ParamId
Set rs = CreateObject("ADODB.Recordset") rs.Open cmd
If Not rs.EOF Then
' Transfer result.
Sheets("Valuta").Cells(5, 5).CopyFromRecordset rs ' Close the recordset
rs.Close Else
MsgBox "Error: No records returned.", vbCritical End If
' Clean up If CBool(conn.State And adStateOpen) Then conn.Close Set conn = Nothing Set rs = Nothing
End Function