0% found this document useful (0 votes)
341 views29 pages

Excel VBA Programming for Engineers

This document provides an introduction to programming in VBA for automating Excel. It discusses key programming concepts like types, functions, control structures, and introduces an example for calculating pseudopressure using the trapezoidal rule for numerical integration. Interactive examples are provided for defining a pseudopressure function in VBA and calling it from Excel.

Uploaded by

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

Excel VBA Programming for Engineers

This document provides an introduction to programming in VBA for automating Excel. It discusses key programming concepts like types, functions, control structures, and introduces an example for calculating pseudopressure using the trapezoidal rule for numerical integration. Interactive examples are provided for defining a pseudopressure function in VBA and calling it from Excel.

Uploaded by

Ken Ng
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Programming for Engineers

Excel Automation with VBA


Session 1: “Eat Your Vegetables”

Derrick W. Turk
terminus data science, LLC
Thanks for filling out the survey!
Where are you from? [ Houston, TX ] Have you programmed before? [ Yes ]
Where do you live and work now? [ Houston, TX ] For how long? [ 18 years ]
Gender: [ M ] Languages: (limited) assembly, C, C++, C#, Excel
formulas, (limited) Haskell, Java, Javascript, Lisp,
Age: [ 27 ] MATLAB, (limited) ML, F#, or OCaml, Perl,
Python, R, Visual Basic
What languages do you know "well"? C, C++, C#,
Highest degree [ BS, University of Texas ] Javascript, Python, R, Visual Basic
Educational field or major [ Mechanical Largest program? [ ~20000 lines ]
engineering ]

Hello world:
Current title or professional discipline [ Data
science consultant ] #include <stdio.h>
Who do you work for? [ My one-man company: int main(void)
terminus data science, LLC ]
{
Do you write programs as part of your work? [
Yes ] puts("hello world.");
Do you automate Excel (e.g. with VBA) as part of }
your work? [ Yes ]
Is this an “Excel Macro class”?
• They’re not macros.
• They’re programs…
• … and this is a programming class webinar
Programming
programming: the expression of computations in a
formal notation, executable by a real or abstract
machine, and understandable by a human reader

• I made that up, but I like it.


• Programming is also:
• applied math
• an engineering discipline
• an art
• a craft
• a communications medium
Digression: Why VBA?
• I hate Visual Basic.
• No, I really can’t overstate it: I loathe it.

• BUT:
• Many petroleum engineers learn VBA in college
• It’s a development environment that’s installed on most
of your machines, and requires no IT support
• We deal with a lot of spreadsheets, and automating
Excel is a convenient way to enhance them
• VBA is the “native language” of Excel…
• … but we’ll explore some other options at the end
• Think of VBA as a “first step”
Programming
Wirth, 1976 SPE YPs, 2016

functions +
data types =
programs
Interactive Interlude
Hello VBA & editor configuration
Types
type system: “a tractable syntactic method for
proving the absence of certain program
behaviors by classifying phrases according to the
kinds of values they compute.” (Pierce, 2002)

type system: a set of rules for labeling “things” by


the kind of “things” they are, so that you don’t
add bananas to a Lamborghini (YPs, 2016)
A Useful Lie
dynamic typing: values have types; variables store values;
type-checking happens at execution

Examples: Python, Javascript, Perl, Visual Basic with


Variants everywhere and no Option Explicit
Dynamic Typing
>>> x =

>>> y =

>>> x + y
TypeError: unsupported operand
type(s) for +: ‘car’ and ‘fruit’
A Useful Lie
static typing: variables/names have types; these
types constrain the values assigned; type-
checking happens prior to execution

Examples: C, C++, Java, Haskell, FORTRAN,


Visual Basic with Option Explicit
Static Typing
#include <iostream>

int main()
{
car x = ;

fruit y = ;

std::cout << x + y << '\n';


}

In function 'int main()':


error: no match for 'operator+' (operand types are 'car' and
'fruit')
Static Typing
Dim x As Car
Dim y As Fruit

Set x =

Set y =

[Link] x + y
VBA: Primitive Types
primitive type: a type that’s not a composite (e.g.
array, structure, or object) type, usually built into
a language

I’m leaving some out because you should never*


use them.

* well, hardly ever


VBA: Primitive Types
Type What It Is Example / Literal
Long a 32-bit integer 721734
Double a 64-bit floating point -17.56
value
String a character string (i.e. "hello world"
text)
Boolean a true or false value True
Variant a "boxed" value of any any of the above
other type
Functions (aka subroutines, procedures,
methods, blocks, lambdas...)
function: a subprogram with specified inputs and
outputs which may be invoked multiple times
from elsewhere in the program

pure function: a function whose outputs depend


only on its inputs (i.e. a function with no side
effects)

functional decomposition: the fundamental skill of


engineering… and of software design
VBA: Functions (& “Subs”)
Option Explicit

Public Sub WriteCell(ByVal cell As Range, ByVal contents


As Variant)
[Link] = contents
End Sub

Public Function Factorial(ByVal x As Long) As Long


If x <= 0 Then
Factorial = 1
Else
Factorial = x * Factorial(x - 1)
End If
End Function
VBA: Functions (& “Subs”)
Public Sub UseFunctions()
[Link] "original value: " &
[Link]("A1").Value
WriteCell [Link]("A1"), 17
[Link] "new contents: " &
[Link]("A1").Value
[Link] "factorial(5) = " &
Factorial(5)
End Sub

original value:
new contents: 17
factorial(5) = 120
VBA: Functions
Use Functions when you need to compute output(s)
from input(s), and try to keep them pure functions

[Public|Private] Function
Name([ByVal|ByRef] Arg1 [As Type], …)
As Type

Name = value
End Function

result = Name(arg1, …)
VBA: Sub(routine)s
Use Subs when you need to perform side effects
(read a database, write to the spreadsheet…) and
delegate computation to functions

[Public|Private] Sub
Name([ByVal|ByRef] Arg1 [As Type], …)

End Sub

Name arg1, …
VBA: Control Structures
Conditional statements are used to branch,
depending on a Boolean condition

If Condition Then

[ElseIf OtherCondition Then]

[Else]

End If
VBA: Control Structures
Loops are used to iterate a fixed number of
times, while a condition holds, or until a
condition is met

Dim i As Long
For i = 1 To 10

Next i
VBA: Control Structures
Do [While|Until] Condition

Loop

Do

Loop [While|Until] Condition
Example: Pseudopressure
• Pseudopressure: a computed value used to
(somewhat) re-linearize the diffusivity
equation for compressible fluids (i.e. gas)
• [Link]
nd_multiphase_flow
• There’s an integral, which we’re going to
compute using the trapezoidal rule
• [Link]
Pseudopressure
In short, we want to calculate:

𝑝
𝑝
𝑝𝑝 (𝑝) = 2 න 𝑑𝑝
𝑝0 𝜇𝑧

We’re going to assume constant 𝜇𝑧, which is wrong and defeats the
entire purpose… but this is a short class. The mathematically astute
(or reservoir engineers) among you will notice this is just the
pressure-squared approximation.

We’ll come back to this later.


Trapezoidal Rule
ℎ1

ℎ2

ℎ1 + ℎ2
𝐴=𝑤
2
Interactive Interlude
Pseudo-pressure function & calling functions from Excel
Appendix
(For later reading)
Typographic key
• Vocabulary: usually followed by a definition
• Program text
• Program, compiler, or interpreter
output
• Corrections

You might also like