首页 > 解决方案 > MS Access VBA 代码根据表单上的组合框选择运行特定查询

问题描述

我目前正在尝试开发 VBA 代码(case 语句),它将根据用户从表单上的组合框中选择的查询名称运行特定查询。目前正在运行的查询与用户从组合框中选择的内容不一致。

例如:

代码:VBA – 使用的事件处理程序 – 更新后

Private Sub cboPlantQrys_AfterUpdate()
Select Case PlantQueries
Case Me.cboPlantQrys = "5"
     DoCmd.Close
     DoCmd.OpenQuery "qryPlantsLatin" 
Case Me.cboPlantQrys = "3"   
     DoCmd.Close
     DoCmd.OpenQuery "qryNewPlants2"    
Case Me.cboPlantQrys = "4"
     DoCmd.Close
     DoCmd.OpenQuery "qryPlantInventoryTotal"
Case Else
     MsgBox "Improper Selection"
End Select
End Sub

ComboBox – cboPlantQrys – 行源 SQL

SELECT tblQueries.QryID, tblQueries.QryData, tblQueries.QryName, tblQueries.QryGroup
FROM tblQueries
WHERE (((tblQueries.QryGroup)="Plants"));

不幸的是,我不太确定如何解决这个问题,因为 Row Source SQL 和 After Update Event VBA 对我来说似乎是合乎逻辑的(但显然我遗漏了一些东西)。

标签: sqlms-accessvba

解决方案


实际上,由于要执行的查询的名称出现在您的 ComboBox RowSource 中,因此您可以大大简化代码。

这是您的问题中所述的 ComboBox RowSource:

SELECT tblQueries.QryID, tblQueries.QryData, tblQueries.QryName, tblQueries.QryGroup
FROM tblQueries
WHERE (((tblQueries.QryGroup)="Plants"));

这意味着 ComboBox 在运行时将有 4 列。在 Access VBA 代码中引用 ComboBox 或 ListBox 列时,列编号从 0(零)开始。因此,该QueryName列将是第 2 列(因为它是 RowSource 中的第 3 列)。

现在,只需检查是否已做出有效选择(即 ComboBox 不为空或空白),然后执行查询,从您的 ComboBox 记录源中动态提取名称。

Private Sub cboPlantQrys_AfterUpdate()

'Easiest way to check for Null or Empty String is the following
'When you concatenate a possible Null with a zero length string
'the result is a string, therefore if the Length of this is greater
'then zero, we know the user chose an item in the ComboBox list.
If Len(Me.cboPlantQrys & "") > 0 Then
    DoCmd.Close
    Docmd.OpenQuery Me.cboPlantQrys.Column(2)
End If

End Sub

使用此代码,您不再需要在tblQueries表中添加或删除查询(记录)时更新 VBA 代码。此代码将动态处理表中的任意数量的行。


推荐阅读