what are some differences between class modules and regular modules?
Printable View
what are some differences between class modules and regular modules?
A Module is used as a place you can wright your public Functions or Sub - Routines so that you can access them form somewhere else. The advantage of a Stadard Module is that you get to keep all the common, public Functions and Sub routines at 1 place.
A Class Module is related to Object Oriented Programming (OOP). In this module you can create an Object which has properties, methods and Events. (Note: This is only a template, the actual working only happens when the object is created. You can't call a function or sub routine like you do in a Standard Module). Once you create the object in your code then you can use it's properties, events and method. Here's an Example on how you can call a method in a class (assuming you already have created a Class name "Class1" and also having a subroutine "ADD".
Option Explicit
Dim cls As Class1
Private Sub Form_Load()
Set cls = New Class1 'The class is created here
cls.Add 10, 20 'now you can call a method
End Sub
To add:
A class module is a type of Visual Basic code module. A class module (.cls file) is similar to a standard code module (.bas file) in that it contains functionality that can be used by other modules within the application. The difference is that a class module provides functionality in the form of an object. Each class module defines one type of object. You may have several class modules in an application.
so the main different is that you cant have pubic functions and subs in your class module like you can in a regular module? i also noticed you cant define public constants in a class module. thanks for the info guys.
Yes, you can use public functions in a class module, this is the basis for the objects methods. You can also use public variables, however, this method is frowned upon by many. You would use property let/get/set procedures to access variables. By using this method, you are able to encapsulate the data of the object, which can only be accessed through these properties, unlike public varialbes. When using class modules, before you can have access to their methods, events, and properties, you have to first create an instance of the class:
It is more efficient to use the Dim and Set statements separately to clearly show where the instance of the class is instantiated. With the Dim As New statement, the object is created the first time the object variable is used, but with each subsequent use Visual Basic has to first determine if the object has already been instantiated.Code:Dim x as Class1
Set x = new Class 1
'or
dim x as new class1