2014-03-28 85 views
0

我想要做的是使用帶有參數的查詢從SQL服務器拉入信息到excel電子表格。從Excel中查詢SQL Server的參數

我已經能夠從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 

任何關於如何簡單地在查詢中引用問號的幫助我們將不勝感激。 感謝

回答

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 
+0

我用的是成功地與甲骨文(未接入用戶) - 不熟悉SQL服務器。儘管我在SQL Server上看到了很多使用'?'的例子。 –

+0

是的,我猜ADO驅動程序會將其計算出來。如果您想以任何順序定義您的參數,命名就出現了。我很驚訝你沒有使用Access雖然 – Brad

+0

@Brad - 我不會說我從來沒有使用Access,但我們更像是一家Oracle商店。 –