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

时间:2012-06-13 14:27:20

标签: sql ms-access vba

我有一个组合框,其值我想与SQL WHERE子句一起使用。如何根据组合框值在VBA中运行一个SELECT语句?

3 个答案:

答案 0 :(得分:26)

如果您想使用绑定列值,您可以简单地参考组合:

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

您还可以参考列属性:

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)

在文本框中:

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

答案 1 :(得分:7)

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")

答案 2 :(得分:2)

以下是在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"