0% found this document useful (0 votes)
100 views19 pages

CAPE 3320 & 5330M Advanced/ Reaction Engineering: Executive Summary

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views19 pages

CAPE 3320 & 5330M Advanced/ Reaction Engineering: Executive Summary

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

CAPE3320/5330 Visual Basic Tutorial

CAPE 3320 & 5330M


Advanced/ Reaction Engineering

5
Executive summary
This tutorial aims to support user programming for Reaction Engineers. It explains the basic rules of Microsoft
Office’s Visual Basic for Applications, VBA. An Excel template is provided containing a number of accessible
programming and interface tools to seamlessly integrate programming with the powerful excel user interface.

10Note:
- Text in italics refers to names you can give to functions variables etc and
- [text] in square brackets is optional (you don’t need to have this in your code, but you can!)
- [….] indicates you can repeat the previous syntax as many times as you like

15

20

Frans L. Muller
25Professor of Chemical Process Engineering
School of Process, Environmental & Materials Engineering,
University of Leeds LEEDS, LS2 9JT, UK
Email: [email protected]

30
© Frans Muller, University of Leeds 2018
Copyright Statement
The University of Leeds grants permission for the use of this material as part of the SCAPE Module CAPE
5330M. The express permission of the copyright holder must be obtained for any other use of this material.
1
CAPE3320/5330 Visual Basic Tutorial

2
CAPE3320/5330 Visual Basic Tutorial

1 FIRST STEPS VBA


Follow the steps below to generate your “HelloWorld” program.
1. Open Slate.xltm

5 2. When Prompted save the file with a new name (make sure its save as an Macro Enabled File .XLSM)

3. Go to: File > Options > Customize Ribbon

4. Tick the “Developer tab” and click OK


10
5. Close the option dialog, and click on the Developer Tab, and then the visual basic editor.

6. The Visual Basic Editor (VBE) window should now be visible.

3
CAPE3320/5330 Visual Basic Tutorial

7. The Project area holds the Excel sheets and the Modules (where the code is stored, see figure below).

8. The MyCode Module can be used for a coding test area. Do not change the SLATE module, as proper working
of the SLATE depends on it….
5

9. Type the code into the MyCode module (Accurately, including apostrophes!!)
double click on the CodeModule name to open it in the editor

10 10. Apostrophes in VBA are used to add comments, with any line of text next to an apostrophe not being included
in the code itself.

15

4
CAPE3320/5330 Visual Basic Tutorial

2 SLATE
To help with the training, its important that its
understood how the process modelling is done, this
starts with the fundamentals of numerical methods.
5
This excel VBA tool is written to help with
understanding the key concepts in Process
modelling. You will be programming using the
SLATE Excel Tool. SLATE is a purpose build
10training tool that integrates VBA code and easy
access to the powerful Excel Graphic User Interface
(GUI)

In this section we will use SLATE to explain the basic concepts in VBA coding, before we move on
15to the numerical concepts

Basic Slate principles:


1. The grey area on a worksheet is generated by entering “SLATE” in an appropriate cell

20 2. The area below and on the right of the “SLATE” cell is used by your programs to print text and display data
(NOTE it will regular be deleted and updated so don’t enter information in the grey area!)

3. The slate is removed by entering “#noSlate” in a cell (all output will be removed)

25 4. Cells with “# subroutineName” allow you to run the code by right clicking
try this in the example in the Code sheet

5. Type “wipe” in any cell, and the slate will be emptied


(Double clicking the word SLATE does the same)

6. Just below the word SLATE is the SLATE.State. This is a content area that feeds
back the status of the slate. If you click several cells you should see one or more
periods appear, this means the system is responding well.

35 7. If all fails, and the system does not respond,


Press the stop button in the VBA code editer, select the excel sheet and press “CTRL+r” to restart the SLATE
engine

5
CAPE3320/5330 Visual Basic Tutorial

'
2.1 Analysing Hello world… '
'
Using commands: HELLO WORLD

' A command is defined by a subroutine without parameters


After running the “# Hello world” command ' e.g sub HelloWorld()

by Right clicking it, have a look at the code. '


' Entering "#HelloWorld" in a cell will run the command named after "#",
This is located at the top of the Tutorial ' so here "HelloWorld" (do not enter the aphostrophes!)

