使用Access2007。我试图编写一个VBA函数,该函数将从我作为参数传递的表名,字段和值中构造一个查询。我不断收到“运行时错误'3464':条件表达式中的数据类型不匹配。”
这里是代码:
Function getPrimaryFromForeign(db As Database, table As String, field As String, _
value As Long, _
field2 As String, value2 As Long) As Long
Dim sStr As String
Dim istr As String
Dim rs As Recordset
sStr = "select * from " & table & " where " _
& field & "='" & value & "' and " & field2 & "='" & value2 & "'"
istr = "insert into " & table & "(" & _
field & "," & field2 & ") values ('" & value & "','" & value2 & "')"
Set rs = db.OpenRecordset(sStr)
If rs.RecordCount < 1 Then
db.Execute (istr), dbFailOnError
Set rs = db.OpenRecordset(sStr)
End If
getPrimaryFromForeign = rs("id")
End Function
错误发生在该行:设置rs = db.OpenRecordset(sStr)
我认为这与Value和Value2的变量类型有关。但是我已经使用typename()检查了它们,并且在调用OpenRecordSet()时它们都是Long。该查询位于两个字段均为数字类型的表上。那么为什么会有类型不匹配?
我已经很长时间没有使用Access了,但是我认为,这是因为您将Value
和Value2
用单引号引起来,而没有将字段包含在方括号中的WHERE子句。
尝试这样:
sStr = "select * from " & table & " where [" _
& field & "] = " & value & " and [" & field2 & "] = " & value2
istr = "insert into " & table & "([" & _
field & "], [" & field2 & "]) values (" & value & "," & value2 & ")"
如果引用库中同时包含DAO和ADO,则会发生这种情况。在这种情况下,Dim语句和引用窗口中的声明顺序都很重要。
1)“您必须同时引用和使用DAO和ADO Recordset对象,并按如下所示显式设置对象的尺寸:
Dim adoRS As ADODB.Recordset
Dim daoRS As DAO.Recordset"
2)“确保DAO对象库的引用在“引用”对话框中具有更高的优先级,或者清除对Microsoft ActiveX数据对象的引用。”