我尝试做的是使用带参数的查询将SQL服务器中的拉取信息用于Excel电子表格。
我已经能够从excel查询数据库,但却无法弄清楚如何添加参数。
我需要从工作表中的单元格中获取参数。
Sub DataExtract()
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
Dim strConn As String
strConn = "PROVIDER=SQLOLEDB;"
strConn = strConn & "DATA SOURCE= MyServer ;INITIAL CATALOG = MyDatabase ;"
strConn = strConn & " INTEGRATED SECURITY=sspi;"
cnPubs.Open strConn
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
With rsPubs
.ActiveConnection = cnPubs
.Open "SELECT * FROM [MyTable] WHERE ColA = ?"
Sheet1.Range("B12").CopyFromRecordset rsPubs
.Close
End With
cnPubs.Close
Set rsPubs = Nothing
Set cnPubs = Nothing
End Sub
任何有关如何在查询引用中简单地使用问号的帮助将非常感谢表单中的单元格。 感谢
答案 0 :(得分:1)
未测试:
Sub DataExtract()
Dim cmd as ADODB.Command, param as Object, val
Dim cnPubs As ADODB.Connection
Dim rsPubs As ADODB.Recordset
Dim strConn As String
Set cnPubs = New ADODB.Connection
strConn = "PROVIDER=SQLOLEDB;"
strConn = strConn & "DATA SOURCE= MyServer ;INITIAL CATALOG = MyDatabase ;"
strConn = strConn & " INTEGRATED SECURITY=sspi;"
cnPubs.Open strConn
Set cmd = New ADODB.Command
cmd.CommandText = "SELECT * FROM [MyTable] WHERE ColA = ?"
cmd.CommandType = adCmdText
val = Sheet1.Range("A1").Value 'query value to be used
'create and add the parameter
Set param = cmd.CreateParameter("", adVariant, adParamInput, 0, val)
cmd.parameters.Append param
Set cmd.ActiveConnection = cnPubs
Set rsPubs = cmd.Execute()
Sheet1.Range("B12").CopyFromRecordset rsPubs
End Sub