如果主表单上有多个子表单,则从ACTIVE子表单打开记录

时间:2018-02-01 16:26:39

标签: vba ms-access subforms

我有一个主要表单[frmHome]。它有两个子表单[sbfHome]& [sbfRemarkHome]

我希望用户能够点击任一表单上任何记录中的任何字段,并打开一个包含该记录的所有相关数据的新表单。

我已经尝试了.ActiveControl,因为它总是错误的。

我也尝试使用ActiveForm.Name并在我的代码的EOF / BOF部分中进行此操作。

我如何知道哪个子表单具有焦点?

 Private Sub btnSummary_Click()
 Dim frmCurrentForm As String
 frmCurrentForm = ActiveForm.Name

 If Not (Me.frmCurrentForm.Form.Recordset.EOF And 
 Me.frmCurrentForm.Form.Recordset.BOF) Then
    With Me.frmCurrentForm.Form.Recordset
      txtEARNumber = .Fields("EAR Number")
    End With
 End If

DoCmd.OpenForm "frmView"
[Forms]![frmView].txtEARNumber = txtEARNumber
Forms!frmView.Form.Requery
Forms!frmView.Refresh
End Sub

 Private Sub btnSummary_Click()

 If Me.sbfHome.Form.ActiveControl = True Then

    If Not (Me.sbfHome.Form.Recordset.EOF And Me.sbfHome.Form.Recordset.BOF) 
    Then
        With Me.sbfHome.Form.Recordset
          txtEARNumber = .Fields("EAR Number")
        End With
    End If

Else

     If Not (Me.sbfRemarkHome.Form.Recordset.EOF And 
       Me.sbfRemarkHome.Form.Recordset.BOF) Then
       With Me.sbfRemarkHome.Form.Recordset
        txtEARNumber = .Fields("EAR")
       End With
     End If

End If

DoCmd.OpenForm "frmView"
[Forms]![frmView].txtEARNumber = txtEARNumber
Forms!frmView.Form.Requery
Forms!frmView.Refresh
End Sub

1 个答案:

答案 0 :(得分:0)

我想我理解你的问题。我建议使用事件来告诉父对象在子窗体上执行了哪些操作。这种方式本身的重点并不重要,重要的是行动发生的地方。这也意味着两个物体之间的耦合更加松散。

在我的示例中,我制作了3个表单:MasterSubForm1SubForm2。我将两个子表单绑定到一个包含一些模拟数据的表,并将它们设为continuous forms。布局如下所示:

enter image description here

每个子表单中的代码都是相同的:

Option Compare Database
Option Explicit

Public Event ButtonClicked(FormName As String, RecordId As Long)

Private Sub Command0_Click()
    RaiseEvent ButtonClicked(Me.Name, Me.ID)
End Sub

这表示只要单击Command0按钮,它就会引发ButtonClicked事件。您可以根据需要在事件中自定义这些参数。

然后在主表单中,你可以听到这样的事件:

Option Compare Database
Option Explicit

Private WithEvents SubForm1 As Form_SubForm1
Private WithEvents SubForm2 As Form_SubForm2

Private Sub Form_Load()
    Set SubForm1 = frmSubForm1.Form
    Set SubForm2 = frmSubForm2.Form
End Sub


Private Sub SubForm1_ButtonClicked(FormName As String, RecordId As Long)
    DoSomething FormName, RecordId
End Sub


Private Sub SubForm2_ButtonClicked(FormName As String, RecordId As Long)
    DoSomething FormName, RecordId
End Sub


Private Sub DoSomething(FormName As String, RecordId As Long)
    txtMessages = "Form Name: " & FormName & ", Record ID: " & RecordId
End Sub

enter image description here enter image description here