2016-09-27 86 views
0

請問,你能告訴我如何使用vba執行SQL查詢嗎? (使用參數) 我試圖做到這一點:Vba rs.execute(參數查詢)

  • 首先準備一個子調用的函數Arir_Recordset:

    公用Sub Retriev_rs()

    Dim Query As String 
    Query = "SELECT * FROM '" & Table & "' WHERE DNI = '" & DNI & "' " 
    Dim rs2 As ADODB.Recordset 
    Set rs2 = New ADODB.Recordset 
    
    
    Open_Connection---- Works well! 
    
    Set rs2 = Abrir_Recordset(Query, "PRODUCTOS_CLIENTESBCO", "00000098687") 
    
    
    End Sub 
    

  • 功能:

    公共功能Abrir_Recordset(查詢作爲字符串表作爲字符串,DNI作爲字符串)作爲ADODB.Recordset

    Dim comm As ADODB.Command 
    
    Dim rs As ADODB.Recordset 
    
    Set rs = New ADODB.Recordset 
    rs.CursorType = adOpenStatic 
    rs.LockType = adLockOptimistic 
    
    Set rs = conn.Execute(QUERY) 
    
    Set Abrir_Recordset = rs 
    
    
    End Function 
    

  • 問題:

它不承認查詢。它說:

錯誤sintax近「

它閱讀:

- "SELECT * FROM '' WHERE DNI = '' " 

當然......這是寫不好的查詢,你能幫我嗎?

許多。謝謝!!!

+0

您需要分配或傳入參數* Table *和* DNI *變量。 – Parfait

+0

請參見[創建參數化命令](http://stackoverflow.com/documentation/vba/3578/working-with-ado/12354/creating-parameterized-commands#t=201609272324299867052)。 – Comintern

+0

謝謝!它現在正在工作:: Query =「Select * from」&Tabla&「where DNI ='」&DNI&「'」 – Marcos

回答

0

其完成...將參數傳遞給此函數效果很好:

Public Function Abrir_Recordset(Tabla As String, DNI As String) As ADODB.Recordset 

Dim comm As ADODB.Command 

Dim rs As ADODB.Recordset 

Set rs = New ADODB.Recordset 
rs.CursorType = adOpenStatic 
rs.LockType = adLockOptimistic 

Query = "Select * from " & Tabla & " where DNI = '" & DNI & "'" 

Abrir_Conexion 


Set rs = conn.Execute(Query) 

Set Abrir_Recordset = rs 


End Function