Domanda

I'm sure this is probably something simple so I apologize ahead of time. This is actually my first time ever writing VBA and I've come to a problem which I simply can't get my head around how to fix. I've searched and tried multiple things but still the same problem despite anything I try.

I'm simply opening a new recordset, populating it with values from another table using SQL, retrieving the values from the recordset, then setting the caption on some labels on my form. My code:

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

I run this and I get a runtime error 13 with this line:

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

I can't for the life of me figure out why. I run the SQL in a query and it returns my values for me properly. I've changed the adCmdTable to adCmdText and tried adding "#" symbols as well as a host of other characters around the Me.txtClassID.Value section of the SQL string. Hovering over the SQL string, I can see the right "Class ID =" value (in this case "2") but hovering over the SQL string shows up "=empty".

What simple thing am I neglecting to notice? Thanks in advance for your help!

È stato utile?

Soluzione

The Set part of the assignment for the string is not correct. You only use Set for objects (for example ADODB objects). Primitive data types (string, integer, etc.) use simple assignment.

i.e.

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

Also I don't think the ";" is nessecary when executing SQL from ADODB.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top