Home

Introduction to Classes and Objects

Classes Fundamentals

Introduction

A class is a technique of using one variable or a group of variables in one unit to describe an object.

Practical LearningPractical Learning: Introducing Classes

  1. Start Microsoft Access
  2. From the resources that accompany these lessons, open the Business Starter database

Creating a Class

To help you create a class, Microsoft Visual Basic provides a special version of a module named a class module. To create a class:

As mentioned for the regular module, Microsoft Visual Basic would give a default name to the module. Normally, you should name the module based on the name you want for your class. To name or re-name a class module, click its name in the Project window. In the Properties window, click (Name) or its text box. Type the desired name and press Enter. After creating and naming the module, it becomes a class.

Practical Learning: Creating a Class in Microsoft Access

  1. On the Ribbon, click Create
  2. In the Macros & Code section, click the Class module button
  3. In the Properties window, click (Name) and type Payroll
  4. To start another class, on the main menu, click Insert and click Class module
  5. In the Properties window, click (Name) and type Employee

    The Properties Window

The Contents, Body, and Members of a Class

The whole area of a class module, that is, the whole content of the file is referred to as the body of the class. All things in the module, that is, all the object inside the document are (considered as) the members of the class.

The Member Variables of a Class

A class is a combination of values or variables. To create those values or variables, declare each variable in the module.

Practical Learning: Adding Members to a Class

  1. Click the first blank line and type the following lines of code:
    Dim EmployeeeNumber As Long
    Dim FirstName As String
    Dim LastName As String
    Dim HourlySalary As Double

    The Member Variables of a Class

  2. In the Project window, under Class Modules, double-click Payroll and complete the class with the following values:
    Public PayrollID As Long
    Public EmployeeeNumber As Long
    Public Monday As Double
    Public Tuesday As Double
    Public Wednesday As Double
    Public Thursday As Double
    Public Friday As Double
    Public Saturday As Double
    Public Sunday As Double
  3. Return to Microsoft Access
  4. In the Navigation Pane, right-click Employment Application1 and click Design View
  5. On the form, right-click the Create button and click Build Event...
  6. In the Choose Builder dialog box, double-click Code Builder

Creating an Object

Introduction

After creating a class, to use it in your project, you must declare a variable for it. This is also referred to as creating an object or creating an instance of the class. To create an object, use the Dim keyword followed by a name for the object, the As keyword, and the name of the class. Here is an example:

Private Sub cmdSubmit_Click()
    Dim staff As Employee
End Sub

Allocating Computer Memory for an Object

To let the computer hold the values of an object, you must allocate some computer memory for it. To assist you with this, the Visual Basic language provides an operator named New. To use it, assign it to the variable and follow it with the name of the class. Here is an example:

Private Sub cmdSubmit_Click()
    Dim staff As Employee

    staff = New Employee
End Sub

Instead of first declaring the variable before allocating memory for it, you can take care of this directly when declaring the variable by inserting the New operator between the As keyword and the name of the class.

Practical Learning: Creating an Object

Accessing a Member of a Class

The Public Members of a Class

If you use the Dim keyword to declare a variable in the body (as a member) of a class, the member is said to be hidden. Such a member cannot be accessed outside the class but it can be accessed by the other members of the class, only in the module. For a member to be accessible outside the class, the member must be made public. To make this happen, use the Public keyword in place of Dim to create the member. This is not a requirement. You will (know to) decide when a member must be public and when not.

Practical Learning: Making Members Accessible

  1. In the Project window, under Class Modules, double-click Employee
  2. In the body of the class, replace the Dim keywords with Public:
    Public EmployeeNumber As Long
    Public FirstName As String
    Public LastName As String
    Public HourlySalary As Double
  3. In the Project window, under Microsoft Access Class Objects, double-click Form_Employment Application1

The Period Operator: .

To access a member of a class outside the class, type the name of the variable, followed by a period, followed by the name of the member you want to access. Once you have accessed a member, you can use it. For example, you can assign a value to it.

Remember that, to create more than one statement on the same line, you can use the colon operator. Here is an example:

