MS Access在VBA中为不同的字段值创建表单

问题描述:

我有一个VBA脚本,我需要根据表中不同的LocationID创建表单。因此,对于LocationID = 1的每一行,都会创建一个表单,该表单的名称以表单的标题“formLocation1”表示。然后,对于每个LocationID = 2,在标题“formLocation2”等中创建另一个名称为form的表单。使用VBA脚本中的DoCmd.OpenForm“”来完成此操作的最佳方法是什么?MS Access在VBA中为不同的字段值创建表单

你可以尝试这样的事情。

循环遍历记录集,并使用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