Vous êtes sur la page 1sur 6

EPS Chemical Engineering

Visual Basic for Chemical Engineers

B48BE2

VISUAL BASIC PROGRAMMING from EXCEL


Part 1 Getting Started
Contents

1. Introduction
2. What is Visual Basic?
2.1 Interpreted Languages and Compiled Code
3. Visual Basic in Excel
3.1 Getting Started

1
1
1
2
2

3.1.1 Setting up a Subprogram


3.1.2 Inserting a New Procedure
3.1.3 Saving the Spreadsheet
3.1.4 Using the Function
3.1.5 Details
3.1.5 Modifying the Function

4.
5.

2
3
4
5
5
6

Variable Assignment
Exercises

6
6

1. Introduction
Visual Basic (VB) is a programming language that runs with Microsoft Office products, many others and also standalone. 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. Well start by developing some small function programs and
then make them more complex and more useful. As we go along well 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 dont 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
1

EPS Chemical Engineering

Visual Basic for Chemical Engineers

B48BE2

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 Excels built-in
functions and this is what we will be using in this course.

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 VB 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.

EPS Chemical Engineering

Visual Basic for Chemical Engineers

B48BE2

Once you have checked the Developer check box, this setting will be retained when you use Excel in future. Now
open the editor.
The editor window has two parts:

The left part shows the workbooks 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
where program code will be typed. It is similar to a word processor and can be sized and moved as normal. Dont
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 the use the same function name twice. This is not
allowed as Excel would not know which function to use. This error is also often hard to track down.

3.1.2 Inserting a New Function Procedure


Now 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.

EPS Chemical Engineering

Visual Basic for Chemical Engineers

B48BE2

The first lines of code put in 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 Module 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.

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. 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.

EPS Chemical Engineering

Visual Basic for Chemical Engineers

B48BE2

3.1.4 Using the Function


You can now use this function as a normal build-in function. 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.

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 function code for any
manipulation we would like.
5

EPS Chemical Engineering

Visual Basic for Chemical Engineers

B48BE2

The function name, test1 is used to call the function from the spreadsheet and 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, i.e.
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.

3.1.5 Modifying the Function


You can now modify the function. If you modify the function in the module 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. Well soon create functions which can do
things that the standard build-in functions cant do.

4. Variable Assignment
In computer code the = sign has a different meaning compared to mathematical notation. In VB its 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 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.
6

Vous aimerez peut-être aussi