Private Sub cmdCreate_Click()
    Dim staff As New Employee

    staff.EmployeeNumber = 29739: staff.HourlySalary = 18.85
    staff.FirstName = "Gregory": staff.LastName = "Plane"
    

    txtEmployeeNumber = staff.EmployeeNumber: txtFirstName = staff.FirstName
    txtLastName = staff.LastName: txtHourlySalary = staff.HourlySalary
End Sub

The Members of an Object in the Code Editor: Using the IntelliSence

When writing code, the Code Editor is equipped to assist you with the names of the members of a class. When you type the name of an object followed by the period operator, the available members would appear in a list. Here is an example:

Accessing the Members of an Object in the Code Editor: Using the IntelliSence

This feature is called IntelliSense. It works on most or all objects. If the list is long, you can start typing the lettters until the desired option appears. When using the IntelliSence, if you see the member you want:

Practical Learning: Accessing the Members of an Object

  1. Change the code as follows:
    Private Sub cmdCreate_Click()
        Dim staff As New Employee
    
        staff.EmployeeNumber = 29739
        staff.FirstName = "Gregory"
        staff.LastName = "Plane"
        staff.HourlySalary = 18.85
    
        txtEmployeeNumber = staff.EmployeeNumber
        txtFirstName = staff.FirstName
        txtLastName = staff.LastName
        txtHourlySalary = staff.HourlySalary
    End Sub
  2. Return to Microsoft Access and switch the form to Form View
  3. Click the Create button

    The Period Operator

  4. Save and close the form
  5. In the Navigation Pane, right-cllick Payroll Preparation1 and click Design View
  6. Right-click the button and click Build Event
  7. In the Choose Builder dialog box, click Code Builder, and click OK
  8. You can also involve an accessed member in an expression. For an example, implement the event as follows:
    Private Sub cmdCalculateTimeWorked_Click()
        Dim pay As New Payroll
        Dim timeWorked As Double
    
        pay.PayrollID = 100001
        pay.EmployeeeNumber = 29739
        pay.Monday = 8#
        pay.Tuesday = 9.5
        pay.Wednesday = 8.5
        pay.Thursday = 8#
        pay.Friday = 10#
        pay.Saturday = 0#
        pay.Sunday = 0#
    
        timeWorked = pay.Monday + pay.Tuesday + pay.Wednesday + _
                     pay.Thursday + pay.Friday + pay.Saturday + pay.Sunday
    
        txtPayrollID = pay.PayrollID
        txtEmployeeNumber = pay.EmployeeeNumber
        txtTimeWorked = timeWorked
    End Sub
  9. Return to Microsoft Access and switch the form to Form View
  10. Click the button on the form

    Using a Class

  11. Save and close the form
  12. Return to Microsoft Visual Basic

Static Classes and Static Objects

A class is referred to as static if there is no need to declare a variable in order to access the members of that class. This means that you must use the class directly in your code and access its members using the period operator.

Allocating and De-Allocating Memory for an Object

Creating a Reference to an Object

We saw that, when creating an object, that is, when declaring a variable for it, you can use the New operator to ask the compiler to allocate memory for it. This is done if you want to immediately use the object. Sometimes you can declare a variable but are not ready to use the object. In that case, you don't have to allocate memory for it. You can declare the variable without using the New operator. Here is an example:

Private Sub cmdVariable_Click()

    Dim pay As Payroll

End Sub

In this case, when you are ready to use the object, you must allocate memory for it. This time, you must use another operator named Set but precede the name of the class with New. Here is an example:

Private Sub cmdVariable_Click()
    Dim pay As Payroll

    Set pay = New Payroll

End Sub

From there, you can use the object normally.

De-Allocating Memory Object

Some objects don't use much computer resources. Others do, such as those that use and manipulate many files. Therefore, it is recommended that, after using an object in a procedure, you should ask the compiler to remove the object from memory so that other objects can use the resources your object was using. To assist you with this, the Visual Basic language provides an object named Nothing. To use, assign it to the object using the Set operator.

You can also de-allocate memory even you didn't use the Set operator to initialize the object.

