如何从模块(VBA)中的MS Access获取实际表单的实例

时间:2014-04-03 20:55:03

标签: vba ms-access

我在MS Access 2010中有一堆表单。所有这些表单都是绑定表单,但我欺骗它们只在我点击btnSave后保存。

主要问题是,我在form_beforeUpdate()form_afterUpdate()form_Load()等某些事件中的每个表单都有相当多的代码。一个例子:

Private Sub btnSave_Click()
 'Check first that all fields have been filled
 If CheckAllFields = True Then
     Exit Sub
 End If
 TempSaveRecord = True
 Me.Dirty = False 'this will make an attempt of form_Update()
 Form_Load 'After Saving we restart the data
End Sub

Private Sub Form_BeforeUpdate(Cancel As Integer)
 If TempSaveRecord = False Then
   Me.Undo
   Exit Sub
 End If
End Sub

CheckAllFields只是一个检查所有必填字段是否都不是null的例程:

Private Function CheckAllFields() As Boolean
  Dim Ctrl As Control
  CheckAllFields = False

  'Check for unfilled fields
  For Each Ctrl In Me.Controls
     If Ctrl.Tag = "required" And IsNull(Ctrl) Then
                MsgBox "The field " & Ctrl.Name & " has not been filled."
        CheckAllFields = True
        Exit For
     End If
  Next Ctrl
End Function

我想在一个模块中完成所有这些操作,但是在那一刻我无法找到获取表单实际实例的方法。任何帮助都会非常感激。

由于

2 个答案:

答案 0 :(得分:1)

我一直这样做。

以下是一个例子:

'in a main module
Public Sub mFormLoad(p_form As Form)
    'do stuff with p_form
end sub

然后,在实际形式中:

Private Sub Form_Load()
    mFormLoad Me
End Sub

对于您的示例,将您的函数更改为公共函数并添加表单的参数:

public Function CheckAllFields(p_form as form) As Boolean
  Dim Ctrl As Control
  CheckAllFields = False

  'Check for unfilled fields
  For Each Ctrl In p_form.Controls
     If Ctrl.Tag = "required" And IsNull(Ctrl) Then
                MsgBox "The field " & Ctrl.Name & " has not been filled."
        CheckAllFields = True
        Exit For
     End If
  Next Ctrl
End Function

然后将您调用的行更改为:

If CheckAllFields(me) = True Then

答案 1 :(得分:0)

要获取活动表单,您可以使用以下代码。

Screen.ActiveForm.Name

然后您可以创建一个新对象并将其设置为ActiveForm。

Public obj_Form As Access.Form
Set obj_Form = Forms!MyActiveForm