Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a SQL SELECT statement with Access VBA

Tags:

sql

vba

ms-access

I have a combobox whose value I want to use with a SQL WHERE clause. How do you run a SELECT statement inside VBA based on the combobox value?

like image 732
Nag Hammadi Avatar asked Jun 13 '12 14:06

Nag Hammadi


People also ask

Can you use SQL in Access VBA?

This tutorial contains examples of using SQL with VBA Access. As you will see below, to run SQL queries in Access with VBA you can use either the DoCmd. RunSQL or CurrentDb.


2 Answers

If you wish to use the bound column value, you can simply refer to the combo:

sSQL = "SELECT * FROM MyTable WHERE ID = " & Me.MyCombo

You can also refer to the column property:

sSQL = "SELECT * FROM MyTable WHERE AText = '" & Me.MyCombo.Column(1) & "'"

Dim rs As DAO.Recordset     
Set rs = CurrentDB.OpenRecordset(sSQL)

strText = rs!AText
strText = rs.Fields(1)

In a textbox:

= DlookUp("AText","MyTable","ID=" & MyCombo)

*edited

like image 181
Fionnuala Avatar answered Sep 19 '22 01:09

Fionnuala


Access 2007 can lose the CurrentDb: see http://support.microsoft.com/kb/167173, so in the event of getting "Object Invalid or no longer set" with the examples, use:

Dim db as Database
Dim rs As DAO.Recordset
Set db = CurrentDB
Set rs = db.OpenRecordset("SELECT * FROM myTable")
like image 33
user2885978 Avatar answered Sep 18 '22 01:09

user2885978