5Module ' Command Examples


' type: "#HelloWorld" in a cell and look at the text in the Slate
a) This program is a Subroutine - a bit of code
Sub HelloWorld()
that runs one or more commands. Each sub SlateWipe
ScribeLn 'empty line
must have a unique name consisting of only Scribe "Hello World"
Scribe "Hello", "World"
characters. ScribeLn "Hello World"
10
ScribeLn 1, 2, 3, "Hello World" '3 filled cels on this row, move to beginning of next row
Sub SubName() Scribe 11, 12, 13, "Hello World" 'text on a row, moving to the next cell
ScribeLn 23, 24, 25 'text on the previous row, but moving to the beginning of the next line
Code Scribe "this is", "the end", "good bye"
[Exit Sub] End Sub

Code 'type "Wipe" in a cell to clear the slate

15 End Sub

Good names refer to the purpose of the sub… Use word capitalisation if more than one word are part of the
name. e.g. HelloWorld, not helloworld or HELLOWORLD

20 b) SlateWipe command - Clears the slate

c) Scribe command - Writes text or values onto the SLATE, and moves to the next cell on the same row. Several
items can be added separated by a comma; they end up in adjacent cells

25 d) ScribeLn command - Enters the text and values on adjacent cells, and then moves to the first cell on the row
below (like pressing “ENTER” in word)

e) End Sub tells VBA that the routine is finished

302.2 Your First Program…


Now it’s your turn. Let’s write your name in a cell. In analogy on the HelloWorld Program, write a
program named after your surname, and make it greet you on the Slate using Scribe and
ScribeLn to print some text on the slate in a number of ways

35When coding, you need to play around to find out what works and what does not. You can’t break
the system, and errors will be coming your way, there is no shame in that! Trial and error, just like
development!

TIP: Copy the HelloWorld code to the MyCode module and modify it
40
For a SLATE Cheat Sheet, see the end of this document.

6
CAPE3320/5330 Visual Basic Tutorial

2.3 Variables
When coding, variables are used to store information like numbers and text. To use a variable you
must declare it using ‘Dim’ (short for dimension)
Let’s adapt your name program to retrieve the name from the Slate.
5
1. Generate code similar to the box
2. Clear the MyCode sheet
3. Enter “Name” in a cell, and enter your first name in the
adjacent cell.
10 4. Below “Name” enter “Ntimes” and put an integer value
(say 4) in the adjacent cell.
5. Activate SLATE if not already there
(enter SLATE somewhere)

15
2.3.1 Analysis
a) Dim stands for dimension and tells VBA that a variable is required, and how much memory is needed for that
variable

20 b) Use a colon “:” to continue with multiple statements on a row e.g

Dim Name ‘is the first statement it declares a variable; after the colon (“:”) the second statement:
Name=getval(“name”,”you”) ‘ retrieves a value from the excel sheet from the cell next to “name”
‘ the second value, “You”, passed to the getval function is the default value
25 c) Assign a value to a variable
GetVal retrieves the value associated with the text from the Excel activesheet (use unique names…)

d) For i=1 to Ntimes repeats all subsequent statements, till the line with Next
Each iteration the variable “i” is increased by 1 until “i” is equal to the value of variable “Ntimes”
30 Convention is to indent the statements between FOR and NEXT

e) In this case the two ScribeLn statements are executed a number of times, Greeting you a number of times…

35For a VBA Variables Cheat Sheet, see the end of this document.

7
CAPE3320/5330 Visual Basic Tutorial

3 FUNCTIONS
So far, Subroutines have helped to automate activities (like repeatedly greeting yourself!) this is
very useful, but at times you may want to automate the calculation of a value. Functions are used
to do this. Some common Functions found in Excel are: “SUM”, “SQRT”, “PI”, etc.
5Let’s generate a simple function describing the evolution of time of a First order reaction:

C t
dC dC dC
=−k C → =−k dt → ∫ =∫ −k dt
dt C C=C C 0 o

1
This can be solved with ∫ x dx=ln ⁡(x ):
C
dC C −kt
∫ =ln ( C ) −ln ( C o )=−kt → =e
C=C o C Co
10To help generate “clean” spreadsheets, it’s
often easiest to generate a function for
complex tasks
Try to understand this code and how it
generates results.
15
3.1.1 Analysis
a) Functions are defined by the keyword:

