7 Steps To Creating Professional Quality Vba Macros
7 Steps To Creating Professional Quality Vba Macros
7 Steps To Creating Professional Quality Vba Macros
INTRODUCTION
This book contains the 7 steps for building Professional Quality VBA Applications. You can
use these step to build any type of VBA Application. From small and simple to large and
complex. These are the same steps I have used to build all the application in the Excel VBA
Handbook.
If you have any questions about the contents of the 7 steps or VBA in general then please
feel free to email me at Paul@ExcelMacroMastery.com or leave a comment on my blog at
Excel Macro Mastery.
More organised
Easier to change
Simple to navigate
In VBA the procedures (functions and subs) are stored in Modules. It is a good idea to group
similar procedures together in a single module.
For example, in a book shop you have different sections. There are fiction, romance, sports
and business sections. Treat your modules like these sections and your procedures like
books.
The following is a simple example
The Click_Events module hold the subs that run when a button is clicked.
The Team_Results module holds the main subs for this example project.
The Test_Print module holds subs that are useful in any application.
Click events are subs that run when a button is clicked. Having them all together in one
module and ending their name with “_Click” makes your life much easier.
It is clear from their name what they do. If you need to see how many button click subs you
have you can see at a glance when they are in one module. If you need to update or change
these subs then it is straight forward.
Imagine the opposite case where these subs are in random modules and do not have _Click
in their name. It would make it very tedious trying to locate them.
A second thing to keep in mind for using Click Event subs. Never put any code in them
except calls to other functions
1 Sub CreateReport_Click()
2 CreateReport
3 End Sub
4
5 Sub ClearData_Click()
6 ClearData
7 End Sub
Test_Print Module
The Test_Print module in the diagram above, holds common subs that are useful in many
applications. By having them in one module it is easy to add them to any VBA project.
1 Sub PrintExamples()
2
3 ' Print 15
4 Debug.Print 5 + 10
5
6 ' Print address of range
7 Debug.Print Sheet1.Range("A1:A12").Address
8
9 ' Print cell contents
10 Debug.Print Sheet1.Range("A1").Value
11
12 End Sub
The syntax checker ensures that your line of code has the correct syntax. However it can
only check the line you are currently on.
To check the project you can use Compile VBAProject from the Debug menu
Compile finds syntax errors as well. However it also finds errors where the syntax maybe
correct but the code doesn’t make sense.
If without End If
And so on
Using Compile is simple to use and runs very quickly. You can run after you add any small piece of
code or when you make a change to an existing application.
I have made selecting the correct worksheet as simple as possible. There are two type of
worksheets:
If your code is in the current workbook then use the code name of the workbook.
Take a look in the Project Explorer window. It is normally on the left hand side of the Visual Basic
editor. If it is not visible the select View->Project Explorer.
The code name is the name on the left. The worksheet name is the one on the right – in parenthesis.
When you create a new workbook they will both have the same name i.e. Sheet1.
You can change the code name in the Properties window. It is normally below the Project Explorer
window. If it is not visible select View->Properties Window.
You will often see code examples that use ThisWorkbook.Worksheets to access worksheet in the
current workbook
1 Dim wk As Workbook
2 Set wk = ThisWorkbook.Worksheets("Sheet1")
3 wk.Range("A1") = 1
Anywhere you see this code you can replace it with code that uses the code name. So the previous
example could be written as
1 Sheet1.Range("A1") = 1
If the code is in a different workbook, then you need to open the workbook first. You use the
Workbooks.Open function to open the workbook
1 ' Open Workbook
2 Dim wkBook As Workbook
3 Set wkBook = Workbooks.Open(Filename:="C:\Docs\Data.xlsx", ReadOnly:=True)
Then you use worksheets collection of this workbook to access the worksheet you require. You use
the worksheet name here i.e. the name on the tab at the bottom of the worksheet in Excel.
It is very difficult to see what this code is doing without stepping through the code with the
debugger and seeing exactly what is happening.
If we rewrite the code above using variables it is much more obvious what it is doing
Not only is the code more readable, it is much less likely to have errors. If it does have errors it is
much easier to locate them and fix them.
Magic numbers are numbers other than 0 and 1 that appear in the code.
When we look at this code we have no idea what the number 5 refers to. It could be a bonus value, a
row etc.
If we rewrite the code to use constants it makes the code much clearer
1 Range(RESULT_CELL) = Total * BONUS
This makes our code easier to read and understand. It also means that if we want to change the
value of BONUS we only have to change it in one place in the code.
Imagine we were changing the value of the number 5 in the code. We would have to search
everywhere that a 5 is used and check if this is being used as the BONUS.
Imagine you have been reading up on VBA and you have decided to try out using a Collection in your
application. If you are not familiar with Collections then putting them straight into your project can
waste you considerable time.
Firstly you have to run your full application each time to test what the collection is doing. The code
in your application may affect how the Collection works and the Collection may affect how the
application works.
It makes more sense to create a new workbook and try out the Collection here. It will be much
quicker to run and you can easily test different inputs and outputs.
1 Sub CheckCollection()
2
3 Dim coll As New Collection
4 coll.Add "Apple"
5 coll.Add "Pear"
6
7 coll.Remove (1)
8
9 End Sub
We can then step through the code using F8. Add we go through the code we check the Collection
values in the Watch Window (see screen shot below).
To add a Watch, simply right-click on a variable and select “Add Watch”. Then click Ok on
the dialog that appears.
You can then watch the values of your variables as your applications runs.
When you are happy that you understand how the Collection works you can move to the
next stage.
The next stage is to create a simple version of the code you will use in your application. You
can test and update this code until it is close to what you want.
It is then easy to add it to your project. Approaching the problem this way will save you
considerable time and complexity.
In the above examples, your code may be fine but due to circumstances beyond your control
you may get an error.
Just because you cannot control these type of scenarios doesn’t mean you should ignore
them.
It is good practise to write code to handle these types of events. Let’s have a look at some
code examples.
If the Dir function returns an empty string then we know that the file does not exist. In this
case, we give a message to the user and exit the sub.
If the file is found then you can continue on and open the workbook
1 ' Open Workbook
2 Dim wkBook As Workbook
3 Set wkBook = Workbooks.Open(Filename:="C:\Docs\Data.xlsx",
ReadOnly:=True)
In the following code we are checking if a Collection has entries and informing the user if
there are none
1 ' Check a collection has entries
2 If Coll.Count = 0 Then
3 MsgBox "There are no customer for the current selection."
4 Exit Sub
5 End If
In this case, having no entries is not an error. The issue is this. Imagine the user makes a
selection and there are no entries for their selection choice. If we don’t give them a message
it looks like the application is not doing anything. So it is a good idea to point out why no
results were returned.
Always check files and other obvious items like connection to a database etc.
Don’t overdo it. For example, don’t check every cell in a worksheet to see if it is valid.
Pick one or two.
If an error crops up then considerable how you would like the application the handle
the situation if it occurs again.
CONCLUSION
You have seen the 7 Steps that I use when building a VBA application. I use these steps for
every types of application from small to large and complex.
They work! They have been tested time and time again in the most demanding of
environments.
If you use them you will see dramatic improvement in your applications in terms of quality
and speed to create.
I have used these steps to build 10 VBA applications. These applications cover all aspects of
Excel from reports to databases, sending emails, reading data from website and much more.
The applications come with step-by-step guide and fully working application so you can see
exactly how I build them.
I call this package The Excel VBA Handbook. You can find out more about it here