我确信这可能很简单,所以我提前道歉。这实际上是我第一次编写 VBA,我遇到了一个我根本不知道如何解决的问题。我已经搜索并尝试了多种方法,但尽管我尝试了所有方法,但仍然存在同样的问题。
我只是打开一个新记录集,使用 SQL 用另一个表中的值填充它,从记录集中检索值,然后在表单上的一些标签上设置标题。我的代码:
Dim oconStudents As ADODB.Connection
Dim orsStudents As ADODB.Recordset
Dim strStudentsSQL As String
Set oconStudents = CurrentProject.AccessConnection
Set orsStudents = New ADODB.Recordset
Set strGetCustIDSQL = _
"SELECT [CustomerID] FROM [Students Classes] WHERE [Class ID] = " & _
Me.txtClassID.Value & ";"
orsStudents.Open strGetCustIDSQL, oconStudents, adOpenForwardOnly, _
adLockReadOnly, adCmdTable
With orsStudents
If Not orsStudents.EOF Then
lblStudent1.Caption = orsStudents.Fields.Item(0)
orsStudents.MoveNext
End If
End With
我运行此命令,并收到运行时错误 13,其中包含以下行:
Set strGetCustIDSQL = _
"SELECT [CustomerID] FROM [Students Classes] WHERE [Class ID] = " & _
Me.txtClassID.Value & ";"
我一生都无法弄清楚为什么。我在查询中运行 SQL,它正确地为我返回值。我已将 adCmdTable 更改为 adCmdText,并尝试在 SQL 字符串的 Me.txtClassID.Value 部分周围添加“#”符号以及许多其他字符。将鼠标悬停在 SQL 字符串上,我可以看到正确的“Class ID =”值(在本例中为“2”),但将鼠标悬停在 SQL 字符串上会显示“=empty”。
我忽略了哪些简单的事情? 预先感谢您的帮助!
最佳答案
字符串赋值的Set
部分不正确。您只能对对象(例如 ADODB 对象)使用 Set
。原始数据类型(字符串、整数等)使用简单赋值。
即
strGetCustIDSQL = _
"SELECT [CustomerID] FROM [Students Classes] WHERE [Class ID] = " & _
Me.txtClassID.Value & ";"
而且我不认为“;”从 ADODB 执行 SQL 时是必需的。
关于ms-access - 运行时错误 13 类型不匹配 VBA Access 2007,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9155367/