This VBA Productivity Tip introduces a very simple feature that can be used to organize modules in complex projects — naming individual modules. By providing modules with specific and informative names, developers can easily group and compartmentalize VBA subroutines.
Naming a module is one of the easiest things to do in the VBA editor. The first step is to open the module Properties window. This can be done in one of two ways.
- Simply press the F4 key on your keyboard while the VBA editor is the active window.
- Or, from the windows toolbar, select View > Properties.
The Properties window will appear in the lower left-hand corner of the VBA editor, below the Project window.
Next, select a module in the Project window. Within the Properties window, the “(Name)” field can be modified to change the name from Module1, Module2, etc. Type the new name, then press Enter on the keyboard. The new name will replace the default name in the Project window.
- Names can only contain alpha-characters, numbers, and the underscore symbol. No other symbols are permitted.
- Names cannot begin with numbers. Numbers can be places anywhere but the beginning for a module name.
Renaming Microsoft Excel Objects
When clicking on a Worksheet within a Project window, a number of other fields appear in the properties window (other fields will be discussed a future post). The first item in the display will be the “(Name)” field, which is similar to the corresponding field for modules. This is what is known as the CodeName property for spreadsheets. The CodeName is the object identifier VBA uses to call the Worksheet object. For example, if you previously used Sheet1 to call the Range property, you will now use Your_Custom_Name.
The “(Name)” field is also available in the ThisWorkbook object. Changing this will rename the identifier used access the workbook hosting the code. This is generally unnecessary unless your project works with multiple workbooks.
- The “(Name)” property within modules is also an object identifier, but is seldom used as an object. The only instance where a module name would be required is when two identically named public subroutines exist in two different modules. In this situation, a call is required for both to the module and subroutine, separated with the dot operator (see below). Likewise, this can be used with any public subroutine–regardless of name uniqueness–to help trace calls in complex projects. This can help you easily trance the called subroutine back to its host module.
- Class Modules also have a special use for the “(Name)” field. This is discussed more in part 1 of our VBA classes tutorial.
Relevant Tutorials and Exercises
The following are some relevant tutorials and posts associated with this productivity tip.