sql - MS Access VBA 代码根据表单上的组合框选择运行特定查询
问题描述
我目前正在尝试开发 VBA 代码(case 语句),它将根据用户从表单上的组合框中选择的查询名称运行特定查询。目前正在运行的查询与用户从组合框中选择的内容不一致。
例如:
- 当用户选择 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 – 行源 SQL
SELECT tblQueries.QryID, tblQueries.QryData, tblQueries.QryName, tblQueries.QryGroup
FROM tblQueries
WHERE (((tblQueries.QryGroup)="Plants"));
不幸的是,我不太确定如何解决这个问题,因为 Row Source SQL 和 After Update Event VBA 对我来说似乎是合乎逻辑的(但显然我遗漏了一些东西)。
解决方案
实际上,由于要执行的查询的名称出现在您的 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 代码。此代码将动态处理表中的任意数量的行。
推荐阅读
- javascript - 使用 fs.writefilesync 在 nodejs 中写入文件
- sql - 如果不存在则插入
- java - 在带弹簧休息的全局异常处理程序中使用通用异常类处理程序是一种好习惯吗?
- c - C - 如何使用 while feof 循环来解决空输入文件问题?
- hyperledger - pbft中的leader是如何选出的?
- spring - 如何在 Spring 中自动装配没有实现的接口或抽象类
- javascript - 为什么 Slick Slider slickGoTo 方法不起作用?
- angular - 如何使用 rxjs 6 异步过滤数组的 Observable
- jquery - 随机 ajax 加载的画廊缩略图在高度上被切断(未完全显示)?
- php - 如何访问“最终余额”