简体   繁体   English

MS Access 2019:无法使用 VBA 中的 SQL 查询填充表单字段

[英]MS Access 2019: Can't populate a form field using SQL query in VBA

I want to auto-populate a field in my form based on the results of an SQL query.我想根据 SQL 查询的结果在我的表单中自动填充一个字段。 I'm just not sure of the proper syntax to get it to properly read the query.我只是不确定让它正确读取查询的正确语法。 This is what I've got, but it's not returning the value of the query, it's actually just returning the text of the query itself.这就是我所拥有的,但它没有返回查询的值,它实际上只是返回查询本身的文本。

Private Sub PurchBatchNo_Enter()

Dim MostRecentPurchBatch As String
MostRecentPurchBatch = "SELECT Max(PurchaseBatchNo) FROM purchases"
Me.PurchBatchNo.Value = MostRecentPurchBatch

End Sub

I'm sure the issue has to do with the quotation marks, but it doesn't work without them either, and I'm not sure how to write it properly.我确定问题与引号有关,但没有它们也不起作用,我不确定如何正确编写它。

Thanks for being here for beginners like me!感谢像我这样的初学者来到这里!

All your code does is set a variable to a string of characters then attempts to set value of field with that string.您的代码所做的只是将变量设置为字符串,然后尝试使用该字符串设置字段的值。

But why would you want to populate field with a value already used in a record?但是,为什么要使用已在记录中使用的值填充字段呢? Most likely you need to increment by 1.您很可能需要增加 1。

To use an SQL statement, would have to open a recordset object then reference field of recordset.要使用 SQL 语句,必须打开记录集 object 然后引用记录集的字段。

Private Sub PurchBatchNo_Enter()
Dim MostRecentPurchBatch As DAO.Recordset
If IsNull(Me.PurchBatchNo) Then
    Set MostRecentPurchBatch = CurrentDb.OpenRecordset("SELECT Max(PurchaseBatchNo) AS MaxBatch FROM purchases")
    Me.PurchBatchNo = MostRecentPurchBatch!MaxBatch + 1
End If
End Sub

However, pulling a single value from table is what domain aggregate functions are good for.但是,从表中提取单个值是域聚合函数的优点。

Private Sub PurchBatchNo_Enter()
If IsNull(Me.PurchBatchNo) Then Me.PurchBatchNo = DMax("PurchaseBatchNo", "purchases") + 1
End Sub

Instead of using VBA procedure, consider just setting DefaultValue property of textbox bound to PurchBatchNo field with the DMax() expression.不要使用 VBA 过程,而是考虑使用 DMax() 表达式设置绑定到 PurchBatchNo 字段的文本框的 DefaultValue 属性。 As soon as record is initiated by input to another textbox, the PurchBatchNo will populate.一旦通过对另一个文本框的输入启动记录,就会填充 PurchBatchNo。

If user should not be able to edit this value, set textbox as Locked Yes and TabStop No and use a different event for the VBA code if you go with VBA.如果用户无法编辑此值,请将文本框设置为 Locked Yes 和 TabStop No,如果您使用 go 和 Z6E3EC7E6A9F6007B4838FC0EE793A809,则对 VBA 代码使用不同的事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM