的MS Access VBA ADODB Recordset.Open表确定,但SQL失败
的MS Access VBA ADODB Recordset.Open表确定,但SQL失败
我有一个MS Access 2007表:
列是DB,模块,CommentID和评论
我有一个SQL查询返回MS Access查询设计中的正确记录。
我已经在即时窗口中确认sql在Access Access查询设计和VBA模块“Module1”中的确相同。
我叫如下的功能:在功能
?LookupComment(currentproject.Name,Application.VBE.ActiveCodePane.CodeModule,"1")
随后STRSQL在即时窗口中确认为
Select * from tblComments where DB='db1.accdb' AND Module='Module1' AND CommentID='1'
如果我取代“strSQ”与“tblComments”功能回报良好。
但我得到一个错误的rst.open与STRSQL对象 '_Recordset' 的
方法 '打开' 失败
Public Function LookupComment(theDB, theModule, theCommentID As String) As String
Dim cn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim strSQL As String
Set cn = CurrentProject.Connection
Set rst = New ADODB.Recordset
strSQL = "Select * from tblComments where DB='" & theDB & "' AND " _
& "Module='" & theModule & "' AND CommentID='" & theCommentID & "'"
rst.Open strSQL, cn, adOpenDynamic, adLockReadOnly
' rst.Open "tblComments", cn, adOpenDynamic, adLockReadOnly
If rst.EOF = False Or rst.BOF = False Then
rst.MoveFirst
LookupComment = rst!Comment
End If
Set rst = Nothing
Set cn = Nothing
End Function
的思考?
TIA
测试你的这种变化功能:
strSQL = "Select * from tblComments where DB='" & theDB & "' AND " _
& "[Module]='" & theModule & "' AND CommentID='" & theCommentID & "'"
我包围Module
用方括号,因为它是一个Jet保留字。请参阅Problem names and reserved words in Access。
具有该取消括号名称的SELECT语句会导致ADO记录集.Open
方法失败。正如您所报告的,当在查询设计器中打开的查询使用相同的SELECT语句时,它会成功。 Igor的DAO记录集建议也适用于我,无论我是否用括号括起Module
;我不明白你为什么失败。
很难准确预测何时使用保留字,因为数据库对象名称会将您咬在屁股上。避免完全使用它们更安全。如果无法避免,请将这些名称放在查询中的方括号中,以减少混淆数据库引擎的可能性。
您可以下载Allen Browne的免费Database Issue Checker Utility并使用它来检查数据库中的保留字。它还会警告您有关数据库的其他潜在问题。
我想你在查询结束时丢失了一个分号。
那应该没关系 – 2012-04-22 03:05:01
用分号测试并确认错误仍然 – user824232 2012-04-22 03:23:23
使用DAO记录来代替:
Public Function LookupComment(theDB, theModule, theCommentID As String) As String
Dim rst As Recordset
Dim strSQL As String
strSQL = "Select * from tblComments where DB='" & theDB & "' AND " _
& "Module='" & theModule & "' AND CommentID='" & theCommentID & "'"
Set rst = CurrentDb.OpenRecordset(strSQL, dbOpenDynaset)
If rst.EOF = False Or rst.BOF = False Then
rst.MoveFirst
LookupComment = rst!Comment
End If
Set rst = Nothing
End Function
在侧面说明,你确定你需要CommentID为字符串/文本类型?
谢谢。复制并粘贴你的代码仍然在SQL上。 – user824232 2012-04-22 05:49:05
错误消息需要2个参数。 “tblComments works fine – user824232 2012-04-22 06:04:34
@ user824232:在我发布之前,我测试了代码,它确实有效!如果您得到”预期2参数“错误,则意味着您的列名中有三个是无效的,确保DB,Module和CommentID是 – 2012-04-22 06:41:00
其实我想过支架,但是经过测试,没有它们就可以正常工作 – 2012-04-22 06:55:29
@IgorTurman如果你的意思是你的DAO记录集方法,是的,我同意它没有括号,但我无法使ADO记录集方法工作在没有括号的情况下,我不明白为什么它是ADO的问题而不是DAO的问题。因为我避免了表和字段名称的保留字。:-) – HansUp 2012-04-22 07:06:11
保留名称是问题。 – user824232 2012-04-22 07:53:36