Practical Learning: Allocating and De-Allocating Memory for an Object

  1. To allocate and de-allocate memory, add the following last line to the code:
    Private Sub cmdCalculateTimeWorked_Click()
        Dim pay As New Payroll
        Dim timeWorked As Double
    
        pay.PayrollID = 100001
        pay.EmployeeeNumber = 29739
        pay.Monday = 8#
        pay.Tuesday = 9.5
        pay.Wednesday = 8.5
        pay.Thursday = 8#
        pay.Friday = 10#
        pay.Saturday = 0#
        pay.Sunday = 0#
    
        timeWorked = pay.Monday + pay.Tuesday + pay.Wednesday + _
                     pay.Thursday pay.Friday + pay.Saturday + pay.Sunday
    
        txtPayrollID = pay.PayrollID
        txtEmployeeNumber = pay.EmployeeeNumber
        txtTimeWorked = timeWorked
        
        Set pay = Nothing
    End Sub
  2. In the Project window, double-click Form_Employment Application1 and change the code as follows:
    Private Sub cmdCreate_Click()
        Dim staff As Employee
    
        Set staff = New Employee
        
        staff.EmployeeNumber = 29739
        staff.FirstName = "Gregory"
        staff.LastName = "Plane"
        staff.HourlySalary = 18.85
    
        txtEmployeeNumber = staff.EmployeeNumber
        txtFirstName = staff.FirstName
        txtLastName = staff.LastName
        txtHourlySalary = staff.HourlySalary
        
        Set staff = Nothing
    End Sub

Classes and Procedures

A Function that Returns an Object

A function can be made to return an object. When creating such a function, after its parentheses, type the As keyword followed by a space and the name of the class. Here is an example:

Private Function CreateEmployee() As Employee

End Function

Passing an Object to a Procedure

A class can be passed to a procedure as parameter. In this case, provide the name of the class for the parameter in the parentheses of the procedure. You don't have to use the parameter in the body of the function. Otherwise, you can use the parameter in the body of the procedure. To access a member of the class, type the name of the parameter followed by a period and the name of the member.

Practical Learning: Passing an Object to a Procedure

  1. In the Form_Employment Application1 module, create a procedure as follows:
    Private Sub ShowEmployee(staff As Employee)
        txtEmployeeNumber = staff.EmployeeNumber
        txtFirstName = staff.FirstName
        txtLastName = staff.LastName
        txtHourlySalary = staff.HourlySalary
    End Sub
  2. When calling the procedure, you must pass a valid object. To see an example, change the Click event of the Create button as follows:
    Private Sub ShowEmployee(staff As Employee)
        txtEmployeeNumber = staff.EmployeeNumber
        txtFirstName = staff.FirstName
        txtLastName = staff.LastName
        txtHourlySalary = staff.HourlySalary
    End Sub
    
    Private Sub cmdCreate_Click()
        Dim staff As Employee
    
        Set staff = New Employee
        
        staff.EmployeeNumber = 38405
        staff.FirstName = "Jeannette"
        staff.LastName = "Gibson"
        staff.HourlySalary = 24.27
        
        ShowEmployee staff
        
        Set staff = Nothing
    End Sub
  3. Return to Microsoft Access and switch the form to Form View
  4. Click the button on the form

    Passing an Object to a Procedure

  5. Save and close the form

Passing Many Objects to a Procedure

As mentioned for regular types, a procedure can take more than one parameter. One of the parameters can be a class type while the other(s) is(are) (a) regular type(s). In the body of the procedure, you don't have to use any of the parameters, or you can use one of them or all of them.

You can create a procedure that takes more than one parameter where all parameters are class types. Once again, in the body of the procedure, you can ignore one of the parameters.

