【问题标题】:MS Access create forms for distinct field value in VBAMS Access 为 VBA 中的不同字段值创建表单
【发布时间】:2017-09-05 14:45:38
【问题描述】:
我有一个 VBA 脚本,我需要根据表中不同的 LocationID 创建表单。因此,对于 LocationID = 1 的每一行,创建一个表单,该表单的名称在表单标题“formLocation1”中表示。然后对于每个 LocationID = 2,创建另一个表单,在标题中使用该表单的名称“formLocation2”等。在 VBA 脚本中使用 DoCmd.OpenForm"" 执行此操作的最佳方法是什么?
【问题讨论】:
标签:
vba
forms
ms-access
distinct
【解决方案1】:
你可以试试这样的。
遍历记录集,并使用CreateForm() 方法为每个LocationID 创建一个表单。然后您可以将表单的.Caption 属性设置为“formLocation(LocationID)”。
(将T 更改为您的表名)。
Public Sub CreateForms()
On Error GoTo ex
Dim rs As DAO.Recordset
Set rs = CurrentDb().OpenRecordset("SELECT DISTINCT LocationID FROM T ORDER BY LocationID;", dbOpenSnapshot)
With rs
If .EOF Then GoTo out
.MoveLast
.MoveFirst
End With
Dim frm As Access.Form, i As Integer
For i = 1 To rs.RecordCount
Set frm = CreateForm()
frm.Caption = "formLocation" & rs![LocationID]
DoCmd.Close acForm, frm.Name, acSaveYes
Set frm = Nothing
rs.MoveNext
Next i
out:
On Error Resume Next
rs.Close
Set rs = Nothing
On Error GoTo 0
Exit Sub
ex:
MsgBox Err.Description, vbCritical
Resume out
End Sub