Good Coding Practices

An important part of writing quality code is using good formatting. Good formatting helps prevent errors, organizes the code, and makes it easier to understand. In this class you will be required to use the following good coding practices. Not using these good coding practices will reduce your homework scores.

Naming Controls

Naming your controls helps you keep track of which control does what. This becomes important if you have multiples of the same control, such as 4 command buttons or 6 option buttons.

Controls are made using the insert tool under the developer tab. For this class you should only use ActiveX Controls.

Whenever you create a control it is given a default name. To view the name turn on design mode, open the properties tab, and select the control.

To update a control’s name edit the “(name)” field. Note, a controls caption is not the same as its name. In this class each controll has a naming convention. Make sure that if you change the name of a control in the properties tab that you update the name of the control in your code.


Indenting your code helps you visual organize it. This makes the code easier to understand, especially when there are nested loops or IF statements.

To indent your code press the tab key on a line of code that is a sub-process of a preceding line of code.


Leaving comments in your code makes your code easier to understand. This is especially important for someone else to understand your code or for you to understand your own code after an extended period of time.

To insert a comment put an apostrophe in front of the line of code you want to be a comment. The code will become green once the computer recognizes that it’s a comment.

Declaring Variables and Option Explicit

Variables should be declared before they are used. This helps you make less mistakes.

To declare a variable type “Dim ”, the name of your variable, “As ”, and what type of variable it is. For example, “Dim Color As String”.

The most commonly used types of variables in VBA are: Boolean, currency, date, single, double, integer, long, and string.

Sometimes it is unclear what a variable should be declared as. If this is a case, you can simply declare a variable as “Variant” and the code will guess the type of variable for you.

Option Explicit is a VBA Function that prevents you from using a variable without declaring it beforehand. This helps you keep track of your variables. To use Option Explicit type “Option Explicit” at the very top of your code and press enter.