Practical Learning: Passing Many Objects to a Procedure

  1. From the resources that accompany these lessons, open the Depreciations database
  2. On the Ribbon, click Create and click Class Module
  3. Type:
    Public SerialNumber As String
    Public Make As String
    Public Model As String
    Public Price As String
  4. In the Project window, click (Name) and type Machine
  5. On the Standard toolbar, click the arrow of the Insert button and click Class Module
  6. Type:
    Public Cost As Double
    Public SalvageValue As Double
    Public EstimatedLife As Integer
  7. In the Project window, click (Name) and type Depreciation
  8. In the Project window, if necessary, expand Microsoft Access Class Objects and double-click Form_Straight-Line Method
  9. Create a function as follows:
    Function Calculate(ByVal item As Machine, ByVal estimate As Depreciation) As Double
        Dim value As Double
        
        value = (estimate.Cost - estimate.SalvageValue) / estimate.EstimatedLife
    
        Calculate = value
    End Function
  10. In the Object combo box, select cmdCalculateDepreciation
  11. When calling a procedure that has a class-based parameter, if you don't need to pass an argument for that parameter, pass the argument as Nothing. To see an example, implement the event as follows:
    Function Calculate(ByVal item As Machine, ByVal estimate As Depreciation) As Double
        Dim value As Double
        
        value = (estimate.Cost - estimate.SalvageValue) / estimate.EstimatedLife
    
        Calculate = value
    End Function
    
    Private Sub cmdCalculateDepreciation_Click()
        Dim value As Double
        Dim dep As New Depreciation
    
        dep.Cost = 5000
        dep.SalvageValue = 500
        dep.EstimatedLife = 5
    
        value = Calculate(Nothing, dep)
        
        txtMachineCost = dep.Cost
        txtSalvageValue = dep.SalvageValue
        txtEstimatedLife = dep.EstimatedLife
        txtDepreciation = value
    End Sub
  12. Return to Microsoft Access
  13. In the Navigation Pane, double-click Straight-Line Method
  14. Click the button

    Passing Many Parameters to a Function

  15. Return to Microsoft Visual Basic

Introduction to the Methods of a Class

Overview

A procedure or a function can be created in the body, as a member, of a class module to perform actions for, or on behalf of, the class. Such a procedure or member function is called a method.

To create a method, in the body of a class, use the same formulas as for procedures and functions. Here is an example of a function method:

Public Cost As Double
Public SalvageValue As Double
Public EstimatedLife As Integer

Function Calculate() As Double

End Function

When you have created a member variable in a class module, it is available to all methods of the same class. This means that, to use it from a method of the same class, you don't have to declare a variable for the class.

Practical Learning: Introducing the Methods of a Class

  1. In the Project window, double-click Depreciation
  2. Create a method as follows:
    Public Cost As Double
    Public SalvageValue As Double
    Public EstimatedLife As Integer
    
    Function Calculate() As Double
        Calculate  = (Cost - SalvageValue) / EstimatedLife
    End Function

A Public Method

A method is said to be hidden if it cannot be accessed outside the class but can be accessed only by other members of the same class, in the body of the class. A method is referred to as public if it can be accessed by objects outside the class. To specify that a method is public, precede it with the Public keyword.

Practical Learning: Making a Member Accessible Outside the Class

Accessing a Method Outside the Class

To access a method outside of its class, use the same period operator used for member variables.

Practical Learning: Accessing a Method Outside the Class

  1. In the Project window, double-click Form_Straight-Line Depreciation
  2. Change the Click event of the button as follows:
    Private Sub cmdCalculateDepreciation_Click()
        Dim d As Double
        Dim vehicle As New Depreciation
    
        vehicle.Cost = 45800
        vehicle.SalvageValue = 6000
        vehicle.EstimatedLife = 6
    
        d = vehicle.Calculate()
    
        txtMachineCost = vehicle.Cost
        txtSalvageValue = vehicle.SalvageValue
        txtEstimatedLife = vehicle.EstimatedLife
        txtDepreciation = d
    
        Set vehicle = Nothing
    End Sub
  3. Return to Microsoft Access and click the button

    Accessing a Method Outside the Class

  4. Return to Microsoft Visual Basic
  5. In the Project window, below Class Modules double-click Depreciation

Class Construction and Termination

Object Initialization

When you declare a variable of a class, a special method must be called to initialize the members of that class. In most computer languages, this method is called a constructor. To let you create a special method that can be used to initialize the members of a class, open the class method in Microsoft Visual Basic. In the Object combo box, select Class. In the Procedure combo box, select Initialize. The skeleton code of a private procedure named Class_Initialize would be generated. In the body of that method, you can access the desired member variable and initialize it any way you want.

The Class_Initialize() method is automatically used and called behind the scenes when you create an object. As a result, you should never call that method.

Practical Learning: Initialyzing a Class

  1. In the Object combo box, select Class
    Private Sub Class_Initialize()
    
    End Sub
  2. Implement the method as follows:
    Public Cost As Double
    Public SalvageValue As Double
    Public EstimatedLife As Integer
    
    Function Calculate() As Double
        Calculate = (Cost - SalvageValue) / EstimatedLife
    End Function
    
    Private Sub Class_Initialize()
        Cost = 0#
        SalvageValue = 0#
        EstimatedLife = 0
    End Sub

