You are on page 1of 32

+Contents

Welcome................................................................................................................................................3

Ground rules..........................................................................................................................................3

Introduction...........................................................................................................................................3

Course notes (Transcript.doc)................................................................................................................3

What is VBA?..........................................................................................................................................4

How do I program VBA?.........................................................................................................................4

Terminology...........................................................................................................................................5

Writing our first Sub...............................................................................................................................6

1. Creating a Module......................................................................................................................6

2. Renaming our Module................................................................................................................6

3. Creating a Sub.............................................................................................................................6

4. Running a Sub.............................................................................................................................6

5. Seeing the result of the Sub........................................................................................................7

Writing our second Sub..........................................................................................................................7

1. Creating, and assigning, a VBA Variable.....................................................................................7

2. Updating the value of cell B1, to concatenate it with a VBA Variable........................................8

3. Updating the values of cells in range C3:F6................................................................................8

Running a Sub Revisited!........................................................................................................................8

Extending our Sub..................................................................................................................................8

Saving your work....................................................................................................................................9

Opening your work.................................................................................................................................9

Debugging a Sub...................................................................................................................................10

VBA Variables Revisited........................................................................................................................10

Writing our third Sub............................................................................................................................11

How to force VBA Variable definitions with Option Explicit...................................................12

Defining VBA Variables.........................................................................................................................13

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 1/32
VBA Variable naming rules...................................................................................................................14

VBA Variable types...............................................................................................................................15

VBA Comments.....................................................................................................................................15

The For … Next statement...........................................................................................................15

The Step statement with the For … Next statement..............................................................16

VBA Cheating - Record a Macro...........................................................................................................17

Loops within Loops...............................................................................................................................18

Generate random numbers Sub...........................................................................................................19

Give me a random background colour.................................................................................................20

The If … Then … Else statement.............................................................................................21

User interaction with the InputBox Function................................................................................23

Executing a Sub, from a Sub, using the Call Function.....................................................................24

Receiving parameters passed from the Call Function....................................................................24

Error trapping.......................................................................................................................................25

The IsNumeric() Function...........................................................................................................27

The Do … Loop While statement...............................................................................................28

Let’s put it all together for a better Sub...............................................................................................28

Can we move from a better Sub to an Ultimate Sub?..........................................................................29

The VBA Constant vbNullString..................................................................................................29

The Exit Sub Function..................................................................................................................30

The GoTo Instruction........................................................................................................................31

User warning with the MsgBox Function.........................................................................................32

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 2/32
Welcome
Hello and welcome to the Introduction to Programming module of your course.
We're going to use VBA in Excel, although we could have used VBA in Word, or a different
application.

I’m James Davies, and you can you can phone me directly at any time during this course, or you can
contact me by email, or by Skype. If you have any questions, or do not understand something I have
said, then please stop me at any time…I like questions...

James DAVIES:
06 22 82 06 39
james@netalapage.com
james.davies.netalapage

Ground rules
Firstly, this is the Introduction to Programming module. I'm not going to hide it, It's technical.
For those who are panicking, we're going to go slowly, and it should be understandable to everyone.
Think of programming as a logic problem, or a maths enigma, or a Crossword, or a Sudoku puzzle...
everyone can do it.

And secondly, I enjoy teaching, and I choose to be here, which is great. But what is not great is
talking and disturbing others. So that's the deal – if you are here, please do so quietly, and with
respect for me, and for the others.

Oh - and that respect also extends to smelly food - if you want to eat or drink, then please do so, but
do it quietly, do not leave a mess, and don't bring anything too stinky, ok?

Introduction
So, this course will give you an introduction to programming, and we have chosen to use VBA in
Excel. This is because you will probably already have Excel installed on your computer.
It’s probably easiest if you use that for this course and the final exam.
However, if you prefer, you can use the Citrix Portal and the virtual desktop of the school.

Course notes (Transcript.doc)


This Word document contains the first bit of your course and is all that you need to pass the exam.

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 3/32
It is available for download, from the Extranet, and I suggest you grab it now, and then you can add
your own explanations to it.

What is VBA?
Well, the initials stand for Visual Basic for Applications.
And it's a programming language, closely related to Microsoft's event-driven programming language
Visual Basic, developed to run in a host application (Excel, Word, ...) rather than as standalone
program.

The result is a powerful and sophisticated programming language, which is fully integrated and built
into Excel for you. It has always been there, but probably not many of you have ever knew that you
had access to a complete programming language all of this time.

It allows you to write commands, and design your own functions, that will make every day, boring
Excel tasks quicker and more efficient. There is no limit to what it can do, as it is up to you to decide
and program whatever you want.

How do I program VBA?


This is performed in the VBA Editor.
And this is found under the Developer tab (onglet Développeur).

If you do not have this showing, you will need to activate this now, and of course this varies from
version to version, and from PC to Mac.
It's under Excel Options, or Preferences, and may either be a check-box that must be ticked, or an
option that must be added to the Ribbon Menu at the top of Excel.
(Macs have a brilliant feature that enable to you search for this option)

Once it is activated, please click the Developer tab (onglet Développeur), and then
Visual Basic. The keyboard shortcut is ALT + F11. Both approaches will open the VBA
Editor, and it should look something like the following:

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 4/32
There are 3 main windows:

1. Project Window is on the top left and shows all the projects you have and allows you to
choose between them. If it is not shown, press CTRL + R to open it.

2. Properties Window is on the bottom left and displays and allows editing of all the properties
associated with the selected object. If it is not shown, press F4 to open it.

