Beruflich Dokumente
Kultur Dokumente
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 straightforward.
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 makes itm 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 may be
correct but the code doesnt make sense.
If without End If
And so on
1 Sub TestFor
2 For i = 1 To 10
3 End Sub
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.
I have made selecting the correct worksheet as simple as possible. There are two types of
worksheets:
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 then 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 sh As Workbook
2 Set sh = ThisWorkbook.Worksheets("Sheet1")
3 sh.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
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 the same way you used the code name.
1 shData.Range("A1") = 99
2 shData.Range("A1") = "John Smith"
However, it is better to use the code name here as well. You cant use it directly but you can
get it using the following function
1 ' This function gets the worksheet object from the Code Name
2 Public Function SheetFromCodeName(Name As String, bk As Workbook) As
3 Worksheet
4
5 Dim sh As Worksheet
6 For Each sh In bk.Worksheets
7 If sh.CodeName = Name Then
8 Set SheetFromCodeName = sh
9 Exit For
10 End If
11 Next sh
12
13 End Function
If the user changes the worksheet name, the code will still work fine.
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.
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 doesnt mean you should ignore
them.
It is good practice to write code to handle these types of events. Lets 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 customers 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 dont 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 the connection to a database etc.
Dont overdo it. For example, dont check every cell in a worksheet to see if it is valid.
Pick one or two.
If an error crops up then consider 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