Object Termination

When an object has been used and is not needed anymore, it must be removed from the computer memory. To assist you with this, the VBA provides a special method for every class and it its named Class_Terminate. To let you create this special method, open the class method in Microsoft Visual Basic. In the Object combo box, select Class. In the Procedure combo box, select Terminate. The skeleton code would be generated for you.

Practical Learning: Terminating a Class

  1. In the Procedure combo box, select Terminate
    Private Sub Class_Terminate()
    
    End Sub
  2. Return to Microsoft Access
  3. Save and close the form

Using an Object With Me

With a Class Instance

To access the members of a class using an object, you can use the With keyword. Type it followed by the name of the variable. Create a new line and type End With. The section between the With variable-name line and the End With line is the body of the With statement. In that body, to access a member of the class, type the period operator followed by the desired member.

Practical Learning: Accessing the Members With an Object

  1. On the Ribbon, click File and click Open
  2. In the list of files, click Business Starter used earlier
  3. On the Ribbon, click Create and click Visual Basic
  4. If the Form_Employment Application1 module is not displaying, in the Project window, double-click Form_Employment Application1.
    Change the Click event as follows:
    Private Sub ShowEmployee(staff As Employee)
        txtEmployeeNumber = staff.EmployeeNumber
        txtFirstName = staff.FirstName
        txtLastName = staff.LastName
        txtHourlySalary = staff.HourlySalary
    End Sub
    
    Private Sub cmdCreate_Click()
        Dim staff As Employee
    
        Set staff = New Employee
        
        With staff
            .EmployeeNumber = 20864
            .FirstName = "Paula"
            .LastName = "Henley"
            .HourlySalary = 14.88
        End With
        
        ShowEmployee staff
        
        Set staff = Nothing
    End Sub
  5. Return to Microsoft Access
  6. In the Navigation Pane, double-click Employment Application1 and click the Create button

    Accessing the Members With an Object

  7. Save and close the form
  8. On the Ribbon, click File and click Open
  9. In the list of files, click Depreciations used earlier
  10. On the Ribbon, click Create and click Visual Basic
  11. If the Form_Straight-Line Method module is not displaying, in the Project window, double-click Form_Straight-Line Method
  12. You can use a With statement to access a method of a class.
    For an example, change the Click event as follows::
    Private Sub cmdCalculateDepreciation_Click()
        Dim d As Double
        Dim vehicle As New Depreciation
    
        With vehicle
    	.Cost = 128500
        	.SalvageValue = 30000
        	.EstimatedLife = 10
    
    	d = .Calculate()
    
            txtMachineCost = .Cost
            txtSalvageValue = .SalvageValue
            txtEstimatedLife = .EstimatedLife
            txtDepreciation = d
        End With
    
        Set vehicle = Nothing
    End Sub
  13. Return to Microsoft Access and, in the Navigation Pane, double-click Straight-Line Method
  14. Click the button on the form:

    Accessing the Members With an Object

  15. Return to Microsoft Visual Basic
  16. In the Project window, expand Class Modules and double-click Depreciation

Me

To let you access the member(s) of a class module while inside the module, the Visual Basic language provides a special object named Me. When using Me, you can access any member of a class within any method of the same module.

Because Me is an object, you can assign it to a variable that refers to an object of the same class. Here is an example:

Option Compare Database
Option Explicit

Public ItemNumber As Long
Public ItemName As String
Public Size As String
Public UnitPrice As Double
    
