Professional Documents
Culture Documents
Transcript 1
Transcript 1
Welcome................................................................................................................................................3
Ground rules..........................................................................................................................................3
Introduction...........................................................................................................................................3
What is VBA?..........................................................................................................................................4
Terminology...........................................................................................................................................5
1. Creating a Module......................................................................................................................6
3. Creating a Sub.............................................................................................................................6
4. Running a Sub.............................................................................................................................6
Debugging a Sub...................................................................................................................................10
__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 1/32
VBA Variable naming rules...................................................................................................................14
VBA Comments.....................................................................................................................................15
Error trapping.......................................................................................................................................25
__________________________________________________________________________________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.
__________________________________________________________________________________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.
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.
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.
__________________________________________________________________________________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.
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:
2. Double click PSB in the Module list, within the Project Window
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!
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:
And at the end, the VBA Variable text contains the value entered in the Input Box.
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.
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.
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
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.
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
__________________________________________________________________________________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.
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.
__________________________________________________________________________________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!)
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:
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!
Option Explicit
So, from now on, all of your VBA Variables must be defined in this entire Module.
__________________________________________________________________________________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)
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)
Sub mySecondSub()
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!
Sub myThirdSub()
__________________________________________________________________________________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:
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!
There are some rules to follow for the choice of your VBA Variable names:
Names cannot be VBA Reserved Words (for example, Sub, Dim, Next, and For)
__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 14/32
But apart from that, they can be pretty much anything you want!
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, …)
Boolean -1 or 0
Byte 0 to 255
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!
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.
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
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
Select all of the lines, and press CTRL + C to copy, then CTRL + V to paste.
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.
__________________________________________________________________________________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.
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.
Note: The possible maximum values for the 2 VBA Variable types are:
Byte 0 to 255
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.
__________________________________________________________________________________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.
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)
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
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.
__________________________________________________________________________________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:
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)
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)
to:
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)
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:
to:
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
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
…
__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 21/32
Else
…
code_else
…
End If
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:
The goal here is to inspect the value of every cell, and to do 1 or 3 things:
The first bit is easy – we introduce the If … Then statement, and the condition to evaluate:
Next, we need to test another condition, so we must use the ElseIF statement:
__________________________________________________________________________________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:
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:
The goal here is to create a new Sub, which will accept 2 values from the user:
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!
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:
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.
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.
with:
with:
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!
'Define variables
Dim lower As Byte
Dim upper As Byte
to:
'Define variables
Dim lower As Variant
Dim upper As Variant
__________________________________________________________________________________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:
And then use these to call the Sub highlight(), so change the following line:
to:
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.
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!
Do
lower = InputBox("Please Enter Lower Value", "Low Value")
Loop While IsNumeric(lower) = False
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
__________________________________________________________________________________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!
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…
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.
__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 29/32
Loop While IsNumeric(lower) = False
to:
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.
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.
'Exit if Cancel
If lower = vbNullString Then
Exit Sub
End If
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!
to:
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
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():
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.
please add:
Nice.
We really have an ultimate Sub!
Ultimate? Perhaps! But we can always improve it! Let’s include the values in the messages. Change:
to:
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:
to:
__________________________________________________________________________________I
BBA Introduction to Programming Transcript 1 Page 32/32