2014-04-03 38 views
1

我在MS Access 2010中有一堆表單。它們都是綁定的表單,但是我欺騙它們僅在單擊btnSave時才保存。如何從模塊(VBA)中的MS Access中獲取實際表單的實例

主要的問題是我有相當多的代碼是相同的一些事件,如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 

我想做到這一切在短短的一個模塊,但我可以」 t找到一種方法來獲取當前表單的實際實例。任何幫助將不勝感激。

感謝

回答

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 
+0

太棒了!謝謝@enderland它的作品完美,我應該問過這個,現在我有20個表格來更新。 – EricPb

+0

@EricPb我知道你的意思,我有類似的問題,有一天剛剛崩潰,花了一個....而更新所有這些有這樣的事情。相信我,你會感激(特別是因爲我對大多數開放/關閉/當前事件進行回調,這些回調在很多形式上都是相同的)。 – enderland

0

要獲取活動窗體,可以使用以下代碼。

Screen.ActiveForm.Name 

然後,您可以創建一個新對象並將其設置爲ActiveForm。

Public obj_Form As Access.Form 
Set obj_Form = Forms!MyActiveForm 
相關問題