Excel VBA - Summary
Excel VBA - Summary
ENGINEERING APPLICATIONS
Meza Puente Victor Enrique
Introduction
This course
About Excel
Excel is one of the most used software for general engineering applications. The fundamentals of excel:
formulas, formatting and charting, can be used to solve a lot of common tasks encountered on the job.
This is why Excel is a general-purpose engineering software every engineer should learn.
Purpose of VBA
In many engineering occupations the main software youre going to use is specialized software (e.g.
CMG Suite), but there are going to be occasions were the specialized software cannot perform
something very particular you need, thats were Excel-VBA comes in, Excel has its own programming
language (VBA) that allows the modification of the Excel environment to suit a particular need, unlike
high level programming languages (e.g. Fortran, C++, C#), Excel has already a built-in interface, and this
allows a much quicker development of solutions than starting from scratch with a high level
programming language, so thats the main advantage of using Excel-VBA, the quick development of the
interface for custom solutions, on the other hand the main disadvantages of VBA, are that Excel VBA is
not well suited for numeric-intensive calculations, especially calculations involving matrixes, thats were
Matlab excels (Matlab stands for Matrix Laboratory), which supports interoperability with Excel, in this
way, it is possible do develop custom solutions with a quick developed interface, and with code that
supports numeric-intensive calculations.
The other main disadvantage of Excel-VBA is that VBA is not as flexible and powerful as a high-level
programming language, so when the capabilities of Excel-VBA have been reached and the problem has
not yet been solved, thats were a high level programming language comes in such as Fortran, C++, or
C#.
// other disadvantage - lack of documentation in equations (Mathcad)
Requirements
To follow the material presented here, a notion of the basic elements of excel is required, which include:
the use of formulas, formatting of cells, and charting.
Also a basic notion of the fundamentals of reservoir engineering is desirable but not indispensable, as
long as the user has a strong background on mathematics and physics.
Begin by opening The Excel Workbook Relative Permeability Fractional Flow (Exercise):
First enable the Visual Basic Editor. By default the Visual Basic Editor is disabled, you have to enable it by
checking the Developer checkbox in File -> Options -> Customize Ribbon -> Main Tabs:
Now open the Visual Basic Editor in Developer -> Visual Basic:
Next we are going to insert a Module in which the VBA code will be written by right clicking on the
current workbook and selecting Insert -> Module:
Now that we have our default Module1 we can write VBA code in it. Create the function we are going
to use by writing the keyword Function next to the name we want the function to have, in this case
Corey_WaterOil_WaterRelPerm, the name of the function has to end with parenthesis, then press
Enter, and the keywords End Function will be automatically added:
Within the parenthesis we have to write the arguments our function is going to use, in this case the
water curve point (k_rw_Sorw), the water saturation (S_w), the initial water saturation (S_wi), the
residual oil saturation to water (S_orw), and the Corey exponent (N):
We have also to declare every variable we are going to use that is not an argument of the function, in
this case the result of the function, which is the relative permeability to water (krw):
To make sure the Visual Basic Editor requires every variable to be declared, and highlights as an error
any undeclared variable, make sure to write the keywords Option Explicit at the top of the Editor.
Developing this habit will help stop some very hard-to-find errors from creeping in.
Now that the value k_rw is calculated we have to return its value to the function, in VBA this is done by
assigning the name of the function to the value we want it to return, this is done by writing the
following:
It is a good-programming practice to write comments that explain what your code does, in this case we
are going to just add a short description just above the Function keyword, in VBA, comments are written
using the keyword (apostrophe), your code should look like this:
Finally Save the function by clicking the save icon, or File -> Save. When you click save a warning
message will appear telling you that the workbook with the macro can only be saved on a MacroEnabled Workbook, to do this simply click No, and select a Macro-Enabled Workbook as the file type:
Now you can call the newly created function as if it were an Excel built-in function:
Enter the function, assign the corresponding arguments, and calculate the relative permeability for the
first row of the relative permeability to water (krw) column. Make sure to assign the arguments in the
same exact order as defined in the previously defined function, also use absolute reference for all
arguments except D6 (water saturation, Sw):
To calculate the rest of the values simply click on the autofill corner handle of the current cell and drag it
to the cell E18:
In the same way, now write a function for the other Corey correlation, the one that calculates the
relative permeability to oil.
And drag the handle to calculate all the values of the column:
A basic If Statement consists of the keywords If followed by the condition that is to be evaluated, in
this case if the water saturation (S_w) is less that the initial water saturation (S_wi), followed by the
keyword Then, and the code that is going to be executed if the condition to be evaluated is true, and
finishes with the keyword End If.
If [condition] Then
[code to be executed if condition is true]
End If
Message Box
In this case the code to be executed if the condition is true is the display of a message box control form
that alerts the user of invalid input.
A basic message box has three arguments: the message to be displayed, the buttons that the message
box is going to have, and the title of the message box, in VBA code this is indicated with the following
statements:
Message
Between quotes the message of the message box is written first, in this case The Water Saturation
cannot be less than the initial Water Saturation
Buttons
Following the message the buttons the message box is going to have is indicated with keywords, in this
case vbOKOnly which indicates that only the OK button is going to appear on the message box.
Title
After the type of button has been indicated, the title of the message box can be written between
quotes, in this case Error!
Note that the arguments of the message box are separated with commas. Also note that within the code
written for the message box there is an underscore (_), this symbol is used to indicate the editor that
the code of the current statement will be continued on the next line.
2. Subroutines
Up until now we have only used functions, which are a fundamental part of VBA but are very limited in
their manipulation of the elements of the spreadsheet, that because functions are designed to receive
input, do calculations with that input and return an output. If we want more manipulation of the
elements of the spreadsheet we have to use subroutines.
Next we are going to use the macro recorder to make a macro from the actions we do in the workbook,
to do this click on the Developer tab and then on the Record Macro button:
And give the Macro the name of CopyRelPermData, then click OK:
Now click on the Relative Permeability sheet, select the relative permeability data, right-click, select
copy, select the Fractional Flow tab, click on the cell E4, and select paste values:
Note: If you start to record this Macro when you are displaying sheet 1 (Relative Permeability) it is still
important to click the on the name of the sheet at the bottom (sheet tab), so the recorder knows it has
to copy the cells of this specific worksheet:
Now open the Visual Basic Editor click on Module 2 and check out the VBA code the Macro Recorder
automatically generated from your actions in the workbook:
Next we are going to assign this Macro to a button, to do this, on the Developer tab select Insert ->
Form Controls > Button:
An Assign Macro menu will automatically appear when the button is created. Assign it the
CopyRelPermData Macro, and click OK:
You can edit the text that appears in the button by selecting the text and writing over it:
Now test the button by erasing the relative permeability data in the Fractional Flow worksheet, and
clicking on the newly created button, the relative permeability data should appear again in the
Fractional Flow worksheet:
Now that we have copied the relative permeability data to this worksheet, we can calculate the
fractional flow with these data, to do this create a new function in Module1 with the following equation:
Call this function in the Fractional Flow worksheet and drag it:
Note that in the first row of the fractional flow column it appears an error, this is because at this row the
relative permeability to water (krw) has a value of zero which causes the fractional flow equation to be
divided by zero, to correct this, open the Visual Basic Editor and add an If statement that tells the
function to assign a value of zero to the fractional flow if the relative permeability to water (k rw) equals
zero, additionally in any other case where the krw does not equal zero tell the function to use the normal
equation to calculate the fractional flow, which is done by using the Else statement, in VBA code these
instructions would look like this:
Now recalculate the cell where the error appears, drag it again, and all values of the column should be
error-free:
Review If Statement
Review CopyRelPermData Code
Conclusion
Essential tools to develop from basic to intermediate engineering worksheets
Advanced matrix manipulation with matlab
Summary
Homework
Try to continue to develop the exercise workbook until it looks like the Solved workbook
Procedures
Procedures are a set of instructions written
Function (returns value)