3. Code Window is on the right-hand side and is where we will write the actual code. This will
also show any Macros which have been recorded, shown within module sheets under
generic names such as Module1, Module2, etc.

In our example, we are looking at the code associated with worksheet 1.


On older versions, especially on Macs, it may look closer to the following:

This offers reduced functionality, but it will be enough for this course.
Here, we have the Code Window on the right where we will create our programs, and the Project
Window on the left to manage the locations of our code.

However, there is no Properties Window, and the functionality to run our programs is restricted to
the buttons on the bottom right.

Terminology
Line of code: This is a VBA instruction.
Usually, one instruction is one line, which will perform one task.

Sub: Made up of one or more lines of code.


When the Sub is run, VBA goes through all the lines, and executes them all.

Function: This is the same as a Sub, but it will return a value.

Module: This is a container for Subs and Functions.

VBA Editor: This is where we write our code.

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 5/32
Writing our first Sub

1. Creating a Module
Firstly, let's create a new Module to hold out work:
In the Project Window, click on the Workbook to activate it.
Click Insert (Insertion), and then select Module (Module) in the drop-down list.

2. Renaming our Module


If your version of VBA Editor has a Properties Window, then click the newly created Module.
The name will appear in the Properties Window, where you can change it to PSB.

If your version of VBA Editor does not have a Properties Window, try right clicking on the newly
created Module, and select Rename (Renommer) in the drop-down list.
Change the name to PSB.

In both cases, the name PSB will now be shown at the top of the VBA Editor.

3. Creating a Sub
Subs are entered in the Code Window. There are 2 ways to get here:

1. Simply click in the Code Window

2. Double click PSB in the Module list, within the Project Window

Note: Subs need 4 things:

1. The keyword Sub

2. The name of the Sub

3. Parentheses to accept the Parameters to the Sub


If no parameters are required, they must still be present, but they will be empty ()

4. The keywords End Sub to indicate the end of the Sub

Enter the following:

Sub myFirstSub()
Cells(1, 2) = "Hello World!"
End Sub

4. Running a Sub
Make sure your cursor is over one of the 3 lines you have just entered in your Sub myFirstSub().
Then click the Green Arrow just above the Code Window, or the Double Arrow just below the Code
Window, or press F5, depending on which version of the VBA Editor you are using, to execute it.

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 6/32
That's it!
That's all there is to it!

5. Seeing the result of the Sub


The easiest way is to arrange your windows so that you can see both the Excel spreadsheet and the
VBA Editor at the same time. And you should see the words Hello World! appear in cell A1.

Writing our second Sub


Now we've got a taste of VBA, let's get straight onto the next Sub.
Under the same Module, in the Code Window, please enter the following:

Sub mySecondSub()
text = InputBox("Please enter your text", "Text Entry")
Cells(1, 2) = Cells(1, 2) + " > " + text
Range("C3:F6") = text
End Sub

Make sure your cursor is over one of the lines you have just entered in your Sub mySecondSub().
Then click the Green Arrow just above the Code Window, or the Double Arrow just below the Code
Window, or press F5, depending on which version of the VBA Editor you are using, to execute it.

A pop-up Input Window is displayed, with the parameters defined in the first line of the Sub.

Enter some text, say James, and this will be concatenated to the text in cell B1, separated by a
greater than sign for clarity, and the same text inserted into all of the cells in the range C3:F6.

Run it again, and enter some different text, say Loves, and the same thing happens again.
And run it a last time, and enter say Excel, just to check everything is great.
This is fantastic, and I'm hoping you can see what is happening in the 3 lines within this Sub.
Let's just go through them now:

1. Creating, and assigning, a VBA Variable


The first line assigns a value to a VBA Variable, which here, is called text:

text = InputBox("Please enter your text", "Text Entry")

And at the end, the VBA Variable text contains the value entered in the Input Box.

Note: VBA, like most programming languages, performs this in 3 steps:

1. Variable name (here it is text)

2. Excel assignment keyword =

3. Variable value (here it is the return value from the Method InputBox)

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 7/32
2. Updating the value of cell B1, to concatenate it with a VBA Variable
The second line assigns a value to the cell B1.
This cell is accessed via Cells(1, 2)

It follows the same format as we have just seen in assigning a value to a VBA Variable.
The 3 parts are what we want to assign a value to, the assignment keyword =, and lastly the value.

Cells(1, 2) = Cells(1, 2) + " > " + text

And here, the value we are setting is also composed of 3 things:

1. The existing value, as indicated by Cells(1, 2)

2. A space, followed by a pipe, followed by a space, as indicated by " > "

3. And the value from the Input Box, as indicated by the VBA Variable text

The result is whatever was entered in the Input Box, is concatenated to the end of the value in B1.

3. Updating the values of cells in range C3:F6


The third line assigns values to all of the cells in the range C3:F6.

Note: Previously, we used the VBA Object Cells.


(This points to 1 single cell)

Now we want to update multiple cells.


(We therefore must use the VBA Object Range)

And once again, we find the same 3 parts when assigning values in VBA:
Firstly what we want to assign a value to, then the assignment keyword =, and lastly the value itself:

Range("C3:F6") = text

Running a Sub Revisited!


Ok, now that we have 2 Subs defined within our Module, I want to share something.
In the Code Window, click on one of the lines in the first Sub, myFirstSub(), and then run it.

The extra text we have concatenated is now removed.


As we saw previously, this Sub sets the value of cell B1 to Hello World!

Now click on a blank line in the Code Window and run it again.
This time a pop-up dialogue box, with the available Subs, is shown.
This time, you need to select which one to run, and then click Run (Exécuter).

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 8/32
Extending our Sub
Ok, add one line to our second Sub, mySecondSub().

