Vous êtes sur la page 1sur 6

Visual Basic for Design Dr. H.

Bock

Project 1 – Getting Started

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.

2. What is Visual Basic?


Visual Basic is a more recent variant of the old BASIC (Beginner's All-purpose Symbolic Instruction Code) that was
developed in 1960s. It is a high-level programming language along with C, C++, FORTRAN, JAVA and many others.
“High-level” means that you don’t have to worry about how the computer does things. You can just type “+” and the
computer will add. In a low-level language e.g. machine code you would have to tell the computer how to add via bit
manipulation. Essentially, high-level language means (relatively) easy to use.
Visual Basic is an “object oriented” language, which means that you can define and then use objects. Objects are
things such as buttons, scroll-down menus, switches, etc. but could also fulfil some more mathematical purpose. This
is very useful if you want to program new software, e.g. for smartphones.
What is perhaps more useful for us, is that VB can be used to program new functions for Excel, which you can call
from a spreadsheet as you call all predefined functions. This allows you to do things that you can not do with the
standard Excel functions. It also allows you to produce cleaner spreadsheets as you can move thinks like
documentation and unit conversion into the VB function.
A word of caution: Excel and VB do not convert units for you, so you have to be disciplined in using the right units
and program their conversion.

2.1 Interpreted Languages and Compiled Code


In some programming languages the commands are INTERPRETED into machine code one at a time while the
computer runs through the commands. That means that the code it is “interpreted” each time you run it. This makes
execution slow, but has the advantage that you can essentially run your source code, that the interpreter can help
you write correct code and that your code “works” on any computer which has the correct interpreter (Microsoft,
Apple, Linux,…). Visual Basic is such a language along side with JAVA, HTML and others.
To produce fast code COMPILATION is better. Code in FORTRAN, C, C++, etc. is generally compiled. Here an
“executable” is produced by compilation of the source code once and then only the “executable” is run. The Excel
program you are using is such an executable. Compilation provides faster software, but the executable will only work
for the specific operating system for which it was compiled – Windows 8 but possibly not for Windows 7.
However, as computers have become very fast the distinction between interpreted and compiled code has become
less clear-cut. For example, the VB code that is used in Excel is partly compiled which allows faster execution.

3. Visual Basic in Excel


VISUAL BASIC is a programming environment that is accessible from Microsoft Office products. Within Excel, VB
exists in two forms: as SUBroutines and as FUNCTIONs. Functions behave very similarly to Excel’s built-in functions
and this is what we will be using in this course.

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.

3.1.1 Setting up a Function


In Excel, select “Visual Basic” on the Developer tab. This brings up the VB editor.

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.

3.1.2 Inserting a New Function Procedure


Now place the cursor in the editor window and start a new function using the INSERT  PROCCEDURE pull down
menu; a window will pop up:

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.

3.1.3 Saving the Spreadsheet


The first time you save the program, you must select “Save As Excel Macro-Enabled Workbook” from the File menu.
Subsequently, you can use the simple SAVE button or the Ctrl+s shortcut.
If you have longer code or if you are “experimenting” you may want to save some versions that work or are otherwise
valuable.
Always keep the code for completed exercises for later reference and for building more complex code on their basis.

3.1.4 Using the Function


You can now use your new function in the same way you would use one of the build-in functions. Go to the
spreadsheet write a number into some cell and in another cell start to write the command to call the new function: ”=
test1”. At this point Excel already recognizes the new function.

4
Visual Basic for Design Dr. H. Bock
Now complete the function call: “= test1(A1)”

and press <Enter>.

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.

3) Computer programs allow us to use operations like


y = y +3
This is not an implicit equation for y! Here the current value of y is added to 3 and the result reassigned to y. Test
operations of this form.

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.

Vous aimerez peut-être aussi