MS 访问 VBA 代码以根据表单上的组合框选择运行特定查询



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

例如:

  • 当用户选择 PlantNames (QryID 5( 而不是运行 qryPlantsLatin 查询(这是正确的(时,它正在运行 qryNewPlants2 查询(这是不正确的(。
  • 当用户选择PlantInventory (QryID 3(时,它不是运行qryNewPlants2查询(这是正确的(,而是运行qryPlantsLatin查询(这是不正确的(。
  • 当用户选择 PlantInventoryAvailable (QryID 4( 而不是运行 qryPlantInventoryTotal 查询(这是正确的(时,它正在运行 qryPlantsLatin 查询(这是不正确的(。

代码: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 – Row Source SQL

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

不幸的是,我不太确定如何解决这个问题,因为行源 SQL 和更新后事件 VBA 对我来说似乎是合乎逻辑的(但显然我错过了一些东西(。

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

这是您的问题中所述的组合框行源:

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

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

现在,只需检查是否已进行有效的选择(即 ComboBox 不为 null 或空白(,然后执行查询,从 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 代码。 此代码将动态处理表中任意数量的行。

尝试:

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

最新更新