This will change the value of cell E8 so that it contains the value of the VBA Variable Text,
concatenated with the symbol <, concatenated with the current value of cell E8, concatenated
with the symbol >, concatenated with the value of the VBA Variable Text.

Cells(5, 8) = Cells(1, 2) + ">" + Text

Saving your work


Go back to your spreadsheet and try and save it as macros.
Hopefully the following warning dialogue is shown, as we have no included some VBA:

Basically, in order to save it, you must change the filename extension to .xlsm
So, follow the instructions, and click No.
Then change the default file extension, and specify .xlsm
And finally, please save your work now as macros.xlsm

Remember, the filename extension indicates which version of Excel can process the file:

.xlsx is an Office Open XML format (OOXML) introduced with Microsoft Office 2007
(it has been the default Excel format ever since)

.xls is a legacy filename extension, which was deprecated with Microsoft Office
2007, but used by Excel versions 97, 2000, 2002, and 2003
(there were no other versions of Excel between 2003 and 2007)

.xlsm is an Excel Macro-Enabled Workbook file, created with Microsoft Excel 2007
or newer, and is actually identical to an .xlsx file, except it will execute
embedded macros programmed in VBA

Opening your work


Now it's saved, please close your Excel spreadsheet.
Next, and yes it sounds mad, but please do it, open it again.

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 9/32
As the spreadsheet contains VBA, a warning is displayed:

In order to run your VBA, you must authorise and activate the macros.

Debugging a Sub
This is incredibly useful when your VBA code does not produce the expected results.
It allows you to execute line by line the code in a Sub.

Make sure your cursor is over one of the lines you have just entered in your Sub mySecondSub().
Instead of clicking the Green Arrow just above the Code Window, press the keyboard shortcut F8.

The line about to be executed will be highlighted in yellow.


(In other words, this line has not yet been executed)

To execute it, press F8.


This will advance the execution line by line.
Keep pressing F8 until the end of the Sub is reached.

At any time, you can click the Green Arrow just above the Code Window, or the Double Arrow just
below the Code Window, depending on which version of the VBA Editor you are using, and the Sub
will execute in one go as normal.

VBA Variables Revisited


Ok, we've already introduced a VBA Variable called text, within the Sub mySecondSub().
And the important thing, is that we didn't assign a type to this VBA Variable.

Some programming languages are Loosely Typed, which means:

 you declare variables without a type AND

 type coercion is allowed

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 10/32
Basically, it means you don't need to bother with types too much!
(It also means that the language converts automatically between types, to try and help you out)
Some examples include JavaScript and PHP.

The opposite, is a Strongly Typed Language, and examples include C, C++, and Java.
(Here, the name and type of variable must be defined before using it)

