有没有一种方法可以简化保存/更新模块?

时间:2018-07-05 07:45:18

标签: vba ms-access

我正在编写一个具有几个表和字段的应用程序,这些表和字段当然需要保存和更新。每个部分(例如一个页面)都有自己的模块,该模块具有保存/更新/删除子项。

这是保存模块内部的保存子示例:

Public Sub saveRecToStaff(FirstName As String, LastName As String, Address As String, Email As String, PhoneNumber As String, Status As String)
Dim rstSave As New ADODB.Recordset
rstSave.ActiveConnection = CurrentProject.Connection
rstSave.CursorType = adOpenDynamic
rstSave.LockType = adLockOptimistic

rstSave.Open "SELECT FirstName, LastName, Address, Email, PhoneNumber, Status FROM Staff"
rstSave.addNew

rstSave.Fields("FirstName").Value = FirstName
rstSave.Fields("LastName").Value = LastName
rstSave.Fields("Address").Value = Address
rstSave.Fields("Email").Value = Email
rstSave.Fields("PhoneNumber").Value = PhoneNumber
rstSave.Fields("Status").Value = Status
rstSave.update

rstSave.Close
Set rstSave = Nothing
End Sub

一段时间以来,我一直在想,也许有一种方法可以简化此过程。例如,创建一个基本函数,只要需要保存就可以简单地调用它。但是,我对VBA编码非常陌生,所以我不确定该如何处理。

任何建议将不胜感激!

编辑:更新顺序如何?

Public Sub saveRecToStaff(oldFirstName As String, FirstName As String, oldLastName As String,
LastName As String, oldAddress As String, Address As String, Email As String, PhoneNumber As String,
 Status As String)
Dim rstSave As New ADODB.Recordset
rstSave.ActiveConnection = CurrentProject.Connection
rstSave.CursorType = adOpenDynamic
rstSave.LockType = adLockOptimistic

rstUpdate.Open "SELECT FirstName, LastName, Address, Email, PhoneNumber, Status FROM Staff 
 WHERE FirstName='"& oldFirstName & "' AND LastName='" & oldLastName & "' AND Address='" & oldAddress & "'"

If (rstUpdate.EOF = False) Then
rstUpdate.update
rstUpdate.Fields("FirstName").Value = FirstName
rstUpdate.Fields("LastName").Value = LastName
rstUpdate.Fields("Address").Value = Address
rstUpdate.Fields("Email").Value = Email
rstUpdate.Fields("PhoneNumber").Value = PhoneNumber
rstUpdate.Fields("Status").Value = Status
rstUpdate.update
End If

rstSave.Close
Set rstSave = Nothing
End Sub

1 个答案:

答案 0 :(得分:3)

通过切换到DAO,您可以轻松地使用简短的代码。通过使用With,不需要声明记录集并自动关闭:

Public Sub saveRecToStaff(FirstName As String, LastName As String, Address As String, Email As String, PhoneNumber As String, Status As String)
    With CurrentDb.TableDefs!Staff.OpenRecordset
        .AddNew
        .Fields("FirstName").Value = FirstName
        .Fields("LastName").Value = LastName
        .Fields("Address").Value = Address
        .Fields("Email").Value = Email
        .Fields("PhoneNumber").Value = PhoneNumber
        .Fields("Status").Value = Status
        .Update
    End With
End Sub

但是,您也可以使用绑定表,然后就不需要使用任何VBA来添加新行。您只能使用内置的表单功能。