Académique Documents
Professionnel Documents
Culture Documents
Bock
1. Introduction
Visual Basic (VB) is a programming language that runs with Microsoft Office products, many others and also stand-
alone. We will use it to improve the functionality of Excel spreadsheets. The key goal is to encourage you to develop
a couple of tools for “standard design tasks”, such as pipe, pump and heat exchanger sizing. We hope that you use
and expand this tool set in the following years.
The second goal is to provide an introduction to programming. This VB introduction should complement the Matlab
course that is part of Math 4.
The course concept is essentially “learning by doing”. We’ll start by developing some small function programs and
then make them more complex and more useful. As we go along we’ll learn elements of the language, some
programming conventions, etc. Vital for “learning buy doing” is the “doing” bit! You need to practice. This will be
mainly “playing”, i.e. trying out how things work and testing variations of the code. With the skills and knowledge
acquired during “playing” you can then produce code that fulfils new tasks.
1
Visual Basic for Design Dr. H. Bock
3.1 Getting Started
We will now set up a VB function within Excel. This first function takes an input variable and doubles it.
If the Developer tab is missing, click File Options. In the new window chose Customize Ribbon and then tick the
Developer check box.
Once you have checked the Developer check box, this setting will be retained when you use Excel in the future. Now
open the editor.
The editor window looks similar to this:
2
Visual Basic for Design Dr. H. Bock
The left part shows the workbook’s contents and any MODULES. Modules are collections of VB routines (subroutines
and functions) in the workbook.
First, we add a new module. Use the INSERT MODULE menu command. The new window, which opens, is the
actual editor window where the program code will be typed. It is similar to a word processor and can be sized and
moved as normal. Don’t worry about the words (General) and (Declarations); these relate to other aspects of
programming.
IMPORTANT: You must use INSERT MODULE before typing any code. If this is not done, then your program will
not run as intended.
IMPORTANT: A common mistake is to insert two modules and then use the same function name twice. This is not
allowed as Excel would not know which function to use. As this error is often hard to track down, better use only one
module.
Select “Function” in the Type part. You must also give the function a name. Here it is “test1”. Function names can
contain letters and numbers, but they cannot use spaces. The first character must be a letter. We leave the Scope
setting at Public for now. Once OK is pressed, the function declaration is automatically inserted in the editor.
The first lines of code inserted by the system “Public Function…” is the function declaration and also demarcates
the beginning of the function code. The “End Function” defines the end of the function. All commands typed in
between these two lines are the function itself.
Now use the editor window like a word processor. Put the cursor at the start of the line and type in a command. Finish
the line by pressing <Enter>. If there is an error, correct the statement, move to the end of the line and press <Enter>
again.
3
Visual Basic for Design Dr. H. Bock
Copy the simple function shown here:
As you finish a line of code and press <Enter>, the system will change the colours of some words (syntax highlighting)
and start commands with a capital letter. These changes indicate that the command line has been understood by the
interpreter/compiler. If it is not understood, then the system will bring up an error box and change the text to RED.
Read the error message carefully and correct the error.
Colours which you will see are:
• GREEN for all comment lines. These lines are used by the programmer to describe what the program
is doing.
• BLACK used for non-command lines which are usually bits of maths.
• BLUE Commands which the system knows about.
• RED Something is incorrect. (It is possible that the problem originates in a line of code different to
the one where the error is detected.)
Note the use of comment and blank lines. These are included to make it easier to navigate and understand the code.
Practice the use of comments! They may seem a lot of unnecessary work, but if you have not used the code for half
a year, you will be very grateful for any help you can get to understand it again.
4
Visual Basic for Design Dr. H. Bock
Now complete the function call: “= test1(A1)”
The function is executed and the result, 6 is written into the cell. The function is still shown in the function line (red
arrow).
As with build-in functions Excel will re-evaluate the function as soon as its input changes. Try it!
3.1.5 Details
Visual Basic is fairly intuitive and you should be able modify the function already. However it makes sense to consider
some details before that.
It makes sense to use function names which make it intuitive to use them. In the present case “double” seems
attractive. But, if you try to type “Public Function double(x)”, you will get an error message. The reason is,
that “Double” is defined and used already, as we shall see. Of course, two functions cannot have the same name
because they need to be distinguishable. However, “multiply_by_2” will work.
The function requires an input parameter. This is specified in the function declaration line: “Public Function
test1(x)” by the x in the parenthesis. It states that exactly one input parameter is required and that its value is
assigned to the variable x within the function code. The variable x can then be used in the function code for any
manipulation we would like. Note that “x” is just one choice for the variable name, we could equally well use “a”, “b”,
“variable1” or “temperature” – whatever is most convenient.
The function name, “test1” is used to call the function from the spreadsheet via the function call “= test1(A1)”. The
value, that is currently in the cell given in the parenthesis, here A1, will be transferred to the function and then
assigned to the variable specified in the function declaration, here x, as described above.
The function name, “test1” it is also the name of the variable whose value is returned to the spreadsheet. Thus, the
result of the function evaluation, i.e. the number that you want to return to the spreadsheet, must be assigned to the
variable with the same name as the function, here test1, inside the function code. We have done this in the line
test1 = 2 * x. If you fail to do this, Excel will return the default value of test1, which should be Zero.
5
Visual Basic for Design Dr. H. Bock
3.1.5 Modifying the Function
You can now modify the function. If you modify the function in the editor, it will not automatically be updated on the
spreadsheet. There are various ways to force a re-evaluation. Unfortunately, many of them seem to be system
dependent. However there are two ways that always work:
1) Retype or modify one of the input parameters and press <Enter>. In the present example that would be the
value in cell A1.
2) Mark the cell with the function call, move the cursor into the function editor line (red arrow in the screenshot
above), click once and press <Enter>.
Now you are ready to play! It is important that you play with functions a bit. Create function for different calculation
tasks, program them and check if they produce the expected result. We’ll soon create functions which can do things
that the standard build-in functions can’t do.
4. Variable Assignment
In computer code the “=” sign has a different meaning compared to mathematical notation. In VB it’s the assignment
operator. It instructs the computer to take what is on the right of the “=” sign (usually a value) and assign it to what is
on the left (usually a variable). Thus test1 = 2 * x instructs the computer to take the value of x, multiply it by 2
and assign the result to the variable test1. Therefore 2 * x = test1 would produce an error.
The first variable assignment is done essentially automatically in the function declaration. However, values can also
be assigned to variables directly:
y = 5
From now on y can be used and its value will be 5.
Variables should never be used without assigning a value first. This is possible and the default value would be used.
In VB the default should be Zero, but it is not impossible that this depends on the system you are using. In other
programming languages, such as C a default value is not assigned at all, so the value of y would be whatever
happens to be in the memory that is assigned to y by the operating system (OS).
Another way to assign values is through a mathematical operation, such as
z = x * y
or
test1 = 2 * x
5. Exercises
1) In many cases our VB functions will require more than one argument. This is easily achieved: In the function
declaration replace test1(x) by test1(x, y). Now, when you call the function from the spreadsheet, you need
to provide two arguments, for example “=test1(A1,A2)”. Now you can use x and y in the calculation, e.g. x + y.
2) A number of arithmetic operators are available in VB. They are all listed and explained in the documentation
provided by Microsoft (Arithmetic Operators). Go through the list and test all operators in your VB function.
4) Design a function that calculates the ideal gas pressure in MPa from the temperature in °C, the volume in m3 and
the number of moles in kmol. Test the code by comparing the result to a calculation you do by hand.