Using Returned Results from a SQL Vba Query

sross81

Registered User.
Local time
Yesterday, 21:19
Joined
Oct 22, 2008
Messages
97
Hello,

I have this query that I am using to find an ID number. I want to use the ID that the query returns and assign it to a text box on my form. I can't figure out how to do it and can't seem to find anything that gives an example.

Dim strSQL As String
strSQL = "Select ID FROM [Computer Inventory] " _
& "WHERE [PC Name] = '" & Me.cboComputerName & "'"


Me.txtComputerIDCode = strSQL (this just gives me my sql statement... :) )
 
Code:
dim rs as ADODB.Recordset
Set cnn = New ADODB.Connection
Set cnn = CurrentProject.Connection
Dim strSQL As String

strSQL = "Select ID FROM [Computer Inventory] " _
& "WHERE [PC Name] = '" & Me.cboComputerName & "'"

Set rs = New ADODB.Recordset
    With rs
    Set .ActiveConnection = cnn
    .LockType = adLockOptimistic
    .CursorType = adOpenStatic
    .Open strSQL
    End With

'Now you have a recordset and you can examine one row at a time
something = rs.fields("FieldName").value

'Or you can use the field index, it starts at 0 and goes to however many fields you have, so usually the first field 0 is your index
something = rs.fields(0).value
'To move about your recordset you have to
rs.movenext
rs.moveprevious
rs.movefirst
rs.movelast

'usually you loop thru a recordset

do until rs.eof
'Get all of your field values and execute code here

rs.movenext
loop

There are many more examples on this forum of how to use and open ADO and DAO recordsets.

They are pretty much the same, but I think DAO is being depreciated.
 
Thanks for the response. I will save that for future reference. I ended up just finding this other example that worked. I will post it here so if anyone else might find it helpful:

Dim strCriteria as string
strCriteria = "[PC Name] = '" & me.cboComputerName & "'"
me.txtComputerIDCode = DLOOKUP("ID", "Computer Inventory", strCriteria)
 

Users who are viewing this thread

Back
Top Bottom