Introduction to Record Sets in the Microsoft Access Object Library |
|
Introduction to a Record Set
Overview
The records of a table or a query are grouped in an object referred to as a set of records also called a record set. A record set is of type Object. To use it, declare a variable of type Object. Before using it, use the Set operator to assign it to the object that would use it. Here is an example:
Private Sub cmdRecordset_Click() ' Create a recordset Dim rstTimeSheet As Object ' Specify that the record set points to the records of this form Set rstTimeSheet = ... End Sub
Most of the time, you use an Object object without being aware because the database engine handles all or most of the necessary routines behind the scenes. In some other cases, you must create or initialize an Object object in order to use it. You have various options.
Practical Learning: Introducing Record Sets
Based on their behaviors, there are various categories of record sets:
The Record Set of a Control
Some controls, such as the combo box or the list box, are meant to hold a list of values. We also know that a form or a report is primarily created to show one or more records. Such controls hold their own record set. If you create a record set and want to initialize it with the values held in the form where it is called, you can simply assign it Me.Recordset. Here is an example:
Private Sub cmdRecordset_Click()
' Create a recordset
Dim rstTimeSheet As Object
' Specify that the record set points to the records of this form
Set rstTimeSheet = Me.Recordset
End Sub
When a form is equipped to display the values of a list, that form has a record set that represents its records. Once again, remember that there are various other ways you can initialize a record set.
Opening a Record Set
To let you create a record set, the database class of the Microsoft Access Object Library provides a method named OpenRecordset. The syntax of this method is:
Public Function OpenRecordset(ByVal Expression As String, ByVal Optional Type As Variant, ByVal Optional OptionsAs Variant, ByVal Option Lockedits As Variant) As Object
The variable that calls this method can be of type Object. It can be the current database or another database. The only required argument of this method is the Expression, which is passed as a string. This can be the name of a table or a query. Here is an example:
Private Sub cmdGetEmployees_Click()
Dim dbKoloBank As Object
Dim rstEmployees As Object
Set dbKoloBank = CurrentDb
Set rstEmployees = dbKoloBank.OpenRecordset("Employees")
End Sub
Closing a Record Set
After using a record set, you should (strongly) close it. To let you close a record set, its class is equipped with a method named Close. Here is an example of calling it:
Private Sub cmdTableReference_Click()
Dim rstEmployees As Object
. . . Use the record set here
rstEmployees.Close
End Sub
As an option, after closing the record set, you can release the resources it was using and make them available to other applications that would need them. To do this, assign the Nothing value to the record set variable. Here is an example:
Private Sub cmdTableReference_Click()
Dim rstEmployees As Object
. . . Use the record set here
rstEmployees.Close
Set rstEmployees = Nothing
End Sub
Introduction to the Records of a Record Set
Introduction to Data Entry
After opening and then getting a record set, you can create a new record. To support the creation of a record, the record set is equipped with a method named AddNew method. Here is an example of calling it:
Private Sub cmdDataEntry_Click()
Dim curDatabase As Object
Dim rstEmployees As Object
Set curDatabase = CurrentDb
Set rstEmployees = curDatabase.OpenRecordset("Employees")
rstEmployees.AddNew
Set rstEmployees = Nothing
Set curDatabase = Nothing
End Sub
This method only indicates that you want to create a new record. To actually create a record, specify a value for the columns of the table. To do this, you can access a field using its name indexed property. It is equipped with a property named Value. To specify the new value of a column, assign the desired value to this property applied to the column. Here is an example of specifying a new value for a column named FirstName from a table named Employees:
Private Sub cmdDataEntry_Click()
Dim curDatabase As Object
Dim rstEmployees As Object
Set curDatabase = CurrentDb
Set rstEmployees = curDatabase.OpenRecordset("Employees")
rstEmployees.AddNew
rstEmployees("Something").Value = ...
Set rstEmployees = Nothing
Set curDatabase = Nothing
End Sub
Updating a Record
After adding a new record, you must ask the record set to receive the new value. To support this, the record set is equipped with a method named Update. Call this method after specifying a value for thecolumns. Here is example:
Private Sub cmdCreateTable_Click()
Dim curDatabase As Object
Dim tblEmployees As Object
Dim fldFirstName As Object, fldLastName As Object
' Get a reference to the current database
Set curDatabase = CurrentDb
' Create a new table named Employees
Set tblEmployees = curDatabase.CreateTableDef("Employees")
Set fldFirstName = tblEmployees.CreateField("FirstName", dbText)
tblEmployees.Fields.Append fldFirstName
Set fldLastName = tblEmployees.CreateField("LastName", dbText)
tblEmployees.Fields.Append fldLastName
' Add the Employees table to the current database
curDatabase.TableDefs.Append tblEmployees
End Sub
Private Sub cmdDataEntry_Click()
Dim curDatabase As Object
Dim rstEmployees As Object
Set curDatabase = CurrentDb
Set rstEmployees = curDatabase.OpenRecordset("Employees")
rstEmployees.AddNew
rstEmployees("FirstName").Value = ...
rstEmployees("LastName").Value = ...
rstEmployees.Update
Set rstEmployees = Nothing
Set curDatabase = Nothing
End Sub
Data Entry in a Record Set Based on Type
Data Entry With Strings
In a record set, the value of a string-based field is provided in double-quotes. Here are examples:
Private Sub cmdAddEmployee_Click()
On Error GoTo cmdAddEmployee_Click_Error
Dim curDatabase As Object
Dim rstEmployees As Object
Set curDatabase = CurrentDb
Set rstEmployees = curDatabase.OpenRecordset("Employees")
With rstEmployees
.AddNew
.Fields("EmployeeNumber").Value = "608-285"
.Fields("FirstName").Value = "Elizabeth"
.Fields("LastName").Value = "Eloundou"
.Update
End With
Set rstEmployees = Nothing
Set curDatabase = Nothing
MsgBox "The employee has been hired.", _
vbOKOnly Or vbInformation, "Kolo Bank"
cmdAddEmployee_Click_Exit:
Exit Sub
cmdAddEmployee_Click_Error:
MsgBox "For some strange reason, the employee was not hired.", _
vbOKOnly Or vbInformation, "Kolo Bank"
Resume cmdAddEmployee_Click_Exit
End Sub
Data Entry With Numeric Values
To provide the value of a number-based field, simply assign it. Here is an example:
Private Sub cmdAddEmployee_Click() On Error GoTo cmdAddEmployee_Click_Error Dim curDatabase As Object Dim rstEmployees As Object Set curDatabase = CurrentDb Set rstEmployees = curDatabase.OpenRecordset("Employees") With rstEmployees .AddNew .Fields("EmployeeNumber").Value = "204-058" .Fields("FirstName").Value = "Richard" .Fields("LastName").Value = "Kelsun" .Fields("HourlySalary").Value = 16.85 .Update End With Set rstEmployees = Nothing Set curDatabase = Nothing MsgBox "The employee has been hired.", _ vbOKOnly Or vbInformation, "Kolo Bank" cmdAddEmployee_Click_Exit: Exit Sub cmdAddEmployee_Click_Error: MsgBox "For some strange reason, the employee was not hired.", _ vbOKOnly Or vbInformation, "Kolo Bank" Resume cmdAddEmployee_Click_Exit End Sub
Data Entry With Boolean Values
To specify the value of a dbBoolean or DB_BOOLEAN Boolean field, assign True or False to it. Here is an example:
Private Sub cmdAddEmployee_Click() On Error GoTo cmdAddEmployee_Click_Error Dim curDatabase As Object Dim rstEmployees As Object Set curDatabase = CurrentDb Set rstEmployees = curDatabase.OpenRecordset("Employees") With rstEmployees .AddNew .Fields("EmployeeNumber").Value = "942-9274" .Fields("FirstName").Value = "Frank" .Fields("LastName").Value = "Alley" .Fields("HourlySalary").Value = 32.85 .Fields("CanCreateNewAccount").Value = True .Update End With Set rstEmployees = Nothing Set curDatabase = Nothing MsgBox "The employee has been hired.", _ vbOKOnly Or vbInformation, "Kolo Bank" cmdAddEmployee_Click_Exit: Exit Sub cmdAddEmployee_Click_Error: MsgBox "For some strange reason, the employee was not hired.", _ vbOKOnly Or vbInformation, "Kolo Bank" Resume cmdAddEmployee_Click_Exit End Sub
The Visual Basic language, the compiler can consider numeric values for Boolean fields. This means that you can assign any number (positive or negative) in place of True and 0 in place of False for the Value property or a Boolean field. If you assign 0, the field would receive a value of False, equivalent to an empty check box. If you assign any other value, the field would receive a value of True, which is the same as the check box being checked.
Data Entry With Date/Time Values
To programmatically perform data entry on a column created for a date or a time type, you can provide the value as a date/time or as a string. If you are providing the value as date or time, use any of the formulas we reviewed for date/time value and include the value between # and #
You can provide the value of a date as a string. In this case, you should (must) use an appropriate formula with the year represented by 2 or 4 digits. If you want to specify the year with 2 digits, use the formula:
mm/dd/yyyy
or
mm-dd-yy
If you want to use a 4-year digit, apply the following formula:
mm/dd/yyyy
or
mm-dd-yyyy
The year with 4 digits is more precise as it properly expresses a complete year. A month from January to September can be represented as 1, 2, 3, 4, 5, 6, 7, 8, or 9. Day numbers follow the same logic. Here are examples:
Private Sub cmdTable_Click() Dim curDatabase As Object Dim colFullName As Object Dim tblEmployees As Object Dim colStartVacationDate As Object Dim colEndVacationDate As Object Set curDatabase = CurrentDb Set tblEmployees = curDatabase.CreateTableDef("Employees") Set colFullName = tblEmployees.CreateField("Full Name", DB_TEXT, 80) tblEmployees.Fields.Append colFullName Set colStartVacationDate = tblEmployees.CreateField("Start Vacation Date", DB_DATE) tblEmployees.Fields.Append colStartVacationDate Set colEndVacationDate = tblEmployees.CreateField("End Vacation Date", DB_DATE) tblEmployees.Fields.Append colEndVacationDate curDatabase.TableDefs.Append tblEmployees MsgBox "A table named Employees has been created." End Sub Private Sub cmdCreateRecord_Click() Dim curDatabase As Object Dim rstEmployees As Object Set curDatabase = CurrentDb Set rstEmployees = curDatabase.OpenRecordset("Employees") rstEmployees.AddNew rstEmployees("Full Name").Value = "Peter Mukoko" rstEmployees("Start Vacation Date").Value = "04/26/2009" rstEmployees("End Vacation Date").Value = "04-26-2009" rstEmployees.Update MsgBox "A record has been added to the Employees table." Set rstEmployees = Nothing Set curDatabase = Nothing End Sub
Practical Learning: Introducing Data Entry in a Record Set
Private Sub cmdMaritalsStatusRecords_Click() Dim dbDepartmentStore As Object Dim rstMaritalsStatus As Object Set dbDepartmentStore = CurrentDb Set rstMaritalsStatus = dbDepartmentStore.OpenRecordset("MaritalsStatus") rstMaritalsStatus.AddNew rstMaritalsStatus("MaritalStatusID").Value = 1 rstMaritalsStatus("MaritalStatus").Value = "Single" rstMaritalsStatus.Update rstMaritalsStatus.AddNew rstMaritalsStatus("MaritalStatusID").Value = 2 rstMaritalsStatus("MaritalStatus").Value = "Married" rstMaritalsStatus.Update rstMaritalsStatus.AddNew rstMaritalsStatus("MaritalStatusID").Value = 3 rstMaritalsStatus("MaritalStatus").Value = "Unknown" rstMaritalsStatus.Update Set rstMaritalsStatus = Nothing Set dbDepartmentStore = Nothing End Sub
Private Sub cmdFilingsStatusRecords_Click() Dim rstFilingsStatus As Object Dim dbDepartmentStore As Object Set dbDepartmentStore = CurrentDb Set rstFilingsStatus = dbDepartmentStore.OpenRecordset("FilingsStatus") rstFilingsStatus.AddNew rstFilingsStatus("FilingStatusID").Value = 1 rstFilingsStatus("FilingStatus").Value = "Head of Household" rstFilingsStatus.Update rstFilingsStatus.AddNew rstFilingsStatus("FilingStatusID").Value = 2 rstFilingsStatus("FilingStatus").Value = "Married Filing Jointly" rstFilingsStatus.Update rstFilingsStatus.AddNew rstFilingsStatus("FilingStatusID").Value = 3 rstFilingsStatus("FilingStatus").Value = "Unknown" rstFilingsStatus.Update Set rstFilingsStatus = Nothing Set dbDepartmentStore = Nothing End Sub
Control | Caption | Name | |
Label | Fun Department Store | ||
Line | |||
Label | New Employee | ||
Text Box | Employee #: | txtEmployeeNumber | |
Text Box | First Name: | txtFirstName | |
Text Box | Last Name: | txtLastName | |
Text Box | Address: | txtAddress | |
Text Box | City: | txtCity | |
Text Box | County: | txtCounty | |
Text Box | State: | txtState | |
Text Box | ZIP Code: | txtZIPCode | |
Option Group | Marital Status | fraMaritalsStatus | |
Text Box | Exemptions: | txtExemptions | |
Text Box | Hourly Salary: | txtHourlySalary | |
Option Group | Filing Status | fraFilingsStatus | |
Button | Submit | cmdSubmit | |
Button | Close | cmdClose |
The Characteristics of a Record Set
The Source
To work on a record set, you must communicate to the database engine what rules your set will follow. Once the table has been created, it is considered a record set. You can use it as the contents of a record set.
The Number of Records of a Record Set
After creating a record set, you may want to know the actual number of records it contains. This information is stored in a property named RecordCount. On a form, to get the number of records it contains, you can access the RecordCount property of its RecordsetClone object. This can be done as follows:
RecordsetClone.RecordCount
Record Navigation in a Record Set
Introduction
Navigating through a record set consists of visiting its records. This is similar to using the navigation buttons at the bottom of a table, a query, a form, or a report. We know how to programmatically do this using the DoCmd object. The record set also supports record navigation through various methods.
Moving to the First Record
When performing an operation on a record, you should know your position in the set. Whenever in doubt, you can reset your position by moving to the first record. To support this, the record set is equipped with a method named MoveFirst. This method takes no argument. Here is an example of calling it:
Private Sub cmdVideoAnalyze_Click()
Dim fldEach As Object
Dim rstTimeSheet As Object
REM Blah Blah Blah
rstTimeSheet.MoveFirst
. . .
rstTimeSheet.Close
Set rstTimeSheet = Nothing
End Sub
Moving to the Previous Record
To move to the previous record in the set, call the MovePrevious() method of the record set.
Moving to the Next Record
To move from one record to the next, you can call the MoveNext() method of the record set.
Moving to the Last Record
Besides the first record, another extreme position you can move to is the last record. To do this, you can call the MoveLast() method of the record set.
Moving to a Specific Record
The MoveFirst() and MoveLast() methods allow you to navigate one record at a time until you get to a certain record. If you are positioned at a certain record and you want to jump a certain number of records ahead or you want to move back by a certain number of records, you can call the Move() method. Its first argument specifies the number of records by which to jump. Here is an example:
Private Sub cmdEditRecord_Click() Dim dbCustomers As Object Dim rstCustomers As Object Set dbCustomers = CurrentDb Set rstCustomers = dbCustomers.OpenRecordset("Customers") rstCustomers.Move 4 End Sub
When this code executes, it would jump 4 records ahead of the current record. You can also pass a negative value to move behind the current record. If the record set doesn't contain any record when you call the Move() method, you would get a 3021 error:
Don't Move Beyond the Extremes
Some, if not most, operations require that you remain within the range of values of the record set. If you move below the first record, you (actually the user) may receive an error. In the same way, if you move beyond the last record, you would receive an error. To assist you with checking whether you are in the first record, the record set uses the BOF() method. This method returns a Boolean value as follows:
On the other hand, if you want to check whether you are at the highest position of the records, you can call the EOF() method of the Recordset object. It also returns a Boolean value as follows:
Record Location
Editing a record consists of changing the value of one or more columns. Editing a record is done in various steps. First, you must locate the record.
If you know exactly the index of the record that contains the value you want to edit, you can call the Move() method to jump to it. Here is an example:
Private Sub cmdMovePosition_Click()
Dim dbKoloBank As Object
Dim rstTimeSheet As Object
Set dbKoloBank = CurrentDb
Set rstTimeSheet = dbKoloBank.OpenRecordset("Videos")
rstTimeSheet.Move 6
End Sub
We also saw that you could call one of the other Move-related methods (MoveFirst(), MovePrevious(), MoveNext(), or MoveLast()). Once you get to a record, you can then perform the necessary operation(s). For example, you can retrieve the values held by that record.
Record Maintenance
Locating a Value in the Microsoft Access Libraries
Before editing a record, you must locate it to indicate to the record set what record is involved. Here is an example of locating a record:
Private Sub cmdUpdate_Click() Dim curDatabase As Object Dim rstEmployees As Object Dim fldEmployee As Object Set curDatabase = CurrentDb Set rstEmployees = curDatabase.OpenRecordset("Employees") With rstEmployees Do Until .EOF For Each fldEmployee In .Fields If fldEmployee.Name = "EmployeeID" Then If fldEmployee.Value = CInt(txtEmployeeID) Then ' The record to be edited has been located Exit For End If End If Next .MoveNext Loop End With End Sub
Editing a Value in a Recordset
To support the ability to update a record, the record set uses a method named Edit. After calling this method, access the field or each field that needs to be edited and assign the desired value to it (or them). After calling the Edit() method and assigning the value(s) to the appropriate field(s), you must call the Update method of the record set. This can be done as follows:
Private Sub cmdUpdate_Click() Dim curDatabase As Object Dim fldEmployee As Object Dim rstEmployees As Object Set curDatabase = CurrentDb Set rstEmployees = curDatabase.OpenRecordset("Employees") With rstEmployees Do Until .EOF For Each fldEmployee In .Fields If fldEmployee.Name = "EmployeeID" Then If fldEmployee.Value = CInt(txtEmployeeID) Then ' The record to be edited has been located .Edit .Fields("DateHired").Value = txtDateHired .Fields("FirstName").Value = txtFirstName .Fields("LastName").Value = txtLastName .Fields("HourlySalary").Value = txtHourlySalary .Update Exit For End If End If Next .MoveNext Loop End With End Sub
Deleting a Record in the Microsoft Access Libraries
To give you the ability to remove a record, the record set uses a method named Delete. Of course, before performing this operation, first locate the record you want to delete. Once you have found the record, call the Delete() method. Here is an example:
Private Sub cmdDeleteRecord_Click()
Dim curDatabase As Object
Dim rstEmployees As Object
Dim fldEmployee As Object
Set curDatabase = CurrentDb
Set rstEmployees = curDatabase.OpenRecordset("Employees")
With rstEmployees
Do Until .EOF
For Each fldEmployee In .Fields
If fldEmployee.Name = "EmployeeID" Then
If fldEmployee.Value = CInt(txtEmployeeID) Then
' The record to be deleted has been found
.Delete
Exit For
End If
End If
Next
.MoveNext
Loop
End With
End Sub
Practical Learning: Ending the Lesson
|
||
Previous | Copyright © 2005-2022, FunctionX, Inc. | Next |
|