Excel VBA Programming For Solving Chemical Engineering Problems
Excel VBA Programming For Solving Chemical Engineering Problems
• Solving a function
y = 2-x
when y = x, for 0 ≤ x ≤ 2.
• We can use the built-in Goal Seek feature of
Excel.
• We can also write our own VBA program to
solve this problem by iteration.
Solving a Mathematical Problem (2)
• Demonstration:
– Goal Seek
– A VBA program
Sub HelloYou()
Dim MyMessage
MyMessage = "Hello You!"
MsgBox MyMessage
End Sub
• Both have a variable called MyMessage.
• However, these two variables are independent variables.
• Example program (Variable_Scope_1.xls).
Variable Scope (2)
• Now consider this program:
Dim MyMessage
Sub HelloWorld()
MyMessage = "Hello World!"
MsgBox MyMessage
End Sub
Sub HelloYou()
MyMessage = "Hello You!"
MsgBox MyMessage
End Sub
Sub Hello()
MsgBox MyMessage
End Sub
• Now the variable MyMessage is “shared” among these three
procedures.
• Example program (Variable_Scope_2.xls).
Variable Scope (3)
• Case I:
– A variable declared inside a procedure is available
only inside that procedure.
– This variable is called procedure-level variable.
• Case II:
– A variable declared outside a procedure but in the
same module. This variable is available to all
procedures in the same module but not to other
module.
– This variable is called module-level variable.
Variable Scope (4)
• You should pay attention to Dim Var1 As Integer
variable scope when
designing your program.
Sub MainProgram()
• If you design your variable
Var1 = 10
scope properly, you can
avoid modifying the value MyFunction()
of a variable accidentally. End Sub
• For the example program at
right, what will be the value Function MyFunction()
of module-level variable Var1 = 100
Var1 after execute
procedure End Function
MainProgram()?
Operators (1)
Commonly used operators
• Arithmetic operators: • Comparison operators:
– Addition: + – Equal To: =
– Subtraction: - – Not Equal To: <>
– Multiplication: * – Less Than: <
– Division: / – Greater Than: >
– Integer Division: \ – Less Than Or Equal To: <=
– Modulo Division: MOD – Greater Than Or Equal To: >=
– Exponentiation: ^ • Logical operators:
– Negative Number: - – Conjunction: And
• String operator: – Disjunction: Or
– Concatenation (i.e., joining – Negation: Not
two strings together to form
a longer string): &
Operators (2)
• Syntax of some operators:
– 87 \ 10 ( = 8, result is an integer )
– 87 MOD 10 ( = 87 - (87 \ 10) = 7, result is an
integer )
– 10^2 ( = 102 = 100 )
– "Hello " & "World" ( = "Hello
World" )
• You should pay attention on the result data
types of operators, and functions.
Operator Precedence (1)
^
- (negative number)
*, /
\
MOD
+, -
&
<, <=, >, >=, =, <> (comparison)
Not
And
Or
Operator Precedence (2)
•1 ^ 2 + 3=4 (i.e. 12 + 3 = 4)
• 1 ^ (2 + 3) = 1 (i.e. 1(2+3) = 1)
• You need to add parentheses as necessary