27

Click here to load reader

Excel VBA - Summary

Embed Size (px)

DESCRIPTION

Curso de programación en VB para un caso de ingeniería de yacimientos petroleros. Se programo la ecuación de flujo fracciónal asi como la correlación empíríca de Corey para el calculo de las KR.

Citation preview

Page 1: Excel VBA - Summary

EXCEL VBA TRAINING COURSE WITH RESERVOIR

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.

What is an Excel Macro

Although Excel is a very powerful software, there are going to be times where the built-in capabilities of

excel are not going to be enough to solve some more particular tasks at hand. That’s were the built-in

programming language of Excel Visual Basic for Applications (VBA) comes in, allowing the extension of

the built-in capabilities of Excel, as well as the automatization of repetitive tasks that we are doing over

and over again.

An Excel Macro is a subroutine written in the Visual Basic for Applications (VBA) programming language

for automating tasks and expanding Excel’s capabilities. Macros can be written manually through the

Visual Basic Editor within the Excel environment or through the Macro Recorder which can record the

user’s actions within Excel and translate them automatically into VBA code.

Purpose of VBA

In many engineering occupations the main software you’re 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, that’s 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 that’s 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, that’s 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.

Page 2: Excel VBA - Summary

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, that’s were a high level programming language comes in such as Fortran, C++, or

C#.

// other disadvantage - lack of documentation in equations (Mathcad)

How VBA will be Explained

In this tutorial the minimal theoretical foundation of each aspect of VBA will be explained followed by

hands-on examples, this examples consists on the enhancement of a pre-made excel workbook, with

VBA code. The theme of each workbook used will be about some aspect of reservoir engineering.

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.

Page 3: Excel VBA - Summary

1. User-Defined Functions, Macro Recorder and Form Controls

Introduction

In this section the VBA material that will be covered will be the making of simple functions, the basic

statements of VBA, an introduction to control structures (e.g. If statements) and the message box.

Functions and Subroutines

VBA adds functionality to the Excel environment through Procedures. Procedures can be divided in two

categories: Functions and Subroutines, the difference between the two are how they are invoked, and

their ability to change the working environment.

A Function is a Procedure declared with the Function keyword that can accept passed arguments and

return a value, and can be invoked directly from a worksheet cell. A Function cannot change the

contents or format of any cell.

A Subroutine is a Procedure declared with the Sub keyword that can accept passed arguments, but they

cannot return a value, and cannot be invoked directly from a worksheet cell. But unlike functions they

do can change the contents and form of cells.

So basically a Function is a procedure that you use to calculate things, like the built-in formulas of excel,

for everything else use Subroutines.

Page 4: Excel VBA - Summary

Example: Relative Permeability and Fractional Flow

One set of data fundamental for reservoir simulations is relative permeability data, normally these data

are supplied by laboratory measurements (RCAL), but these measurements are not always available, or

could be useful to compare the results of the laboratory with other data, in such cases empirical

correlations can prove useful. In this section the Corey correlations will be employed to calculate the

relative permeabilities to water and oil in a water wet, oil-water system. The modified Corey

correlations will be programmed in VBA code and added to the excel workbook as functions that can be

called as if they were Excel built-in functions.

Page 5: Excel VBA - Summary

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:

Page 6: Excel VBA - Summary

Now open the Visual Basic Editor in Developer -> Visual Basic:

Page 7: Excel VBA - Summary

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:

Page 8: Excel VBA - Summary

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):

Page 9: Excel VBA - Summary

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.

Write the following equation in the VB Editor:

In VBA code this equation looks like this:

Page 10: Excel VBA - Summary

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

Enabled Workbook, to do this simply click “No”, and select a Macro-Enabled Workbook as the file type:

Page 11: Excel VBA - Summary

Now you can call the newly created function as if it were an Excel built-in function:

Page 12: Excel VBA - Summary

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:

Page 13: Excel VBA - Summary

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:

Page 14: Excel VBA - Summary

If Statement and Message Box Control Form

Writing code that can handle invalid user’s input is one of the most important aspects of programming,

so next we are going to add code that alerts the user if the input data for water saturation is invalid. To

do this, write the following code within the Corey_OilWater_WaterRelPerm() function:

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

Page 15: Excel VBA - Summary

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.

Page 16: Excel VBA - Summary

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.

3. Macro Recorder, Button Form Control

Now that we have calculated the relative permeability data with the Corey correlations, we can

calculate the fractional flow of water that can serve as a parameter for the evaluation of an immiscible

displacement in a waterflooding recovery process.

First we are going to add a button that automatically copies the calculated relative permeability data in

sheet 1 (Relative Permeability) to the sheet 2 (Fractional Flow):

Click on the Fraction Flow sheet to see it:

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:

Page 17: Excel VBA - Summary

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:

Page 18: Excel VBA - Summary

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:

Page 19: Excel VBA - Summary

Your Fractional Flow worksheet should now look like this:

Click on Stop Recording

Page 20: Excel VBA - Summary

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:

Page 21: Excel VBA - Summary

Select the area you want the button to occupy:

An Assign Macro menu will automatically appear when the button is created. Assign it the

“CopyRelPermData” Macro, and click OK:

Page 22: Excel VBA - Summary

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:

Page 23: Excel VBA - Summary

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:

Page 24: Excel VBA - Summary

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 (krw) 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:

Page 25: Excel VBA - Summary

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

Page 26: Excel VBA - Summary

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

Visual Basic IDE (Default)

Insert Module

Save as Excel Macro-Enabled Workbook

List of statements

Option Explicit

Dim

Function, End Function

If, End If

‘ (comments

Worksheets("Factor z múltiple").Range("B2").Value = "= HallYarborough(A2/$E$3, $E$2/$E$4)"

Procedures

Procedures are a set of instructions written

Function (returns value)

Page 27: Excel VBA - Summary

Subroutine (does not return a value)

Macro Recorder (Format, unknown keywords)