Function FuncName([Prm][, pm2][…]) [as String/Integer/Long/Double/Boolean]


20 [FuncName=ReturnValue1]
[Exit Function]
CODE
[FuncName=ReturnValue2]
End Function
25
b) Note the conditional “IF” “THEN” [ELSEIF] [ELSE] “End If” statement to determine the time
c) You can use the function directly in Excel, just like any other function!

Note:
30 - Text in italics refers to names you can give to functions variables etc and
- [text] in square brackets is optional (you don’t need to have this in your code, but you can!)
- [….] indicates you can repeat the previous syntax as many times as you like
3.1.2 Exercise
1. Implement the code and add the text to the MyCode sheet
35 2. Enter the Variable-Value pairs in Excel
a. NOTE the Formulatext function
3. Test the performance of the code
a. What happens when you change t
b. What happens when you change K
8
CAPE3320/5330 Visual Basic Tutorial

4. Improve the code so that the behaviour with respect to K improves

9
CAPE3320/5330 Visual Basic Tutorial

3.2 Program Flow Structures: For next loops


The flow of a program can be changed from being linear (one statement after the next, to
conditional steps and repeated steps

53.3 Conditional Statements


Here the next statement is determined by the evaluation of an expression. If the expression is true,
once set of statements occurs, else the other set is run. Such code structures are named IF-Then
Statements:
IF Then Else Statement
[If BooleanExpression then THE IF THEN ELSE Structure (conditional code)
If the expression above is True,
[statements A]
then statements A will be executed
[Elseif BooleanExpression then If not, then
If the expression above is True,
[statements B] ]
then statements B will be executed
[Else If not, then
. [statements C] ] then these statements will be executed
End If] This is the end of the if statement

[Exit Function/Sub] Break the conditional flow by the function or subroutine altogether

10A Boolean expression is an expression that returns the result True or False. Eg.:
 3<2
 Param1>param2
 BooleanParam=true
 Prm <> “test”
15  [Not] (Varname [=/</>/<> Varname [….]])

A Boolean expression is thus easily seen as a comparison of non-boolean variables. However, an


expression can also be defined from Boolean sub elements: e.g. an expression that is a
combination of Boolean variables or Boolean expressions:
20:
[Not] BooleanVarname/BooleanExperssion [And/Or/Not/Xor BooleanVarname/BooleanExperssion) [….]]
 Brackets can be used to ensure an expression is evaluated
 The operator NOT has priority over AND

25

10
CAPE3320/5330 Visual Basic Tutorial

3.4 Repetition and iteration: the For Next Loop


Whereas the If-Then-Else statement selects which statements to choose, at times we may want to
repeat an action a number of times, for instance we may want to generate the values of a
concentration profile at ten different times.

THE FOR LOOP:


IvarName Is a variable that will range between I1 and I2 with an
[For IvarName = I1 to I2 [Step i3]
increment/step size of I3 (default for I3=1). I1, I2 and I3 are three
integers.
Any statement, usually there is an effect of I
[Statements]
increasing/decreasing, e.g: t=(i-1)*dt
Break the loop by leaving to the first cell after Next, or leaving the
[Exit Function/Sub/For]
function all together
Next]
5
3.5 FOR Loop Example '
' Subroutines/Pocedures
The Concentration Profile code adjacent applies '
' these are used to excecute a series of tasks
to a first order reaction ' we are calculating many things, or want to automate a task
'
Study the code and you see a program that ' for instance here we plt a concentration profile, and generate a graph
10combines various elements discussed above
Sub ConcProfile()
3.5.1 ANALYSIS 'identify your output!

a) Initial lines print text to inform us of the nature of 'declare the variables (this prevents typo's not being spotted!)
the output Dim k, Co, t, i, c
k = Getval("k", 0.03) '1/s
Co = Getval("Co", 1.2) 'M
15 b) Values for K and Co are retrieved from the
MyCode worksheet SlateWipe
ScribeLn
ScribeLn "# ConcProfile"
c) Headers of a table are written using the ScribeLn ScribeLn
ScribeLn "k", k, "1/s"
command ScribeLn "Co", Co, "M"
ScribeLn
d) A table of Concentration vs time is generated
'generate output
with a For Loop ScribeLn "t", "C"
ScribeLn "s", "M"
e) The command ScribePlot retrieves the data and For i = 0 To 10
t = i / 10 * 60 's
25 uses it to generate a chart c = Co * Exp(-k * t)
ScribeLn t, c
Next
ScribePlot
SlateState = "ConceProfile done"
End Sub

