VBA Objects, Methods, Properties, and Conditionals

  • Objects, Methods, and Properties

    Objects

    Everything in VBA programming is an object. The workbook is an object. The worksheet is a "child" object (i.e. sub-component) of the workbook. A cell, or range of cells, is a child object of the worksheet. Objects have methods (i.e. things the object can do) and properties (i.e. facts about the object). Conceptually, think of an object as a noun: a person, place, or thing. A dog would be an object. Dogs have methods (e.g. bark, run, poop) and properties (e.g. weight, color, breed). Programming objects are similar. A cell object has methods that can be performed and properties about the cell.

    Methods

    Methods are a set of predefined actions that can be performed on the data contained in the object. Methods are tied directly to an object. They occur when an action takes place upon that object. They do not exist independent of that object. Methods can be "executed" by "calling" them in VBA code. For example, to clear the contents of a cell, you would write:

    Range("A1").Clear

    The "." indicates that the "Clear" command which comes after the "." is a method of the Range("A1") object. Different types of objects have different methods available to them.

    Properties

    Properties are characteristics of an object. In other words, a property is a piece of information that describes some aspect of an object (e.g. the value of a cell, the number of columns in a Range, the width of a column, etc.). Unlike methods that are "called" with a simple line of code, properties are either "get" or "set," "read" or "written." In other words, when writing VBA code and referring to an object's properties, we are always either trying to find out what the property is ("get" or "read" the Range("A1").Font.Bold property to find out if the cell is bold) or we are trying to set the property to some new value ("set" or "write" the Range("A1").Font.Bold property to True). As a result of this, we always refer to object properties in VBA code with an "equals" ( = ) sign on one side or the other. For example:

    Range("A1").Font.Bold = True

    The following code gets, or reads, the Bold property of cell A1 and stores it in the declared boolean variable "bold":

    Dim bold as Boolean
    
    bold = Range("A1").Font.Bold

    You can view an object's methods and properties by opening the Visual Basic editor. Type the object's name followed by a period. A dropdown list appears that contains the methods and properties available for the object. Methods are designated by a green box icon. Properties are designated by a finger icon. The figure below shows this for the Range object.

  • Conditionals