简体   繁体   English

如何在Access VBA中使用SQL SELECT语句

[英]How to use a SQL SELECT statement with Access VBA

I have a combobox whose value I want to use with a SQL WHERE clause. 我有一个组合框,其值我想与SQL WHERE子句一起使用。 How do you run a SELECT statement inside VBA based on the combobox value? 如何根据组合框值在VBA中运行 SELECT语句?

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: 您还可以参考column属性:

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 *编辑

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: Access 2007可能会丢失CurrentDb:请参阅http://support.microsoft.com/kb/167173 ,因此如果使用示例获取“对象无效或不再设置” ,请使用:

Dim db as Database
Dim rs As DAO.Recordset
Set db = CurrentDB
Set rs = db.OpenRecordset("SELECT * FROM myTable")

Here is another way to use SQL SELECT statement in VBA: 这是在VBA中使用SQL SELECT语句的另一种方法:

 sSQL = "SELECT Variable FROM GroupTable WHERE VariableCode = '" & Me.comboBox & "'" 
 Set rs = CurrentDb.OpenRecordset(sSQL)
 On Error GoTo resultsetError 
 dbValue = rs!Variable
 MsgBox dbValue, vbOKOnly, "RS VALUE"
resultsetError:
 MsgBox "Error Retrieving value from database",VbOkOnly,"Database Error"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM