Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

7 Steps To Creating Professional Quality Vba Macros

Download as pdf or txt
Download as pdf or txt
You are on page 1of 21

TABLE OF CONTENTS

Table of Contents ___________________________________________________________ 0


Introduction _______________________________________________________________ 1
#1 Create a simple framework _________________________________________________ 2
#2 Use this quick and easy method to test your output _____________________________ 4
#3 Reduce errors using this little-known option ___________________________________ 7
#4 Make selecting the correct worksheet a snap __________________________________ 9
#5 Make your code easy to read and user friendly ________________________________ 12
#6 Use the “Sandbox” method to solve complex tasks _____________________________ 15
#7 Make your macros tough to break __________________________________________ 17
Conclusion ________________________________________________________________ 19
7 Steps to Creating Professional Quality VBA Macros 1

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.

TheExcelVBAHandbook.com @2016 All Rights Reserved.


7 Steps to Creating Professional Quality VBA Macros 2

1 CREATE A SIMPLE FRAMEWORK

Creating a simple framework will make your code

 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

Click_Events Team_Results Test_Print

• GenerateReport_Click() • CreateReport() • PrintArrays()


• ClearMatchData_Click() • ClearReportArea() • PrintCollection()
• CreateTextFile_Click() • CreateTeamResults()

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.

TheExcelVBAHandbook.com @2016 All Rights Reserved.


7 Steps to Creating Professional Quality VBA Macros 3

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.

TheExcelVBAHandbook.com @2016 All Rights Reserved.


7 Steps to Creating Professional Quality VBA Macros 4

USE THIS QUICK AND EASY METHOD TO


2 TEST YOUR OUTPUT
Debug.Print prints to the Immediate Window. It is simple to use but a really powerful feature.
As we create out application we can use it to write to the Immediate Window.

TheExcelVBAHandbook.com @2016 All Rights Reserved.


7 Steps to Creating Professional Quality VBA Macros 5

The following are some examples of using Debug.Print

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

We can use Debug.Print to test our framework before we add code.

1 Public Sub CreateReport()


2
3 ' 1. Turn off functionality such as auto calculations
4 TurnOffFunctionality
5
6 ' 2. Clear existing data
7 ClearReportArea
8
9 ' 3. Find and copy matches
10 CreateTeamResults
11
12 ' 4. Turn functionality back on
13 TurnOnFunctionality
14
15 End Sub
16
17
18 Public Sub TurnOffFunctionality()
19 Debug.Print "TurnOffFunctionality()"
20 End Sub
21
22 Public Sub TurnOnFunctionality()
23 Debug.Print "TurnOnFunctionality()"
24 End Sub
25
26 Public Sub ClearReportArea()
27 Debug.Print "ClearReportArea()"
28 End Sub
29
30 Public Sub CreateTeamResults()
31 Debug.Print "CreateTeamResults()"
32 End Sub

TheExcelVBAHandbook.com @2016 All Rights Reserved.


7 Steps to Creating Professional Quality VBA Macros 6

The above code will give the following output

TheExcelVBAHandbook.com @2016 All Rights Reserved.


7 Steps to Creating Professional Quality VBA Macros 7

REDUCE ERRORS USING THIS LITTLE-


3 KNOWN OPTION
You may not know this, but there are three types of errors in VBA

1. Syntax errors – on a single line


2. Project errors – on multiple lines
3. Run time errors – these occur when your application is running

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

TheExcelVBAHandbook.com @2016 All Rights Reserved.


7 Steps to Creating Professional Quality VBA Macros 8

Compile finds syntax errors as well. However it also finds errors where the syntax maybe
correct but the code doesn’t make sense.

Examples of these errors are

 For loop without a corresponding Next

 If without End If

 With without End With

 Calling a Sub that does not exist

 Calling a Sub with incorrect parameters

 And so on

The following code is missing the Next statement.


1 Sub TestFor
2 For i = 1 To 10
3 End Sub

If you use Debug->Compile you will get the following error

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.

It is always a good idea to use it before you run your code.

TheExcelVBAHandbook.com @2016 All Rights Reserved.


7 Steps to Creating Professional Quality VBA Macros 9

MAKE SELECTING THE CORRECT


4 WORKSHEET A SNAP
The three most important elements of VBA are workbooks, worksheets and ranges. You use
them in every VBA project you undertake.
There are multiple ways to access a worksheet and this leads to confusion all the time.

I have made selecting the correct worksheet as simple as possible. There are two type of
worksheets:

1. One that is in the current workbook


2. One that is in another workbook

By current workbook I mean the workbook where your code is.

If your code is in the current workbook then use the code name of the workbook.

What is the code name?

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.

TheExcelVBAHandbook.com @2016 All Rights Reserved.


7 Steps to Creating Professional Quality VBA Macros 10

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.

We can use the code name directly in code


1 CodeName.Range("A1") = 99
2 CodeName.Range("A1") = "John Smith"

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

TheExcelVBAHandbook.com @2016 All Rights Reserved.


7 Steps to Creating Professional Quality VBA Macros 11

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.

1 Dim shData As Worksheet


2 Set shData = wkBook.Worksheets("Sheet1")

Once you have the worksheet you then use it as normal


1 shData.Range("A1") = 99
2 shData.Range("A1") = "John Smith"

TheExcelVBAHandbook.com @2016 All Rights Reserved.


7 Steps to Creating Professional Quality VBA Macros 12

MAKE YOUR CODE EASY TO READ AND


5 USER FRIENDLY
There are lots of way to make your code user friend. Here we’re going to look at the two
major ones in VBA

 Use meaningful variable names instead of ranges

 Avoid using magic numbers

TheExcelVBAHandbook.com @2016 All Rights Reserved.


7 Steps to Creating Professional Quality VBA Macros 13

Take a look at the following code

1 If cnReport.Cells(i, COL_YEAR) = cnData.Cells(rowRep, COL_DATA_YEAR) Then


2 cnReport.Cells(i, COL_RES) = cnData.Cells(i, COL_DATA_YEAR) + 1
3 ElseIf cnReport.Cells(i, COL_YEAR) = cnData.Cells(rowRep, COL_DATA_YEAR) Then
4 cnReport.Cells(i, COL_RES) = cnData.Cells(i, COL_DATA_YEAR) + cnData.Cells(i,
5 COL_BONUS)
6 Else
7 cnReport.Cells(i, COL_RES) = cnData.Cells(i, COL_DATA_YEAR) * cnData.Cells(i,
8 COL_BONUS)
9 End If

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

1 If sRepYear = sDataYear Then


2 lResult = lResult + 1
3 ElseIf sRepYear > sDataYear Then
4 lResult = lResult + lBonus
5 Else
6 lResult = lResult * lBonus
7 End If
8
9 cnReport.Cells(i, COL_RES) = lResult

All we need to do it place the cell values in variables first

1 sRepYear = cnReport.Cells(i, COL_YEAR)


2 sDataYear = cnReport.Cells(i, COL_DATA_YEAR)
3 lBonus = cnReport.Cells(i, COL_BONUS)
4 lResult = cnReport.Cells(i, COL_RES)

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.

TheExcelVBAHandbook.com @2016 All Rights Reserved.


7 Steps to Creating Professional Quality VBA Macros 14

Magic numbers are numbers other than 0 and 1 that appear in the code.

For example, look at this line of code


1 Range("C7") = Total + 5

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

We can create constants like this


1 ' Constants
2 Public Const BONUS As Long = 5
3 Public Const RESULT_CELL As String = "C7"

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.

TheExcelVBAHandbook.com @2016 All Rights Reserved.


7 Steps to Creating Professional Quality VBA Macros 15

USE THE “SANDBOX” METHOD TO


6 SOLVE COMPLEX TASKS
In simple terms the “Sandbox” method means working with code in isolation where it cannot affect
anything or be affected by anything.

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.

For example we could take sample code like the following

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

TheExcelVBAHandbook.com @2016 All Rights Reserved.


7 Steps to Creating Professional Quality VBA Macros 16

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.

TheExcelVBAHandbook.com @2016 All Rights Reserved.


7 Steps to Creating Professional Quality VBA Macros 17

MAKE YOUR MACROS TOUGH TO


7 BREAK
We have looked at Syntax and Compile errors. The third type of error is a Runtime error.
These are errors that only occur when you code is running. They depend on something
external to your code.

Some examples of run time errors are:

 A file cannot be found

 Cell value is text instead of a number

 The worksheet is not the one you expected

 No data is available for a particular selection

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.

TheExcelVBAHandbook.com @2016 All Rights Reserved.


7 Steps to Creating Professional Quality VBA Macros 18

In the following code we check if a file exists


1 ' Check if the file exists
2 If Dir(sFilename) = "" Then
3 MsgBox "Could not find the workbook: [" & sFilename & "]."
4 Exit Sub
5 End If

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.

How do you determine what to check?

 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.

TheExcelVBAHandbook.com @2016 All Rights Reserved.


7 Steps to Creating Professional Quality VBA Macros 19

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

TheExcelVBAHandbook.com @2016 All Rights Reserved.

You might also like