2017-09-05 83 views
0

我有一個VBA腳本,我需要根據表中不同的LocationID創建表單。因此,對於LocationID = 1的每一行,都會創建一個表單,該表單的名稱以表單的標題「formLocation1」表示。然後,對於每個LocationID = 2,在標題「formLocation2」等中創建另一個名稱爲form的表單。使用VBA腳本中的DoCmd.OpenForm「」來完成此操作的最佳方法是什麼?MS Access在VBA中爲不同的字段值創建表單

回答

0

你可以嘗試這樣的事情。

循環遍歷記錄集,並使用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