【问题标题】:Access: passing value to a parameter query using VBA?访问:使用 VBA 将值传递给参数查询?
【发布时间】:2016-06-11 20:59:57
【问题描述】:

我有一个带有参数查询(粉红色)的 Access 表单。这是我的表格:

当用户选择一个物种时,Access 使用选项组(称为“speciesSelection”)生成的数字在表中查找物种名称,并且它可以工作。但是,我想将物种名称传递给参数查询,以便记录集可以作为突出显示的组合框 (Combo12) 的数据源。但是,当我选择一个物种时,组合框是空白的。这是我的代码:

Private Sub speciesSelection_AfterUpdate()
Dim dbs As Database
Dim qdf As QueryDef
Dim rst As Recordset

Set dbs = CurrentDb

'Get species name of the current Cases instance'
Dim speciesChosen As String
speciesChosen = DLookup("Species", "tblSpeciesList", "ID=" & speciesSelection)

'Get the parameter query
Set qdf = dbs.QueryDefs("qryClinicalObservations")

'Supply the parameter value
qdf.Parameters("enterSpecies") = speciesChosen

'Open a Recordset based on the parameter query
Forms!inputForm.Controls!Combo12.RowSource = qdf.OpenRecordset()
End Sub

我使用向导创建了我的查询。这是一张快照:

在标准部分,我可以在出现提示时手动输入一个物种(例如“猫”),它可以工作。但不是我的 VBA 代码...

有明显的错误吗? Combo12 好像没有被识别出来。

编辑:

这是我的新代码。实际上,Combo12 位于一个名为observationsSubform 的子表单中。这是我的代码和新表格。如您所见,下拉菜单,但选项不可见:

Private Sub speciesSelection_AfterUpdate()
Dim dbs As Database
Dim qdf As QueryDef
Dim rst As Recordset

Set dbs = CurrentDb

'Get species name of the current Cases instance'
Dim speciesChosen As String
speciesChosen = DLookup("Species", "tblSpeciesList", "ID=" & speciesSelection)

MsgBox (speciesChosen)

'Get the parameter query
Set qdf = dbs.QueryDefs("qryClinicalObservations")

'Supply the parameter value
qdf!enterSpecies = speciesChosen

Set Me!observationsSubform!Combo12.Recordset = qdf.OpenRecordset()

【问题讨论】:

  • 看起来您的组合框有 2 列,第一列不可见,但您的查询只返回一列,因此可见的组合框列是空的。

标签: ms-access vba ms-access-2010 ms-access-2007 ms-access-2013


【解决方案1】:

组合框的RowSource 是一个字符串属性,因此您不能将Recordset 对象分配给它。将您的 Recordset 分配给组合的 Recordset 属性。

因为这是一个对象赋值,所以使用 Set 关键字。

Set Forms!inputForm!Combo12.Recordset = qdf.OpenRecordset()

如果 Combo12speciesSelection 都包含在同一个表单 (inputForm) 中,您可以改用它...

Set Me!Combo12.Recordset = qdf.OpenRecordset()

【讨论】:

  • 非常感谢您的回答!我刚刚意识到 Combo 12 位于一个名为observationsSubform 的子表单中。现在可以识别 Combo12,下拉菜单有效,但我看不到任何条目。所以,我快到了?你能看看编辑吗?谢谢! :)
  • 您检查过qdf.OpenRecordset() 是否返回任何行吗?
  • 其实挺好用的,就是栏目编辑的问题! :) 现在,它完美运行!再次非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-27
  • 2014-08-23
相关资源
最近更新 更多