CAPE 3320 & 5330M Advanced/ Reaction Engineering: Executive Summary
CAPE 3320 & 5330M Advanced/ Reaction Engineering: Executive Summary
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
5 2. When Prompted save the file with a new name (make sure its save as an Macro Enabled File .XLSM)
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
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
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.
5
CAPE3320/5330 Visual Basic Tutorial
'
2.1 Analysing Hello world… '
'
Using commands: HELLO WORLD
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
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)
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
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:
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
9
CAPE3320/5330 Visual Basic Tutorial
[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 [….]])
25
10
CAPE3320/5330 Visual Basic Tutorial
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
For a Function and Program Flow Control Cheat Sheet, see the end of this document.
20
12
CAPE3320/5330 Visual Basic Tutorial
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)
2. Click on VBA.
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.
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.
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.
14
CAPE3320/5330 Visual Basic Tutorial
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.
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.
Let SLATE
know you want
the answers
from the arrays
and For Loops
to be scribed.
ScribePlot generates
a graph from the data
provided.
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)
18
CAPE3320/5330 Visual Basic Tutorial
Funcname=Value
End Function
6.4 For more information on VBA code there are numerous resources
available:
19