Here in our VBA, we didn't assign a type, so Excel assigns a default VBA Variable type of Variant.
(Basically, we didn't determine the type, Excel did!)

It's not always a bad thing to leave it to Excel, and to not declare a type.
And the Variant VBA Variable type is more flexible than other VBA Variable types.
(It can also be quite powerful and useful in some circumstances!)

Writing our third Sub


To check you understand, let's see this in a third Sub.
Under the same Module, in the Code Window, please enter the following:

Sub myThirdSub()
james = 1
Cells(3, 1) = james
ethan = james + 1
Cells(3, 2) = james
james = "PSB"
Cells(4, 1) = james
james = james + " Rocks"
Cells(4, 2) = james
End Sub

Make sure your cursor is over one of the lines you have just entered in your Sub myThirdSub().
Then click the Green Arrow just above the Code Window, or the Double Arrow just below the Code
Window, or press F5, depending on which version of the VBA Editor you are using, to execute it.

There's our proof - the same VBA Variable james has been used for different VBA Variable types:
The first value is numeric, and so the assignment keyword + is treated as addition.
Then the value is changed to text (or String) so the assignment keyword + is now concatenation.
However, the disadvantages of VBA Variables of type Variant usually outweigh the advantages:

 They are inefficient in terms of memory use

 They result in slower execution of VBA applications

 You cannot use the AutoComplete feature

 Excel will not perform full Error Checking

 Mistakes are more likely, and the code is less clear

 Debugging is harder

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 11/32
You must have understood - I prefer not using VBA Variables of type Variant!
And I prefer to always define my VBA Variables!

How to force VBA Variable definitions with Option Explicit


There is a great way to tell the VBA Editor to always check you have defined your VBA Variables.
At the top of your module, before your Sub myFirstSub(), type the following:

Option Explicit

That's all there is to it.


To test it out, try and run the Sub mySecondSub(), which uses the undefined VBA Variable
text. The VBA Editor shows a compile error:

So, from now on, all of your VBA Variables must be defined in this entire Module.

When I press Enter, my screen looks like the following:

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 12/32
There are 4 important things to notice:

1. The VBA Editor has entered what looks like debug mode
(In fact, the line in yellow it is showing you the last line without an error)

2. The VBA Variable text on the next line is in reverse image


(This is showing you which VBA Variable is causing the error)

3. You can press the Green Arrow to continue – please try that now
(But this is useless as we haven’t fixed the error, so the same error message will be shown)

4. You can now press the Blue Box to reinitialise – please try that now
(This will stop the execution of your Sub, and allow you to fix the error)

Defining VBA Variables


The most common way of declaring a VBA Variable is by using the Dim statement.
And we know we have to do this for our VBA Variable text in the Sub mySecondSub().

Immediately after the line:

Sub mySecondSub()

Add the following:

Dim text As String

That’s it, you have now defined the type of the VBA Variable text, and so your Sub is now valid!

Note: There are 3 other keywords which may be used to declare a VBA Variable:

1. Static

2. Public

3. Private

However, these are not needed for this course, and we will always use the Dim statement

Note: The keyword Dim stands for dimension. Previously it was used to define the dimensions of
an array, but it is now used to define any VBA Variable, whether it is an array or not!

Let’s now fix the Sub myThirdSub().


Currently when I try and run it, I get the old Variable not defined error message.
So, immediately after the line:

Sub myThirdSub()

Add the following:

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 13/32
Dim james As Integer

Now when I run it, the VBA Variable james is defined, so the error message is not shown.
However, I now get a new error message.
This is because I’m trying to use a VBA Variable which is defined as an Integer type, with String data:

This is the VBA Editor telling me that the types are incompatible!
Once a VBA Variable is defined, it keeps that type for the whole Sub.

To fix this, we’ll need to use 2 variables: one for the Integer value, and one for the String value.
For speed, I’m going to define a VBA Variable james2 as a String. Please add:

Dim james2 As String

And then, the 4 lines that reference the VBA Variable james as a String, must be changed to use
the new VBA Variable james2.

Run your Sub to check there are no errors, and that the result is as expected.
Phew! All seems well now!

VBA Variable naming rules


One of the most important things, is to use meaningful names for your VBA Variable.
(In the previous example, the name james is absolutely terrible!)
So always try and use names that reflect the use of the VBA Variable in your code.

There are some rules to follow for the choice of your VBA Variable names:

 Names must begin with a letter

 Names can contain letters, digits, and underscores.

 Names cannot be VBA Reserved Words (for example, Sub, Dim, Next, and For)

 Names are not case sensitive

 The maximum length is 255 characters

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 14/32
But apart from that, they can be pretty much anything you want!

I have 2 further recommendations though:

1. Begin your names with a lower-case character, to separate them from the VBA keywords

2. Even though names are not case sensitive, use camel case for readability
(e.g. totalWithoutTax, clientPostCode, weightOfOrder, …)

VBA Variable types


The following shows the main VBA Variable types:

 Boolean -1 or 0

 Byte 0 to 255

 Integer -32 768 to 32 767

 Long Integer -2 147 483 648 to 2 147 483 647

 Single For numbers with decimal places or fractions

 Double Same as Single, but bigger range

 String Stores values or numbers, but treats them all as text

 Date 1 January, 100 to 31 December, 9999

VBA Comments
As in most programming languages, comments in VBA will not be executed.
(Their only purpose is to be read by humans looking at the code)

I recommend using comments, but you must find the balance between too many and too few!

Their main tasks are to:

 Help others understand what you are doing, and why

 Remind yourself of what you did, and how you made a design choice

They are entered using the ' character, and the VBA Editor will display them in green.

The For … Next statement


Ok, let’s get back into coding, and we are going to first look at simple loops.
Please enter the following:

Sub random()

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 15/32
'Define variables
Dim rows As Byte

'Loop
For rows = 1 To 30
Cells(rows, 3) = rows
Next rows

End Sub

This is your first taste of a loop in this course!


And to see it in action, I’m going to firstly delete everything from my spreadsheet.

Next, make sure your cursor is over one of the lines you have just entered in your Sub random().
Then click the Green Arrow just above the Code Window, or the Double Arrow just below the Code
Window, or press F5, depending on which version of the VBA Editor you are using, to execute it.

When you look at what it has done, I hope you can see that it has followed your exact instructions.
It has looped for 30 rows, and for each iteration of this loop, it has performed the code within the
For … Next statements

The Step statement with the For … Next statement


Just so we are sure that we have completely understood the For … Next statement, let’s copy
our existing Sub random() to the new Sub sillyLoop().
(I’m calling it “silly” as I will be using “silly” VBA Variable names!)

Select all of the lines, and press CTRL + C to copy, then CTRL + V to paste.

Change random() to sillyLoop().


Change all 5 occurrences of rows to james.
Extend the line For james = 1 To 30 to For james = 1 To 30 Step 2
Change line Cells(james, 3) = james to Cells(james, 5) = james * james

Next, make sure your cursor is over one of the lines you have just entered in your Sub
sillyLoop(), then click the Green Arrow just above the Code Window, or the Double Arrow just
below the Code Window, or press F5, depending on which version of the VBA Editor you are using,
to execute it.

Oh no – a new error message is displayed:

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 16/32
The reason is less obvious then the previous error messages.
Here, it is saying that the space reserved for a VBA Variable is not enough for the value.
Clicking on the debug option will highlight the problem line in yellow.
And here we can see that the VBA Variable causing the problem is james.

Change line Dim james as Byte to Dim james as Integer

Next, make sure your cursor is over one of the lines you have just entered in your Sub
sillyLoop(), then click the Green Arrow just above the Code Window, or the Double Arrow just
below the Code Window, or press F5, depending on which version of the VBA Editor you are using,
to execute it.

Nice – all works without any problems.

Note: The possible maximum values for the 2 VBA Variable types are:

 Byte 0 to 255

 Integer -32 768 to 32 767

Our first attempt had the VBA Variable james being set a value greater than the
maximum value allowed!

Ok, please look at what Excel has done, and you should hopefully be able to follow the logic:
The loop is using the VBA Variable name james.
This goes from a starting value of 1, has a finishing value of 30, and will increment by 2.
The Excel cell value to be updated is column E, as indicated by Cells(james, 5)
And the value to be set is the VBA Variable james multiplied by the VBA Variable james.

VBA Cheating - Record a Macro


Ok, let’s check we understand the Step statement, by changing its value:
Change the line For james = 1 To 30 Step 2 to For james = 1 To 30 Step 5
(This should now display numbers in increments of 5)

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 17/32
Next, make sure your cursor is over one of the lines you have just entered in your Sub
sillyLoop(), then click the Green Arrow just above the Code Window, or the Double Arrow just
below the Code Window, or press F5, depending on which version of the VBA Editor you are using,
to execute it.

Ok. It’s not bad. And it has in fact worked, but we still have our old values on the spreadsheet.
What we need to do is to delete the column, before we create the new values within the For …
Next statement.
But how do we do that?
The answer – record a Macro and cheat!

Under the Developer tab (onglet Développeur), look for the option Record a
macro (Enregistrer un macro) - please click it.

A pop-up window is displayed, but as we are using this just to cheat and get the VBA code, simply
accept the defaults and press ok.

Ok, now we do in Excel what we want to do in VBA.


So right click column E and select Delete (Supprimer) from the drop-down list.
Next, click the cell E1.
Lastly, click Stop recording (Arrêter l’enregistrement).

That’s all there is to it.


You have now recorded your first macro!
Let’s use it now – so please switch back to the VBA Editor.

I now have a new module called Module1, and when I double click it, the VBA code is shown.
And this is what I want to use in our Sub sillyLoop().
Please copy the 3 lines, and paste them into our Sub sillyLoop() immediately before the loop.

Now when you run the sub sillyLoop(), the column is deleted.
Try changing the value of the Step statement to say 3, 2, or even 1.
Every time the sub siillyLoop() is executed, only the expected values are now shown.

You should add some relevant comments to the lines of VBA code that you copied from the macro.
(This is to explain what the code is trying to achieve)

Loops within Loops


Please enter the following:

Sub pattern()

'Define variables
Dim x As Integer
Dim y As Integer

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 18/32
'Loop rows
For x = 2 To 25 Step 5

'Loop columns
For y = 2 to 6 Step 2

'Colour cell
Cells(x, y).Interior.Color = RGB(255, 0, 0)

Next y

Next x

End Sub

This is your first taste of a loop in a loop in this course!

Let’s go through it again, but in step by step debug mode.


So, make sure your cursor is over a line in the Sub, and press F8.
This time, we can see the cells being filled in one by one.
(Hopefully this helps understand the loop within a loop concept!)

Generate random numbers Sub


Please change your code to have the following definition for your Sub random():

Sub random()

'Define variables
Dim rows As Byte
Dim cols As Byte

'Loop
For rows = 1 To 30
For cols = 1 to 10
Cells(rows, cols) = Int(100 * Rnd) + 1
Next cols
Next rows

End Sub

And to see it in action, I’m going to firstly delete everything from my spreadsheet.

Next, make sure your cursor is over one of the lines you have just entered in your Sub random().
Then click the Green Arrow just above the Code Window, or the Double Arrow just below the Code
Window, or press F5, depending on which version of the VBA Editor you are using, to execute it.

Ok – we have generated 300 random numbers, in 10 columns, and 30 rows. Nice!


The point of this is to demonstrate the loop construct, using the For … Next statement.
(In fact, like before, we’re using 2 loops – one loops through rows, and one loops through columns!)

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 19/32
We can add more lines to be executed during the loop. Please add the following:

Cells(rows, cols).Interior.Color = RGB(255, 0, 0)


Cells(rows, cols).Font.Color = RGB(0, 0, 255)

Execute the Sub random() again, and this time, not only are random numbers generated, but
they are shown on a background which is set to red, and with a text colour set to blue.
(This is because we have maximum Red, nothing for Green and nothing for Blue, for the background,
hence Red, and nothing for Red and Green, but maximum Blue, hence Blue, for the text colour)

Change the line:

Cells(rows, cols).Interior.Color = RGB(255, 0, 0)


to:

Cells(rows, cols).Interior.Color = RGB(0, 255, 0)

Now, the random numbers are shown on a green background, but still with a blue colour.
(This is because we now have maximum Green, and nothing for Red and Blue for the background,
hence Green)

Change the line:

Cells(rows, cols).Font.Color = RGB(0, 0, 255)

to:

Cells(rows, cols).Font.Color = RGB(255, 0, 255)

Now, the random numbers are still shown on a green background, but with a purple colour.
(This is because we have maximum Red, nothing for Green, and maximum Blue for the text colour,
hence Purple)

Give me a random background colour


Ok. We have generated a random number for the cell contents, but how about generating a random
number for the background colour, resulting in a random colourful pattern?

The code Int(100 * Rnd) + 1 gives a random number from 1 to 100.


The code Int(50 * Rnd) + 25 gives a random number from 25 to 75.
So the code Int(256 * Rnd) gives a random number from 0 to 255.

Currently our line is:

Cells(rows, cols).Interior.Color = RGB(0, 255, 0)

so, please change this to:

Cells(rows, cols).Interior.Color = RGB(0, Int(256 * Rnd), 0)

Run the Sub random() again, and this time the numbers are displayed with a random Green
background colour.

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 20/32
If we want a completely random colour, we need to also randomise the Red and Blue parts.
Change the line:

Cells(rows, cols).Interior.Color = RGB(0, Int(256 * Rnd), 0)

to:

Cells(rows, cols).Interior.Color = RGB( _


Int(256 * Rnd), _
Int(256 * Rnd), _
Int(256 * Rnd) _
)

Run the Sub random() again, and this time the numbers are displayed with a completely random
background colour, as all of the Red, Green and Blue values are randomly generated.

Note: The character _ allows a VBA line of code to be split over multiple lines

The If … Then … Else statement


The next thing for us to look at, is how to make decisions.
And almost all programming languages use the same construct – execute some code if a specified
condition evaluates to TRUE, or another set of code if it evaluates to FALSE.

In VBA, the simplest form is defined as:

If condition_1 Then

code_1

End If

However, this can be extended to more complex scenarios using ElseIf and Else:

If condition_1 Then

code_1

ElseIf condition_2 Then

code_2

ElseIf condition_n Then



code_n

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 21/32
Else

code_else

End If

An example may make this clear.

Suppose we want to put some text in the cell A3 depending on the value of the cell C9.
If the value of cell C9 is greater than 8, then we want Great Score to be shown:

If Cells(9, 3) > 8 Then


Cells(3, 1) = "Great Score"
End If

And, to extend this to include other messages, we could put:

If Cells(9, 3) > 8 Then


Cells(3, 1) = "Great Score"
ElseIf Cells(9, 3) > 6 Then
Cells(3, 1) = "Not Bad"
Else
Cells(3, 1) = "Try Harder!"
End If

Let’s code a more useful example.


It’s going to be similar to the Sub random() so the easiest thing to do is to copy and paste this.

Rename the new Sub to highlight().


Delete the 3 lines that are performed inside the For … Next statement.
And we are now ready to rock and roll!

The goal here is to inspect the value of every cell, and to do 1 or 3 things:

1. If < 10, give it a red background

2. If > 90, give it a green background

3. Anything else, give it a normal background


(We have to do this, as our Sub random() sets the background to red!)

The first bit is easy – we introduce the If … Then statement, and the condition to evaluate:

If Cells(rows, cols) < 10 Then

If this evaluate to TRUE, we want the background to be red. Please add:

Cells(rows, cols).Interior.Color = RGB(255, 0, 0)

Next, we need to test another condition, so we must use the ElseIF statement:

ElseIf Cells(rows, cols) > 90 Then

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 22/32
And again, we need to code what to do is this evaluates to TRUE. This time, we want it to be green:

Cells(rows, cols).Interior.Color = RGB(0, 255, 0)

Lastly, if it is anything else, remove the background colour, so we need our Else statement, and
the code to be executed if we get here:

Else
Cells(rows, cols).Interior.Color = xlNone

And the last thing to do, is to finish our If statement, with an End If statement.
So, putting it all together, we get:

If Cells(rows, cols) < 10 Then


Cells(rows, cols).Interior.Color = RGB(255, 0, 0)
ElseIf Cells(rows, cols) > 90 Then
Cells(rows, cols).Interior.Color = RGB(0, 255, 0)
Else
Cells(rows, cols).Interior.Color = xlNone
End If

User interaction with the InputBox Function


We have already seen this in use within our Sub mySecondSub().
It’s a great (and simple) way to get user interaction into our VBA code.

The goal here is to create a new Sub, which will accept 2 values from the user:

1. A Lower Value, which determines whether the background is to be set to Red

2. An Upper Value, which determines whether the background is to be set to Green

Let’s call this values. So, to start with, please enter the following:

Sub values()

'Define variables
Dim lower As Byte
Dim upper As Byte

End Sub

Cool, let’s get those values now. Please enter the following:

'Get values
lower = InputBox("Please Enter Lower Value", "Low Value")
upper = InputBox("Please Enter Upper Value", "High Value")

Nice! The user enters some numbers, and we get them into the VBA Variables lower and upper.
All that is left is to actually use them!

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 23/32
Executing a Sub, from a Sub, using the Call Function
The first thing is to pass these numbers to our existing Sub highlight().
And for this, we need the Call Function. Please enter the following:

'Call highlight
Call highlight(lower, upper)

This should be fairly clear – we are passing the values in the VBA Variables lower and upper to
the Sub called highlight(). We could have written:

'Call highlight
Call highlight(10, 90)

but this would have been so much more boring. In this case, we always pass the values 10 and 90.
(The beauty of programming languages is that variables allow us to change the nature of the code)

What I am hoping is that you realise that we are getting values from the user into our VBA Variables,
and then using these pass to our Sub, where the will be used!

Receiving parameters passed from the Call Function


Ok, as it stands the Sub values() will not execute.
If you try and click the Green Arrow just above the Code Window, or the Double Arrow just below
the Code Window, or press F5, depending on which version of the VBA Editor you are using, to
execute it, you will get the following error:

If you now press the Blue Box to reinitialise, you will find that you can still execute the Sub
highlight(). The problem is with the calling of the Sub, and not with the Sub itself!

To fix this, we need to extend Sub highlight() to accept parameters. Please change the line:

Sub highlight()

to:

Sub highlight(low As Byte, high As Byte)

Nice. As we are now accepting parameters in our Sub highlight() the Sub values(), which
calls it, should now execute with no problems. Let’s try that now.

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 24/32
Make sure your cursor is over one of the lines in your Sub values().
Then click the Green Arrow just above the Code Window, or the Double Arrow just below the Code
Window, or press F5, depending on which version of the VBA Editor you are using, to execute it.

Everything should be fine, and you should see a pop-up Input Window displayed, for the Lower
Value, with the parameters defined in the Sub. Enter a value of say 40 and click OK.

A second pop-up Input Window should now be displayed for the Upper Value. Enter a value of say
60 and click OK.

Everything seems great. And no errors are displayed.


However, the only thing is that the Upper and Lower values have not been processed.
(The Red background is still for any value less than 10, and the green for any value greater than 90)

This is normal, as we have not yet used our parameters in the Sub highlight().
And yup! You’ve guessed it. That’s what we’re going to do now.
(And this should be trivial!)

In the Sub highlight() we are receiving our values into the VBA Variables low and high,
so all we need to do is to use them.

Replace the line:

If Cells(rows, cols) < 10 Then

with:

If Cells(rows, cols) < low Then

And the line:

If Cells(rows, cols) > 90 Then

with:

If Cells(rows, cols) > high Then

Make sure your cursor is over one of the lines in your Sub values().
Then click the Green Arrow just above the Code Window, or the Double Arrow just below the Code
Window, or press F5, depending on which version of the VBA Editor you are using, to execute it.

In the first pop-up Input Window, for the Lower Value, enter a value of say 40 and click OK.
In the second pop-up Input Window, for the Upper Value, enter a value of say 60 and click OK.
This time your values are used to determine the background colour!

Error trapping
Make sure your cursor is over one of the lines in your Sub values().
Then click the Green Arrow just above the Code Window, or the Double Arrow just below the Code
Window, or press F5, depending on which version of the VBA Editor you are using, to execute it.

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 25/32
In the first pop-up Input Window, for the Lower Value, enter a value of say psb and click OK.
This time, your code stops executing with the following error:

Why is this?
Well, we defined the VBA Variable lower as a type Byte.
But unfortunately the data we entered was a type String, and so the VBA code fell over.

This is the most important thing you can get from this VBA course – you need to think like the
computer and imagine every possible scenario…and then code for it!

The solution may seem like a step backwards, but that’s what we need to do!
We’ve restricted the values of the VBA Variable lower to values between 0 and 255.
(This is because we defined it as type Byte)
But we need to widen this in case the user is stupid and enters something else!

So please change the lines:

'Define variables
Dim lower As Byte
Dim upper As Byte

to:

'Define variables
Dim lower As Variant
Dim upper As Variant

This should solve our situation. Please try it out:


Make sure your cursor is over one of the lines in your Sub values().
Click the Green Arrow just above the Code Window, or the Double Arrow just below the Code
Window, or press F5, depending on which version of the VBA Editor you are using, to execute it.

Oh no! The following error message is displayed:

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 26/32
And I cannot argue with the VBA Editor – it is always right!

Because our VBA Variables lower and upper in the Sub values() are now defined as type
Variant, the Sub that receives them must also receive them as type Variant.

I’ve already said that VBA Variables of type Variant are to be avoided if possible.
So let’s create 2 new VBA Variables in the Sub values(), and use these to pass the parameters.
That way, we don’t have to change the Sub highlight() and this can still receive VBA Variables
of type Byte. Where the VBA Variables are defined, add the following 2 lines:

Dim low As Byte


Dim up As Byte

And then use these to call the Sub highlight(), so change the following line:

Call highlight(lower, upper)

to:

Call highlight(low, up)

Execute this Sub highlight() again:


In the first pop-up Input Window, for the Lower Value, enter a value of say psb and click OK.
Great – no error message, and we now move onto the second pop-up.
In this pop-up Input Window, for the Upper Value, enter a value of say ROCKS and click OK.
Excellent! No error messages, and we have finished our script.

The next thing, is to test to see if these values are numeric, and to force these values to be numeric.
And there are some great VBA Functions and statements to do this.

The IsNumeric() Function


Basically, this VBA statement does pretty much what it says.
It will return a value of TRUE if the expression is a valid number.
Otherwise, the expression is not a valid number, and it will return a value of FALSE.

So, the following line will return TRUE:

IsNumeric(1969)

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 27/32
And the following line will return FALSE:

IsNumeric("James")

And this can be combined with a looping construct, which will continue looping until a value of
TRUE is returned, and we know we have a Numeric!

The Do … Loop While statement


This VBA statement will perform one or more lines of code, and then check a condition.
If the condition evaluates to TRUE, the loop will continue.
Once the condition evaluates to FALSE, the loop stops.

Let’s put it all together for a better Sub


That’s all we need to improve our Sub values().

Please change the following line:

lower = InputBox("Please Enter Lower Value", "Low Value")


to:

Do
lower = InputBox("Please Enter Lower Value", "Low Value")
Loop While IsNumeric(lower) = False

And the line:

upper = InputBox("Please Enter Upper Value", "High Value")


to:

Do
upper = InputBox("Please Enter Upper Value","High Value")
Loop While IsNumeric(upper) = False

Basically, if the input is not a numeric value, the Input Box will be redisplayed until the input is a
numeric value. And this will be performed for both the Lower and Upper values!

As we know we have numeric values, we can then assign them to the VBA Variables that we are
passing to the Sub highlight(). So please add the lines:

'Set values
low = lower
up = upper

just before the line:

Call highlight(low, up)

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 28/32
Make sure your cursor is over one of the lines in your Sub values().
Then click the Green Arrow just above the Code Window, or the Double Arrow just below the Code
Window, or press F5, depending on which version of the VBA Editor you are using, to execute it.

In the first pop-up Input Window, for the Lower Value, enter a value of say 40 and click OK.
In the second pop-up Input Window, for the Upper Value, enter a value of say 60 and click OK.
And once again, your values are used to determine the background colour!

Click the Green Arrow just above the Code Window, or the Double Arrow just below the Code
Window, or press F5, depending on which version of the VBA Editor you are using, to execute it.

In the first pop-up Input Window, for the Lower Value, enter a value of say psb and click OK.
This is identified as not being numeric, and so the pop-up Input Window is redisplayed.
Enter a value of say rocks and click OK.
Again, this is non-numeric, and so the pop-up Input Window is redisplayed.
This time enter say 30 and click OK.
At last, all is good!

In the second pop-up Input Window, for the Upper Value, enter a value of say UK and click OK.
This is identified as not being numeric, and so the pop-up Input Window is redisplayed.
This time enter say 80 and click OK.
And again, at last, all is good!

Look at your Excel spreadsheet.


The correct values have been highlighted in green and red!

Can we move from a better Sub to an Ultimate Sub?


There are still 2 things wrong with our Sub, and which we need to code to get an ultimate Sub:

1. We have not coded for when the user presses Cancel

2. We have not coded to check that the Upper Value is greater than the Lower Value

Again, it’s not so much as your technical expertise, but your analytical expertise that is needed!
So, let’s fix these both, so you can impress your future bosses…

The VBA Constant vbNullString


This is a special VBA Constant that denotes a null string.
It is also what to use to see if the user has clicked on Cancel within an Input Box.

Currently, you can click on Cancel as many times as you like, and nothing will happen.
(This is because we are looping until a numeric value is entered)

We therefore need to extend the check, to see if Cancel has been pressed.
If it has (or in other words, if the condition we are using evaluates to TRUE) then do not loop.

So, please change the line:

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 29/32
Loop While IsNumeric(lower) = False

to:

Loop While lower <> vbNullString And IsNumeric(lower) = False

It will now only continue looping while the two conditions evaluate to TRUE.
As soon as one of the conditions evaluates to FALSE, the loop stops.

So, if the user clicks on the button Cancel, the VBA Variable lower will have a value that equals
the VBA Constant vbNullString.

The test lower <> vbNullString will therefore evaluate to FALSE, and the loop will stop.
Nice! That is the first part taken care of.

However, if the user has pressed Cancel, then we don’t want anything else to happen.
The easiest way is to use the Exit Sub Function.

The Exit Sub Function


This is open to abuse, but if used wisely, it’s an excellent Function.
(And it is perfect for our scenario!)

Once the loop is finished, we just need to check the value of the VBA Variable lower.
If this has a value of the VBA Constant vbNullString, then we want to exit the Sub.

Please add the lines:

'Exit if Cancel
If lower = vbNullString Then
Exit Sub
End If

That’s all there is to it!


Try it out - make sure your cursor is over one of the lines in your Sub values().
Then click the Green Arrow just above the Code Window, or the Double Arrow just below the Code
Window, or press F5, depending on which version of the VBA Editor you are using, to execute it.

In the first pop-up Input Window, click Cancel.


Hopefully the VBA stops execution, and nothing is shown.

Again, click the Green Arrow just above the Code Window, or the Double Arrow just below the Code
Window, or press F5, depending on which version of the VBA Editor you are using, to execute it.

In the first pop-up Input Window, enter say psb and click OK.
Great – no error message, and we are still on the first pop-up, for the Lower Value.
Enter say 30 and click OK.
In the second pop-up Input Window, click Cancel.

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 30/32
Uh oh!
Nothing happens!
Well, this is normal - we haven’t coded this part yet!

We need to change the line:

Loop While IsNumeric(upper) = False

to:

Loop While upper <> vbNullString And IsNumeric(upper) = False

And then add the following lines to avoid calling Sub highlight if the user pressed Cancel:

'Exit if Cancel
If upper = vbNullString Then
Exit Sub
End If

Try that out. For me, everything is good!


Ok, we are so close, I can smell it!
Only one thing left to code for the ultimate Sub – make sure that the Upper Value is higher than the
Lower Value. And this will be done just before the end of the Sub!

The GoTo Instruction


Again, this is open to abuse, but if used wisely, it’s an excellent Instruction.
(And it is perfect for our scenario!)

Everything is great.
We have loops for both the Upper Value, and the Lower Value, that will continue while the user has
not pressed Cancel, and if the value is non-numeric.

Once these tests have been passed, the VBA Variables low and up are set to the entered values.
So, all we need to do is to test if the VBA Variable up is less than the VBA Variable low.
If it is, there is an error, so go back, and ask for a new Upper Value.

Please add the following lines just before the call to the Sub highlight():

'Error if up < low


If up < low Then
GoTo upper
End If

Now all that is left, is to define the location upper.

Immediately before the Do … Loop While Statement, add the following single line:

upper:

This puts a "bookmark" into your code, and so the GoTo Instruction know where to go!

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 31/32
User warning with the MsgBox Function
This is very similar to the InputBox Function.
However, instead of accepting parameters, it simply displays a message.

Let’s use it now. After the following line:

If up < low Then

please add:

MsgBox("Error: Upper Value less than Lower Value")

Nice.
We really have an ultimate Sub!

Ultimate? Perhaps! But we can always improve it! Let’s include the values in the messages. Change:

upper = InputBox("Please Enter Upper Value","High Value")

to:

upper = InputBox("Please Enter Upper Value ( >" + lower + ")",


"High Value")

Click the Green Arrow just above the Code Window, or the Double Arrow just below the Code
Window, or press F5, depending on which version of the VBA Editor you are using, to execute it,
and this time the pop-up Input Window includes the lower value.

And change:

MsgBox("Error: Upper Value less than Lower Value")

to:

MsgBox("Error: Upper Value (" + upper +


") less than Lower Value (" + lower + ")"

Again, execute the Sub to see what this gives us.


I find that the more information you give the user, and the more helpful you are, the easier your
programs are to use.

__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 32/32

You might also like