11
CAPE3320/5330 Visual Basic Tutorial

3.6 Exercise: Reaction Profile


Using the information in Levenspiel chapter 3 page 54 generate a table for the Reaction
1
A → R → S k 1=0.03 ∧k 2=0.003
s
To do this generate a subroutine that constructs a table with columns for time, A,R and S and then
5generate a plot of that data using the ScribePlot function

3.7 Exercise: Vessel Volume tool


Write a program that informs the user of the volume in vessels with a rounded bottom.

10 1) Have most variables that are infrequently changed accessed by GetVal


2) Use conditional statements to select between different standards and bottom types (e.g DIN, AASTM, flat,
toroidal)
3) Generate a function that responds to changes in Height z
4) Generate a subroutine that uses the function to generate a table of Volume versus Height, and a plot
15

For a Function and Program Flow Control Cheat Sheet, see the end of this document.
20

12
CAPE3320/5330 Visual Basic Tutorial

4 VBA LANGUAGE REFERENCE HIGHLIGHTS

4.1 Debugging
Use the customise functionality (Right click on the tool bar in
5VBA and click “Customize”). Add the following tools by
dragging and dropping them into the tool bar from the
“Commands” window.
 Last Position (in View)
 Definition (in View)
10  Set next statement (in Debug)
 Compile (in Debug)
 Step into/over/out/run to cursor (all in Debug)
 Add Watch (in Debug)
Learn to use break points to inspect code as it is
15being run (the brown lines that apear when you
click in the grey edge)

4.2 The object Browser


1. From within a macro module, press the F2 key.
20 This will bring up the “Object Browser”.

In the top left you will see a drop-down box which


says “All Libraries”. Click on the down arrow at the
right of this line. You will see a dropdown list with,
at a, “VBA” and “Excel” and other entries
25 representing open Files and libraries

2. Click on VBA.

a In the “Classes” list, click on “Math”.

b To the right, in the “Members of Math” box, you now have a list of all the math functions
which are available in VBA. Note that “log” is included in this list, but not “ln” or
30 “NormSDist”. If you right-click on “log” and then click on “help”, you will see that “log”
returns the natural logarithm.

c Move back to the top left box which now says “VBA”. Click on the down arrow at the right of
this line.

3. Click on VBAPoject.

35 4. In the “Objects/Modules” list, click on “WorksheetFunction”

13
CAPE3320/5330 Visual Basic Tutorial

5 MORE EXAMPLES

In this section more examples will be given relating to reaction engineering topics. Some will show
5you how to form solutions using the VBA SLATE tool, but others will prompt you to try and solve
the problems yourself using SLATE. Don’t worry if you can’t answers these questions initially, some
of the topics will be covered later on in this module.

5.1 Reaction Rate


10This example shows a simple solution for determining the rate of reaction in a CSTR using the VBA
Slate tool.

Study the code and outputs (shown below) and try and follow how the answers were determined as
well as how the code is written to generate the answers using Slate.
15 List every variable that you
will require to answer the
question.

Get all the information


given to you in the
question down.

Write each equation


you need to answer the
question.

Now get SLATE to Scribe


your outputs.

14
CAPE3320/5330 Visual Basic Tutorial

5.2 Plug Flow Reactor


Have a go at creating your own VBA Slate solution for the following question, using the Slate.xlsm
sheet. The answer is provided below, so use this information to help you write your own code.
5

You can go one step further and write your own function for this problem and get it to print multiple
10times with different reactor sizes.

5.3 Rate Equation


This example will show you how to use the VBA Slate tool to generate an answer to a reaction
engineering question. This is particularly useful in cases like the following example as it will have
15you a lot of time and effort in getting to the correct answer.

15
CAPE3320/5330 Visual Basic Tutorial

Study the code and outputs (shown below) and try and follow how the answers were determined as
well as how the code is written to generate the answers using Slate.

Setting arrays with values of


zero lets SLATE know these
values need to be calculated.

The For loops