Public Function CalculateDiscountAmount(Optional ByVal DiscountRate As Double = 20#) As Double
    CalculateDiscountAmount = UnitPrice * DiscountRate / 100#
End Function

Public Sub Examine()
    Dim inside
    
    Dim inside = Me
End Sub

You can also compare an object to Me to find out what that object represents.

There are rules you must follow when using Me:

Practical Learning: Using Me

  1. Change the contents of the class module as follows:
    Public Cost As Double
    Public SalvageValue As Double
    Public EstimatedLife As Integer
    
    Function Calculate() As Double
        Calculate = (Me.Cost - Me.SalvageValue) / Me.EstimatedLife
    End Function
    
    Private Sub Class_Initialize()
        Me.Cost = 0#
        Me.SalvageValue = 0#
        Me.EstimatedLife = 0
    End Sub
    
    Private Sub Class_Terminate()
    
    End Sub
  2. In the Project window, double-click Form_Straight-Line Application
  3. Remember that when you write code for a control, such as a button, positioned on a form or a report, you are in fact writing your code in the class module of the form or report. Therefore, you can access any of those controls using Me. To apply this, change the code of the event as follows:
    Private Sub cmdCalculateDepreciation_Click()
        Dim d As Double
        Dim vehicle As New Depreciation
    
        With vehicle
    	.Cost = 4500
        	.SalvageValue = 500
        	.EstimatedLife = 3
    
    	d = .Calculate()
    
            Me.txtMachineCost = .Cost
            Me.txtSalvageValue = .SalvageValue
            Me.txtEstimatedLife = .EstimatedLife
            Me.txtDepreciation = d
        End With
    
        Set vehicle = Nothing
    End Sub
  4. Return to Microsoft Access and click the button on the form:

    Using Me

  5. Save and close the form

Methods and Arguments

Introduction

Like regular procedures, a method can have one or more parameters. The rules are the same as those applied to regular procedures or functions. Because a method has direct access to all regular members of its class, you don't have to create a parameter for a member variable of the same class. You would need a parameter only if an external value would be passed to the method.

Practical Learning: Using Parameters in a Method

  1. On the Ribbon, click File and click Open
  2. In the list of files, click Business Starter used earlier
  3. On the Ribbon, click Create and click Visual Basic
  4. In the Project window, expand Class Modules and double-click Employee
  5. Change the contents of the class module as follows:
    Public EmployeeNumber As Long
    Public FirstName As String
    Public LastName As String
    Public HourlySalary As Double
    
    Public Function CalculateNetPay(ByVal time As Double) As Double
        CalculateNetPay = HourlySalary * time
    End Function
  6. In the Project window, double-click Form_Payroll Preparation2
  7. In the Object combo box, select cmdCalculatePayroll
  8. Implement the event as follows:
    Private Sub cmdCreate_Click()
        Dim hSalary As Double
        Dim timeWorked As Double
        Dim netPay As Double
        Dim staff As New Employee
    
        staff.EmployeeNumber = 630485
        staff.FirstName = "David"
        staff.LastName = "Salomons"
        staff.HourlySalary = 18.95
    
        timeWorked = 44.5
    
        netPay = staff.CalculateNetPay(timeWorked)
        
        txtEmployeeNumber = staff.EmployeeNumber
        txtFirstName = staff.FirstName
        txtLastName = staff.LastName
        txtHourlySalary = staff.HourlySalary
        txtTimeWorked = timeWorked
        txtNetPay = netPay
        
        Set staff = Nothing
    End Sub
  9. Return to Microsoft Access
  10. In the Navigation Pane, double-click Payroll Preparation2
  11. Click the button on the form:

    Using Parameters in a Method

  12. Save and close the form
  13. On the Ribbon, click Create and click Class Module
  14. Type the following:
    Public ItemNumber As Long
    Public ItemName As String
    Public Size As String
    Public UnitPrice As Double
        
    Public Function CalculateDiscountAmount(ByVal DiscountRate As Double) As Double
        CalculateDiscountAmount = UnitPrice * DiscountRate / 100#
    End Function
  15. In the Properties window, click (Name) and type StoreItem

Optional Arguments

As seen for regular procedures, a method can use one or more parameters that are optional. To specify that an argument is optional, when creating the method, type the Optional keyword to the left of the parameter and assign a default value to it. When calling the method, you can pass or ignore the argument.

The rules of optional arguments in methods are the same rules reviewed for regular procedures.

Practical Learning: Using Optional Parameters in a Method

  1. To make the argument of the method optional, add the following words:
    Public ItemNumber As Long
    Public ItemName As String
    Public Size As String
    Public UnitPrice As Double
        
    Public Function CalculateDiscountAmount(Optional ByVal DiscountRate As Double = 20#) As Double
        CalculateDiscountAmount = UnitPrice * DiscountRate / 100#
    End Function
  2. Return to Microsoft Access
  3. In the Navigation Pane, right-click Inventory Preparation and click Design View
  4. On the form, right-click the Process Store Items button and click Build Event
  5. In the Choose Builder dialog box, click Code Builder, and click OK
  6. Implement the event as follows:
    Private Sub cmdProcessStoreItems_Click()
        Dim item As New StoreItem
        Dim discount As Double, markedPrice As Double
    
        item.ItemNumber = 927497
        item.ItemName = "Leaf Print Short Sleeve Shift Dress"
        item.Size = "Medium"
        item.UnitPrice = 59.5
    
        discount = item.CalculateDiscountAmount()
        markedPrice = item.UnitPrice - discount
    
        txtItemNumber1 = item.ItemNumber
        txtItemName1 = item.ItemName
        txtItemSize1 = item.Size
        txtUnitPrice1 = item.UnitPrice
        txtDiscountRate1 = "Default"
        txtDiscountAmount1 = discount
        txtMarkedPrice1 = markedPrice
    
        item.ItemNumber = 480795
        item.ItemName = "Small-Plaid Shirt"
        item.Size = "Large"
        item.UnitPrice = 34.95
    
        discount = item.CalculateDiscountAmount(35)
        markedPrice = item.UnitPrice - discount
    
        txtItemNumber2 = item.ItemNumber
        txtItemName2 = item.ItemName
        txtItemSize2 = item.Size
        txtUnitPrice2 = item.UnitPrice
        txtDiscountRate2 = "35%"
        txtDiscountAmount2 = discount
        txtMarkedPrice2 = markedPrice
    
        Set item = Nothing
    End Sub
  7. Return to Microsoft Access and switch the form to Form View
  8. Click the Process Store Items button

    Using Optional Parameters in a Method

  9. Save and close the form

A Class as a Member Variable

A member variable of a class can be of the type of another class. To create the member, you ou can use your own class. Here is an example:

Public PayrollID As Long
Public Staff As Employee
Public Monday As Double
Public Tuesday As Double
Public Wednesday As Double
Public Thursday As Double
Public Friday As Double
Public Saturday As Double
Public Sunday As Double

You can also use one of the classes already available. After a member variable has been created as a class type of another class, it can be used Normally. Because the member is a class, declared as a reference, to use it, you must follow the rules of using an object. Foer example, you must make sure you have allocated memory for it.

Returning an Object From a Method

As done for a value of a regular type, you can create a method that returns an object. To do this, declare the method and specify the class as the return type.

Passing an Object as Argument

A class can be used as a parameter to a procedure or to a method of another class. When a class is passed as argument:

Constant Member Variables

You can make a member variable of class to be constant. To do this, type the Const keyword on the left side of the name of the variable and initialize it. Here is an example:

Const PI = 3.14159265359

Public Radius As Double

Built-In Classes and Objects

Introduction

To assist you in creating databases abd their objects, Microsoft Access and Microsoft Visual Basic ship with various objects and classes.

The Object Class

The most fundamental class in the VBA language is called Object. As a result, every object you will use in your application is primarily of type Object. Normally, if you want to use that class, you will first need to declare a variable of that class. Here is an example:

Dim objVariable As Object

You can then initialize the variable based on the actual class you want to use. To initialize the variable, use the Set operator.

After declaring a variable using the Object, you can access the members of the class it represents. When you use the Object class, the IntelliSense will not display the members of the class. This means that you must know the members of the actual class you are trying to use.

In some cases, if you don't know or may not need to specify the particular type of the object you want to use, you can declare the variable of type Object. The class you are trying to use must be one of the existing VBA classes and not one of the primitive data types.

The Database Class

To support databases, Microsoft Access provides a class named Database. This class allows you to get a rereference to the database you are using. To use it, declare a variable of this class. Here is an example:

Dim curDatabase As Database

The Control Class

A Windows control, or a control, is an object positioned on a form or report. To programmatically support controls, the Visual Basic language provides a class named Control.

An Access Object

There are various types of objects you will use in your databases. Each object belongs to a particular collection. Still, to generally identify these various objects, each is identified as an AccessObject. This means that the AccessObject object is used to identify an object that belongs to a collection, whatever that object is and whatever its parent collection is.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2002-2022, FunctionX, Inc. Next