2013-11-20 102 views
0

我在窗體構造函數中有兩段代碼。它們相當於95%,但我不知道如何簡單(VB新手,來自PHP/C/C++ /其他非腳本語言)。有人可以幫我嗎?如何製作一個模板,或者只是創建一個共享類或者只是一些全局變量來使用它? :-o簡化訪問VBA代碼

件:

Private Sub AddOne_Click() 
    If isNull(Forms![Constructor]!FieldOne.value) Then 
     MsgBox ("Please, fill the field one") 
    Else 
     Dim workspace As DAO.workspace 
     Dim recordset As DAO.recordset 

     Set workspace = DBEngine.Workspaces(0) 'The current database 

     workspace.BeginTrans 'Start the transaction buffer 

     Set recordset = CurrentDb.OpenRecordset("One", dbOpenDynaset) 

     With recordset 
      .AddNew 
       !One = Forms![Constructor]!FieldOne.value 
      .Update 
     End With 

     workspace.CommitTrans 'Commit the transaction to dataset 

     MsgBox ("New '" + Forms![Constructor]!FieldOne.value + "' added successfully") 

     Forms![Constructor]!FieldOne.value = Null 
    End If 
End Sub 

Private Sub AddTwo_Click() 
    If isNull(Forms![Constructor]!FieldTwo.value) Then 
     MsgBox ("Please, fill the field two") 
    Else 
     Dim workspace As DAO.workspace 
     Dim recordset As DAO.recordset 

     Set workspace = DBEngine.Workspaces(0) 'The current database 

     workspace.BeginTrans 'Start the transaction buffer 

     Set recordset = CurrentDb.OpenRecordset("Two", dbOpenDynaset) 

     With recordset 
      .AddNew 
       !Two = Forms![Constructor]!FieldTwo.value 
      .Update 
     End With 

     workspace.CommitTrans 'Commit the transaction to dataset 

     MsgBox ("New '" + Forms![Constructor]!FieldTwo.value + "' added successfully") 

     Forms![Constructor]!FieldTwo.value = Null 
    End If 
End Sub 

回答

0

不知道爲什麼你標記過這個「的VBScript」 - 看起來像訪問我(OTOH這是不可能鍵入VBScript中的變量,OTH你已經使用'bang'操作符)。總之:

1)添加一個標準模塊。

2)下面的輔助函數添加到模塊:

Function Add(RecordsetName As String, FieldName As String) 
    If isNull(Forms![Constructor].Fields(FieldName).value) Then 
     MsgBox ("Please, fill " + FieldName) 
    Else 
     Dim workspace As DAO.workspace 
     Dim recordset As DAO.recordset 
     Set workspace = DBEngine.Workspaces(0) 'The current database 
     workspace.BeginTrans 'Start the transaction buffer 
     Set recordset = CurrentDb.OpenRecordset(RecordsetName, dbOpenDynaset) 
     With recordset 
      .AddNew 
       .Fields(FieldName).Value = Forms![Constructor].FieldName(FieldName).value 
      .Update 
     End With 
     workspace.CommitTrans 'Commit the transaction to dataset 
     MsgBox ("New '" + Forms![Constructor].Fields(FieldName).value + "' added successfully") 
     Forms![Constructor].Fields(FieldName).value = Null 
    End If 
End Sub 

3)現有onclick處理現在可以用

=Add("One", "FieldOne") 

=Add("Two", "FieldTwo") 

在替換屬性窗格和從窗體模塊中刪除的當前方法處理程序。