O'Reilly logo

Excel Scientific and Engineering Cookbook by David M Bourg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

2.14. Creating Your Own Objects in VBA

Problem

You know VBA is an object-oriented language and you'd like to create your own objects for use in other subroutines and functions.

Solution

Create a new Class Module in VBA and add your object properties and methods.

Discussion

Let me show you how to do this by way of example. First, for those of you not familiar with object-oriented lingo, an object is a code construct comprised of properties and methods. Properties are variables that describe the object in some way; they store attributes of the object. Methods are functions or subroutines that actually do something. They can manipulate properties, perform some action on given parameters, or do whatever other programming task you can devise. Objects provide a convenient way of packaging code that allows easy reuse.

In Recipe 7.11, I show you how you might add support for manipulating vectors using VBA. You might also approach the same problem by writing a vector object to encapsulate all the properties and functionality of a vector. This way you can define vector type variables and perform computations with these variables. I'll show you step by step how to get started.

Open Excel and the VBA editor. In the VBA editor, select Insert → Class Module from the main menu bar. In VBA (as in some other languages) an object is called a class. Under the VBA project browser panel, you should see a folder called Class Modules and under that a new module called something like class1. Now press F4 (or ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required