2012-02-06 109 views
2

我敢肯定,这可能是简单的,所以我提前道歉。这实际上是我第一次写VBA,而我遇到了一个问题,我根本无法解决问题。尽管我尝试了一些东西,但我仍然搜索并尝试了多种东西,但仍然是同样的问题运行时错误13类型不匹配VBA访问2007

我只是打开一个新的记录集,使用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字符串上显示为“=空”。

什么简单的事情,我忽略注意? 在此先感谢您的帮助!

回答

3

该字符串的赋值部分Set不正确。对象只能使用Set(例如ADODB对象)。原始数据类型(字符串,整数等)使用简单的赋值。

strGetCustIDSQL = _ 
    "SELECT [CustomerID] FROM [Students Classes] WHERE [Class ID] = " & _ 
    Me.txtClassID.Value & ";" 

此外,我不认为 “;”在从ADODB执行SQL时是必须的。

+0

太好了。我知道这一定很简单。绝对是那些facepalm时刻之一。非常感谢! – Eyowzitgoin 2012-02-06 06:13:12

相关问题