I want to be able to use SQL to retrieve Data from a table and display to the immediate window in Access.
I am new to VBA and I can't seem to find the way of doing it
Dim strSQL As String
Dim cdb As DAO.Database
Dim result As Variant
strSQL = "SELECT x, from y WHERE z;"
Set cdb = CurrentDb
Debug.Print strSQL
result = Call cdb.Execute(strSQL)
Debug.Print result
To print value of field from only first record.
Dim strSQL As String
Dim result As DAO.Recordset
strSQL = "SELECT x FROM y WHERE z;"
Set result = CurrentDb.OpenRecordset(strSQL, dbOpenDynaset)
Debug.Print result!x
If you want to print a value from each record, use a loop structure to move to each record like:
Do While Not result.EOF
Debug.Print result!x
result.MoveNext
Loop
Review this site http://allenbrowne.com/tips.html - look at the section 'Examples by Library' about halfway down.
To produce the result with just one line (assuming only one record is going to be returned), you can use:
Debug.Print CurrentDb.OpenRecordset("SELECT x FROM y WHERE z").Fields(0).Value
You can also use the DLookUp function, which is not SQL but you will recognise the parts:
Debug.Print DLookUp("x", "y", "z")
Alternative using With syntax..
Dim Cnt as Long
With CurrentDb.OpenRecordset("SELECT Count(*) FROM MyTable WHERE X=2")
If Not .EOF Then
Cnt = .Fields(0).Value
End If
End With
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.