简化Access VBA代码

时间:2013-11-20 20:39:14

标签: access-vba

我的表单构造函数中有两段代码。它们相当于95%,但我不知道如何简单地使用它(VB新手来自PHP / C / C ++ /其他非脚本语言)。有人可以帮我吗?如何制作模板,或者只是创建共享类或只使用一些全局变量来使用它? :-o

片断是:

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

1 个答案:

答案 0 :(得分:0)

不确定为什么你标记了这个'vbscript' - 看起来像对我的访问(OTOH它不可能在VBScript中输入变量,而你已经使用了'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")

在“属性”窗格中,并从表单模块中删除当前方法处理程序。