Excel VBA query to access is failing
I am trying to query an access file from excel using VBA and it is giving an error on the line rs.Open queryStatement, conn, adOpenStatic, adLockOptimistic
. The error is "Run-Time error '-2147217904 (80040e10)': No Value given for one or more required parameters."
Function queryAccess()
'inputs: filterID, desired output
Dim toSheet As Worksheet
Set toSheet = ThisWorkbook.Sheets("Sheet3")
Dim filterID As String
filterID = "CH0002"
Dim conn As ADODB.Connection
Dim rs As ADODB.recordSet
Dim connStr As String
Dim queryStatement As String
Dim cmd As ADODB.Command
connStr = "Provi开发者_Go百科der=Microsoft.ACE.OLEDB.12.0;Data Source=\\rtpwfil03\etu2\cat\projects\asbestos\STREAMS TO101\Testing\TO101 Testing Data.mdb;Persist Security Info=False;"
'conn.Provider=""Microsoft.Jet.OLEDB.4.0"
Set conn = New ADODB.Connection
Set rs = New ADODB.recordSet
Set cmd = New ADODB.Command
queryStatement = "SELECT Filters.NominalLoading FROM Filters WHERE Filters.FilterID=" & filterID & ";"
conn.Open connStr
Debug.Print connStr
Debug.Print queryStatement
rs.Open queryStatement, conn, adOpenStatic, adLockOptimistic
toSheet.Range(toSheet.Cells(1, 1)).CopyFromRecordset rs
conn.Close
rs.Close
End Function
when I do a debug.print on my connStr and queryStatement I get this, respectively:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\rtpwfil03\etu2\cat\projects\asbestos\STREAMS TO101\Testing\TO101 Testing Data.mdb;Persist Security Info=False;
SELECT Filters.NominalLoading FROM Filters WHERE Filters.FilterID=CH0002;
I got the connection string from http://www.connectionstrings.com/access-2007 "standard security"
Any ideas on how to fix this error?
You need single quotes around the CH002 string in your query. Change:
queryStatement = "SELECT Filters.NominalLoading FROM Filters WHERE Filters.FilterID=" & filterID & ";"
to
queryStatement = "SELECT Filters.NominalLoading FROM Filters WHERE Filters.FilterID='" & filterID & "';"
精彩评论