Excel VBA 查询访问失败
Posted
技术标签:
【中文标题】Excel VBA 查询访问失败【英文标题】:Excel VBA query to access is failing 【发布时间】:2011-08-17 15:30:54 【问题描述】:我正在尝试使用 VBA 从 excel 中查询访问文件,但在 rs.Open queryStatement, conn, adOpenStatic, adLockOptimistic
行出现错误。错误是“运行时错误 '-2147217904 (80040e10)': No Value given for a 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 = "Provider=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
当我在 connStr 和 queryStatement 上执行 debug.print 时,我分别得到以下信息:
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;
我从http://www.connectionstrings.com/access-2007“标准安全”得到连接字符串
关于如何修复此错误的任何想法?
【问题讨论】:
【参考方案1】:您需要在查询中为 CH002 字符串加上单引号。变化:
queryStatement = "SELECT Filters.NominalLoading FROM Filters WHERE Filters.FilterID=" & filterID & ";"
到
queryStatement = "SELECT Filters.NominalLoading FROM Filters WHERE Filters.FilterID='" & filterID & "';"
【讨论】:
以上是关于Excel VBA 查询访问失败的主要内容,如果未能解决你的问题,请参考以下文章
使用 Microsoft Excel VBA 仅查询访问 accdb 文件时,“MSysObjects”没有读取权限(错误编号:-2147217911) - mdb 工作正常