Arrays let you plot data
provide the
from tables.
information for
calculating
variables set in the
arrays.

Let SLATE
know you want
the answers
from the arrays
and For Loops
to be scribed.

ScribePlot generates
a graph from the data
provided.

55.4 Packed Bed Reactor Example (Advanced Reaction Engineering Students)

Have a go at creating your own VBA Slate solution for the following question, using the Slate.xlsm
sheet. Think about how the weight of catalyst could be estimated from analytical integration of a
performance equation:
10

16
CAPE3320/5330 Visual Basic Tutorial

Study the effect different concentrations have on the weight of catalyst required.

10

15

20

25

30

6 CHEAT SHEETS
35
6.1 SLATE Cheat sheet
Notation
1. Bold text are VBA/Tool key words.
11. Square brackets [ ] indicate optional code elements
40 12. […] means the previous optional element can be repeated many times
13. Italic text refers to usernames for code elements (like variables and subroutine and function names
14. “prm” means parameter

The SLATE
SlateWipe ‘This clears the Slate

17
CAPE3320/5330 Visual Basic Tutorial

Scribe [pm1[, prm2[,…]]] Write text output to the slateScribe; the parameters will be printed cell by cell
ScribeLn [pm1[, prm2[,…]]] Same as scribe, but the next text to be written will start in column 1
‘To have a smooth user experience, Scribbles are saved to a buffer,
Scribe2Slate ‘This command forces the buffer to be emptied on the slate
(become visible to the user)

‘If possible, retrieves the value from the Active Sheet


Dim VarName
‘ If a cell containing the text Varname is found, the value next to it will be
VarName =GetVal(“Varname”,Default)
retrieved
‘To generate a plot, write two or more columns of values
ScribePlot
using ScibeLn than plot them using the ScribePlot command

6.2 VBA Cheatsheet - Variables


VB
Variables Cheat Sheet
A

The Dim statement “declares” a variable; this means that VBA


Dim Varname [as
knows what this word means, and the kind of data it has:
String/Integer/Long/Double/Boolean]
String text characters
Integer a integer number (<232)
Long a very Large integer number
(<264)
Double a real number
Boolean binary data, True or False
Variant or No “as” statement means the variable
can contain any data type

‘If possible, retrieves the value from the Active Sheet


Dim VarName
‘If a cell is found, the value next to it will be retrieved
VarName =GetVal(“Varname”,Default)
‘If no cell is found, the Default value will be returned

A statement (a bit of code) is normally a single line of code


Statement : [Statement [:…]] Using a colon, you can combine several statements on a
single line

6.3 VBA Cheatsheet – Function and Program Flow Control


VB
Variables Cheat Sheet
A
Function FuncName ([Pm1 [, Prm2 [,…]]]) FuncName is typically a meaningful name that describe the
[as value returned by the function, e.g. Average or Sum, not
String/Integer/Long/Double/Boolean/Varia Prawn or Jane
nt] Its good practice to capitalise the first letter, and the starting
letters of nouns embedded in the name: e.g SumOfCosts
Vba formats the text entered in the same way as the
declaration, so it is easy to spot if the name is miss typed.

The parameters PRm1,Prm2 etc represent variables that are

18
CAPE3320/5330 Visual Basic Tutorial

passed to the function, If called from Excel, a change in


parameter will cause the function to be recalculated
[Statements] Any number of statements

[If BooleanExpression then THE IF THEN ELSE Structure (conditional code)


If the expression above is True,
[statements A]
then statements A will be executed
[Elseif BooleanExpression then If not, then
If the expression above is True,
[statements B] ]
then statements B will be executed
[Else If not, then
. [statementsC] ] then these statements will be executed
End If] This is the end of the if statement

[For IvarName = I1 to I3 [step i4] THE FOR LOOP


[Statements]
Next]

Funcname=Value
End Function

6.4 For more information on VBA code there are numerous resources
available:

 Use online tutorials like https://www.excel-easy.com/vba.html


5  There are many books. One useful one is Excel VBA Programming For Dummies 3 rd Edition,
with the pdf available online.
 Lots of online forums that answer specific questions. You can find solved solutions to related
problems by this route.
 YouTube has many video tutorials that show you how to use VBA, with some channels
10 providing an entire overview, from the basics to the advanced.

Find whatever works best for you!

19

You might also like