Upload
buikhuong
View
229
Download
0
Embed Size (px)
Citation preview
1
Quick Course of Visual Basic
for Excel
© J. Wach
Introduction 2
Visual Basic for Applications (VBA) is a programming language based on Visual Basic
(VB) implemented in MS Office applications and several others (AutoCAD, Solid Edge
etc.). This simplified version of VB is primarily used to automate work with
documents.
The main difference between VBA and VB is that VBA does not allow creating
independent EXE applications. The program code written in VBA is always included in
the document (i.e. XLS) created by some host program (i.e. Excel) and requires a
runtime environment for running, which is the host application that supports the
document. VBA is an add-on to host applications and is installed together with them.
VBA helps to build customized applications and solutions to enhance the capabilities
of host applications. The advantage of using VBA in Excel is that one can build very
powerful tools using linear programming.
Although the Excel provides a plenty of inbuilt functions virtually most of them are
business oriented and many functions suitable for engineering purposes are simply
not available. Therefore, they must be created by user in the form of Excel
formulas, but when the formulas are complex, they become illegible and
uncomfortable to use. In this case, using VBA to create user defined functions (UDF)
becomes the most obvious solution.
3Starting Visual Basic Editor - VBE
ALT – F11
1. Start the Excel
2. Open or create a new workbook
3. Save it as a XLSM file (file with macro-enabled workbook)
4. … and finally press
… to invoke VBE
NOTE.
Any time you press ALT-F11 you switch between VB
Editor and Excel worksheet
4Creating a new VB module in VBE
(3) … now enter
source code
(2)Then select
Insert Module
to open a new
module window
(1)In Project
Explorer panel
right click on
VBAProject (…)
to invoke popup
menu.
If you don’t want to be annoyed by popping up the error message window, do as follow:
Tools Options tab Editor and uncheck option - [ ] Auto syntax check,
Name the module 5
In Properties panel change the
name of the new module. Should be brief and self-explanatory
Settings 6
In case when someone needs to customize Excel in more elaborated way it would be
advisable to enable Developer ribbon menu.
To do this click: File Options, then click Customize the Ribbon tab and check
Developer and Click OK.
Optionally click here
to start VBE
First dummy function 7
Here is a comment
Keywords Identifier = Name
Use the new defined function in Excel formula 8
In a cell start typing
= du
and Excel displays a list of available functions among which you can find the new defined one. Press TAB to enter its name to formula window
After pressing the Enter key
you’ll see the result
returned by function in the
cell.
9Visual Basic (VB) language elements
Basic characters set (alphabet) used in VB tokens:
a b c d e f g h i j k l m n o p q r s t u v w x y z
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
0 1 2 3 4 5 6 7 8 9
_ . , : ’ = < > + - * / \ ^ ( ) [ ]% # $ @ ! & ” ;
Comments: a programmer-readable annotation in the source code, which areignored by interpreter during runtime. In VB comments are introduced by REM
keyword or by apostrophe and extends as far as the end of line. Examples:
REM This is comment and here all magic words loose its power
or 'Another way of inserting a comment here, the word żółć is OK
Within comment one can use any character than can be entered from a keyboard
even if it isn’t member of the VB character set.
Use comments. Without them, after some time, your own program will
become as mysterious as written by someone else. At least you should
put comment before every function in order to describe exactly its
application, usage, limitations, meaning of parameters, etc.
10Keywords
Keyword: a reserved word with special meaning in a particular context. In
VB cannot be used as an identifier, such as the name of a variable, function, or label. Keywords in VB are case insensitive therefore REM, Rem and rem are
the same
Some VB keywords (minimal set):
REM,
DIM, AS, BOOLEAN, BYTE, INTEGER, LONG, SINGLE, DOUBLE, STRING,
LET, SIN, COS, TAN, ATN, EXP, LOG, SQR, SGN, ABS, RDN, INT, FIX
TRUE, FALSE, IF, THEN, ELSEIF, ELSE
FOR, TO, STEP, NEXT, DO, LOOP, WHILE, UNTIL, WEND
FUNCTION, EXIT, END
In VB keywords are used to build statements. Each statement begins
with some keyword.
11Identifiers (names)
Names are given by programmer to different entities such as variables, functions, types
etc. In VB it is a sequence (max 255 char.) of letters (in Excel VBA diacritical characters
are allowed), digits and the underscore „_” character. Names must begins with an
letter, and must be different from any VB keyword. Identifiers are case insensitive.
In VB variable or function identifier can be suffixed by one of the following characters:
% & # ^ ! $ @
These are identifier type characters, which determine only an item data type, and are not
a part of an identifier.
Examples:
Correct VB identifiers:
dT ≡ dt (hence dT/dt always equals 1 because of case insensitivity)
A1, p_max, pi, temperature, długość (!! this is Ok), ...
Wrong VB identifiers (errors are marked with red)
1A, a?, person█name, temp^2
… and suggestions how to correct them
nr_1A, a_question, person_name or PersonName, temp_2
Statement 12
A statement is a syntactic unit of programming language. In VB statements are used to control
workflow, build definition, declaration, and instructions.
A program in VB (called source code) is simply a sequence of statements.
Statement must occupy one line, but with underscore “_” character, which is line-
continuation character, preceded by space one can break too long statement into two or more
lines.
Several statements can be placed in one line, but then they must be separated by colon “:”
Examples: 'Constant definition
Const pi = 3.141592
'Variable declaration
Dim time, omega As Double
'Assignment statement (instruction)
Let time = 1/(2*pi*f)
'Many statement in one line separated by colon :
Dim f As Double: Let f = 100.0
Let omega = 2*pi*f: Let time = 1/omega
'One long statement . . .
Let a = 1.000023*x + 0.374091*y + 0.096784*z + 0.278868/v
'. . . broken down into many lines
Let a = 1.000023 * x _
+ 0.374091 * y _
+ 0.096784 * z _
+ 0.278868 / v
Returning result to formula 13
In order for a function to return a specific result,
somewhere in the function body, must be at least
one assignment statement that assigns the result
of the calculation to the function identifier. That
value will be returned to the call location. The
syntax is:
LET fun_name = expression
Without this, function will always return the zero
value, what is default behavior. The keyword LET
can be omitted.
This is numerical literal
Literal 14
A literal is a sequence of characters that represents fixed value in source code like
number, text string, date and other.
Integer literal – used to represent integer numbers. It is a sequence of decimal digits preceded if
necessary with minus or optionally with plus character.
+125 ≡ 125 ; -456 ; 30113 ; 000123 ≡ 123 …
Characters: % & and ^ forces respectively INTEGER, LONG or LONGLONG type:
125% 125& 125^ the same number 125, but of different type (and size)
Floating point literal – used to represent rational numbers in decimal form. It is compound of two
sequences of digits, representing respectively integer and fraction part of a number, preceded if necessary
with sign character („–”, „+”) and separated by dot. The plus character can be omitted if the number is
positive. Either integer or fraction parts may be omitted if any of them is equal to zero, but the decimal
separator (dot) must remain.
Another way is to write it in the significand–exponent form (scientific notation) i.e. if m – significand
(integer or floating point literal) and c – exponent (integer literal) then literal has form mEc and represents
value m∙10c.
+125.0 ≡ 125.0 ≡ 125. ; -124.567 ; 0.001234 ≡ .001234 ≡ 0.00123400
0.0 ≡ 0. ≡ .0 floating point zero
1.0E+03 ≡ 1E3 ≡ 10E2 ≡ 100E1 ≡ 1000.0 ≡ 1000. one thousand1.23E+03 ≡ 12.3E+2 ≡ 123.0E1 ≡ 123E1 ≡ 1230.0 1.23∙103 = 1230.0
Characters ! and # forces respectively SINGLE lub DOUBLE type:
125.0! ≡ 125! 125.0# ≡ 125# the same number 125, but of different type (and size)
Literal cont. 15
Date literal – (represents date and time) a sequence of characters enclosed between pair of hash
characters #...#
#1 February 1950#
#01.02.1950#
#1 May 2014 12:35#
String literal – represents text which can be displayed on screen. This is a sequence of characters
enclosed between pair of double-quote characters “…”. Between them one can put any ASCII
character, which can be entered from keyboard including diacritical characters. Upper and lower
case letters are distinguishable. String literal can be empty “”.
"This is some text, in which one can put any printable character "
If double-quote character is to be part of the string, then it must be doubled.
"The title of the film is ""Invincible""" right
"""" represents single double-quote character (!!)
"The title of the film is "Invincible"" wrong because
this is interpreted as string "The film title is "
followed by some illegal token: Invincible""
Function with single parameter 16
The function takes one parameter which is
listed between parenthesis (here is “x”) and
carries out some calculation (here 2x +1)
which result is returned to formula. Syntax:
fun_name ( list_of _par )
dummy_par(x)
This is variablenamed „x”
Whenever you make any amendments to your code you should press
Ctrl + Alt + F9 to force recalculation of all worksheets.
Variables 17
A variable is a memory location (identified by a memory address) paired with an associated
symbolic name (an identifier), used to hold some data value that can be changed during
execution.
There are two things one can do with a variable: read it – take a value stored in it, or write to it
– replace an old value by new one. A variable is read whenever it is used in expression. Reading
doesn't change the value stored in it, but writing does. To write new value to variable one should
use an assignment statement in the following form:
LET variable_name = expression
variable_name = expression
or simpler form
where:
variable_name - variable identifier
expression – some sort of expression e.g. mathematical
Expressions 18
An expression is a sequence of literals, operators, variables, functions, constants and parenthesis that
describes the way the data is to be processed (calculated). In case of mathematical expressions, calculation
are done according to operators precedence, which can be altered by round brackets – parenthesis ( ). No
other type of bracket - like square [ ] or curly { } - can be used in this role.
(2) Arithmetical operators
(descending precedence)
Examples
Rise to power (^) a ^ 2, a ^ 0.5
Opposite value (-) -a
Multiplication, division (*, /) a*b, 2*a, a/b (11/2 = 5.5)
Integer division (\) a\b (11\2 = 5)
Modulo division (mod) a mod b (10 mod 3 = 1)
Addition, subtraction (+,-) a+b, a-b
(4) Logical operators
(descending precedence)
Examples
Negation a (not) NOT a
Conjunction a b (and) a AND b
Disjunction a b (or) a OR b
Exclusive disjunction (xor) a XOR b
Equivalence a b (eqv) a EQV b
Implication a b (ipm) a IMP b
(3) Comparison operators (equal precedence) :
equal =, non-equal <>
greater then >, less then <,
greater or equal >=, less or equal <=
(1) Functions (equal precedence) Examples
Trigonometric: sin(x), cos(x), tan(x), arctan(x) sin(x), cos(x), tan(x), atn(x)
Exponent ex = exp(x) and natural logarithm ln(x) (!!) exp(x), log(x)
Absolute value |x| and sign sgn(x) abs(x), sgn(x)
Square root 𝑥 sqr(x) or x^0.5
Integer part of a number [x] int(x) (< x), fix(x) (>x for x<0 and <x for x>0)
Random number rnd, randomize (seed function)
Expressions - evaluation order 19
Evaluation order: In the first place subexpressions in parenthesis and functions, then arithmetic
operators, then comparison operators and in the end logical operators. Operators are evaluated
according to their precedence. In case of equal precedence they are evaluated from left to right
(left-associative). Evaluating precedence can be altered by parenthesis. In case of nested
parenthesis most nested expression are evaluated as first.
x = x + 1
4/2*12/4 is evaluated as ((4/2)*12)/4 (2*12)/4 24/4 6
NOTE: left-associativity of rise to power operator, and (!) spaces preceding the ^
character
4 ^ 3 ^ 2 is evaluated as (4 ^ 3) ^ 2 64 ^ 2 4096
but not like this (4/2)*(12/4) 3*4 6
NOTE: this is not meaningless
this increases x value by one
x = x - 1 similarly this decreases x value by one
x = 2 * x this increases x value two times
but not like this 4 ^ (3 ^ 2) 4 ^ 9 262144
4*(1+2*(3+4)) is evaluated as 4*(1+2*(3+4)) 4*(1+2*7) 4*(1+14) 4*15 60
4*[1+2*(3+4)] wrong, only round brackets can be used
Expressions - mathematical formula transcription examples 20
𝑎 + 𝑏
𝑐 + 𝑑(a+b)/(c+d)
−𝑏 + 𝑏2 − 4𝑎𝑐
2𝑎
(-b+sqr(b^2-4*a*c))/(2*a)
(-b+sqr(b*b-4*a*c))/2/a
𝑎
𝑏 + 𝑐a/(b+c) 𝑎 + 𝑏
𝑐(a+b)/c
𝑎 + 𝑏
𝑐 𝑑=𝑎 + 𝑏
𝑐
1
𝑑
(a+b)/(c*d)
(a+b)/c/d
sqr(2*k*p/((k-1)*ro)*(1-(p0/p)^((k-1)/k)))
sqr(2*k/(k-1)*p/ro*(1-(p0/p)^((k-1)/k)))
2𝜅
𝜅 − 1
𝑝
𝜚1 −
𝑃0𝑝
(𝜅−1)/𝜅
a = 1.000023 * x _
+ 0.374091 * y _
+ 0.096784 * z _
+ 0.278868 / v
a+b/c 𝑎 +𝑏
𝑐
Too long expressions can be broken into two or more lines using underscore “_” character preceded by space as in thisexample:
a = 1.000023 * x + 0.374091 * y + 0.096784 * z + 0.278868 / v
𝑎 + (−𝑏)
a – b
a + -b
a + (-b)
-b + a
𝑎𝑏
𝑐𝑑
a*b/(c*d)
(a*b)/(c*d)
a/c*b/d
Function with many parameters 21
The function takes two parameters which are listed
between parenthesis (here they are “a” and „b”)
and calculates hypotenuse "c" in right triangle of
sides a, b and c according to Pythagorean theorem.
dummy_2(a, b)
Syntax:
fun_name ( list_of _par )
𝒄 = 𝒂𝟐 + 𝒃𝟐
Note: in some non-English Excel versions not colon, but semicolon is used as an argument separator in function call.
Data types 22
Type Range Size [B]
BYTE 0 .. 255 (1-3 digits accuracy) 1
INTEGER -32768 .. 32767 (4-5 digits accuracy) 2
LONG -2147483648 .. 2147483647 (9-10 digits accuracy) 4
LONGLONG -9223372036854775808 .. 9223372036854775807 (±1019) (18-19 digits accuracy) 8
SINGLE ±1,5∙10-45 .. ±3,4∙1038 (8 digits accuracy) 4
DOUBLE ±5,0∙10-324 .. ±1,7∙10308 (16 digits accuracy) 8
The data type (simply type) is a set of values that data can have. The data type determines which
operation can be performed and how its values are represented in memory. In VB there are primitive
types and composite types. The primitive types represent values that cannot be broken down into
smaller components. Composite types are values that are collection of some values which can be both
primitive or composite types. Bellow list of VB primitive types:
Numerical types: (green - integer, red - floating point types)
Logical type:
BOOLEAN can poses one of the two values TRUE or FALSE
e.g. 2 > 3 FALSE, 2 <> 3 TRUE, 2 = 3 FALSE …
Text string type:
STRING represents text of variable or fixed length
Type declaration 23
It is not obligatory, but highly recommended to declare variables, constants and functions.
Declarations saves execution time and memory space. Undeclared variables are called variants
and occupy more space in memory. They should be used only when a variable is planned to hold
data of different type. If the data type is well known then every variable should be declared.
Declaration syntax:
DIM varaibles_list AS Type
Where: varaibles_list – a list of variables’ names separated by coma, Type – type keyword
(integer, long, single, double, Boolean etc.) or type identifier.
’ Declaration of identifiers a, b as
’ double precision floating point variables
DIM a, b AS Double
’ and this is equivalent to
DIM a AS Double
DIM b AS Double
With identifier type characters (% & ^ ! # $) declaration can be simpler. It is sufficient to suffix
an identifier with type character first time when it appear in the code. Examples:
Dim i As Integer i%
Dim n As Long n&Dim x As Single x!
Dim y As Double y#
24Declaration examples
Function sinh(x as double) as double
sinh = (exp(x) - exp(-x))/2#
End Function
Function sinh#(x#)
sinh = 0.5*(exp(x) - exp(-x))
End Function
sinh 𝑥 =e𝑥 − e−𝑥
2
Function sinh(x)
sinh = (exp(x) - exp(-x))/2.0
End Function
Function diag (a as double, b as double) as double
diag = sqr(a^2 + b^2)
End Function
𝑑(𝑎, 𝑏) = 𝑎2 + 𝑏2
- acceptable but not recommended
- alternative way with identifier type characters (here
character # is used do declare double type)
- recommended way
One argument function
Two or more arguments
function
Block diagrams 25
START
Instruction
a, b …
Condi
-tion
x, y, …
STOP
Condition
11
Terminating place
Line indicating
workflow direction
Data input box
Instructions box
Algorithm branching
Output results
Beginning of an algorithm
Line connector used when line has
to be broken for clarity reason(between pages or within page)
or
SubroutineSubroutine calling
A block diagram is a specialized,
high-level flowchart used in
programming. Its structure provides
a high-level overview of major
algorithm components, and
workflows branching.
The block diagram is used to present
the general idea of an algorithm
without referring to any specific
programming language.
26An algorithm for finding roots of a quadratic equation
Block diagramThe algorithm
𝑓 𝑥 = 𝑎𝑥2 + 𝑏𝑥 + 𝑐
Δ = 𝑏2 − 4𝑎𝑐
1. Get the input parameters: a, b, c
2. Calculate a discriminant
3. Test the D value
a. If D < 0 then no solution is
available
b. If D = 0 then there is one
solution x0
𝑥0 = −𝑏
2𝑎
c. If D > 0 then there are two
solutions x1 and x2
𝑥1 =−𝑏 + √Δ
2𝑎𝑥2 =
−𝑏 + √Δ
2𝑎
Branching - conditional statement IF THEN 27
Instruction_1
Instruction_2
...
Instruction_3
Condition
T
F
X = -15
...
IF X < 0 THEN X = -X
... ' here x=15
Example:Instruction_1
IF condition THEN Instruction_2
Instruction_3
min = 15
max = -1
...
IF min > max THEN x = max: max = min: min = x
... ' Now min=-1 a max=15
Exchanging values between two variables min and max, when min > max.
many instructions can be separated by ":„
and such a sequence is treated as one
min max
x
2
13
Exchanging Algorithm between
min i max with the help of
auxiliary variable x
X = ABS(X)
Function vb_abs(x As Double) As Double
If x < 0 Then x = -x
vb_abs = x
End Function
Instruction_1
IF condition THEN
Instruction_2
...
END IF
Instruction_3
X = -15
...
IF X < 0 THEN
X = -X
END IF
...’here x=15
𝑥 = ቊ−𝑥 when 𝑥 < 0𝑥 when 𝑥 ≥ 0
Condition = Boolean expression resulting in the
values True or False i.e. (x<0 OR 1<x)
Branching – conditional statement IF THEN ELSE 28
Instruction_1
Instruction_3
...
Instruction_4
condition
Instruction_2
...
T F
Instruction_1
IF condition THEN
Instruction_2
...
ELSE
Instruction_3
...
END IF
Instruction_4
Function vb_sgn(x As Double) As Double
If x < 0 Then
vb_sgn = -1#
Else
If x > 0 Then
vb_sgn = 1#
Else
vb_sgn = 0
End If
End If
End Function
Examples:
Function sinc(x As Double) As Double
If x = 0 Then
sinc = 1#
Else
sinc = Sin(x) / x
End If
End Function
sinc 𝑥 = ቐ1 when 𝑥 = 0sin 𝑥
𝑥when 𝑥 ≠ 0
This is nested sequence of IF THEN ELSE statements. See next page how to make it simpler
sgn 𝑥 = ቐ−1 when 𝑥 < 00 when𝑥 = 01 when𝑥 > 0
Branching – conditional statement IF THEN ELSEIF ELSE 29
condition1
Instruction_1
T F
Function vb_sgn(x As Double) As Double
If x < 0 Then
vb_sgn = -1#
ElseIf x > 0 Then
vb_sgn = 1#
Else
vb_sgn = 0
End If
End Function
Note! "ELSEIF" is not the same as "ELSE IF"
condition2F
conditionN_1
Instruction_2
Instruction_n_1
T
T
F
. . . .
. . . .
. . . .
Instruction_n
IF condition1 THEN
instruction_1
ELSEIF condition2 THEN
instruction_2
. . . .
ELSEIF conditionN_1 THEN
instruction_n_1
ELSE
instruction_n
END IF
ELSE part is optional
In case when chain of if then else if then … is to be used VB offers
compact version o IF statement
Loop statement DO LOOP – condition at the beginning 30
Instruction_1
Instruction_2
....
Condition
Instruction_3
Instruction_1
DO WHILE condition
Instruction_2
...
LOOP
Instruction_3
fact = 1
i = 1
DO UNTIL i > n
fact = fact * i
i = i + 1
LOOP
This condition tells when to stay in the loop
This condition tells when to get out of the loop
Instruction_1
DO UNTIL condition
Instruction_2
...
LOOP
Instruction_3
fact = 1
i = 1
DO WHILE i <= n
fact = fact * i
i = i + 1
LOOP
Example, calculating factorial of n i.e n! = 1∙2 ∙3 ∙ ... ∙ n
T, F
F, T
T
F
or NOT i <= n
Instruction_1
WHILE condition
Instruction_2
...
WEND
Instruction_3
Function vb_fact(n As Byte) As Double
Dim res As Double
Dim i As Byte
res = 1
i = 1
Do Until i > n (Do While i <= n )
res = i * res
i = i + 1
Loop
vb_fact = res
End Function
Instruction_1
WHILE NOT condition
Instruction_2
...
WEND
Instruction_3
Loop statement DO LOOP – condition at the end 31
Instruction_1
DO
Instruction_2
...
LOOP WHILE condition
Instruction_3
Instruction_2
...
Instruction_3
ConditionT, F
F, T
Instruction_1
DO
INPUT "X = ", X
LOOP WHILE X <= 0
Example: How to prevent from entering to variable x a non-positive value
DO
INPUT "X = ", X
LOOP UNTIL X > 0
Instrukcja_1
DO
Instrukcja_2
...
LOOP UNTIL condition
Instruction_3
This condition tells when to stay in the loop
This condition tells when to exit the loop
T
F
Function vb_input() As Double
Dim x
Do
x = Application.InputBox("Enter positive number")
Loop While x <= 0
vb_input = x
End Function
Loop statement DO LOOP – condition somewhere inside 32
Instruction_2
...
Instruction_4
ConditionT
F
Instruction_1
Instruction_1
DO
Instruction_2
...
IF Exit_condition THEN EXIT DO
...
Instruction_3
LOOP
Instruction_4
EXIT DO statement is design to exit a loop from any place
inside it. Typically, it is combined with IF THEN statement
with condition which has to be fulfilled to break the loop.
Can be combined with WHILE and UNTIL
. . .
Instruction_3T
Repeating a group of statements a specified number of times - FOR 33
Instruction_1
j = start
DO WHILE j <= Max
Instructions_2
j = j + step
LOOP
Instruction_3
j j + step
Instruction_3
j <= max
T
F
Instructions_2
j start
Instruction_1
Instruction_1
FOR j = start TO Max STEP step
Instructions_2
NEXT j
Instruction_3
Instruction_1
FOR j = 1 TO Max
Instructions_2
NEXT
Instruction_3
Case: start=1, step=1. Loop is
executed Max number of
times
fact = 1
FOR i = 2 TO n
fact = fact * i
NEXT
Note:The section STEP can be omitted when step = 1.
Loop counter after NEXT can be also omitted.
In this loop an instruction set is executed
specified number of times. Here, the
repetition is controlled by auxiliary variable
j (loop counter) which name is given by
programmer.
Alternative realization by
DO … LOOP statement
Example factorial of n
Constants definition 34
In computer programming, a constant is a value that cannot be altered by the program
during normal execution, i.e., the value is constant. When associated with an identifier,
a constant is said to be "named," although the terms "constant" and "named constant" are
often used interchangeably. It is advisable to use constants instead of literals or constant
expressions (i.e. expressions where no variable are used) as it makes source code more
clear, readable, flexible, and easier to maintain.
Syntax: CONST const_name = constant_expresion
or
CONST const_name AS type = constant_expresion
Example: CONST pi = 3.141592
CONST deg = pi / 180#
CONST pi_2 AS DOUBLE = pi / 2
’ This is wrong as it invokes function. In constant expression only constant’ values can be used
CONST pi = 4 * ATN(1)
Example: Sun azimuth calculation 35
Const pi = 3.14159265358979 'can be also computed as pi = 4 * Atn(1)
Const deg = pi / 180# 'to transform angles known in degrees into radians e.g. 15*deg
' The Sun azimuth in radians
'---------------------------------
' Input:
' day - day number 1 .. 365
' hangle - hour angle in radians
' lat - latitude in radians
' Result:
' the sun angular altitude (above horizon) in radians
'
Function SunAzim(day As Double, hangle As Double, lat As Double) As Double
Dim beta As Double ' the Sun altitude
Dim decl As Double ' the Sun declination
Dim azim As Double ' the sun azimuth candidate
Dim cosw As Double ' cosine of hour angle for the Sun on West
decl = 23.45 * deg * Sin(2 * pi * (day - 81) / 365#)
beta = Cos(lat) * Cos(hangle) * Cos(decl) + Sin(lat) * Sin(decl) ' this calculates sin(beta)
beta = Application.WorksheetFunction.Asin(beta) ' and this calculates beta
cosw = Tan(decl) / Tan(lat)
azim = Cos(decl) * Sin(hangle) / Cos(beta)
azim = WorksheetFunction.Asin(azim)
If (Cos(hangle) >= cosw) Then
SunAzim = azim
Else
If (azim >= 0) Then
SunAzim = pi - azim
Else
SunAzim = -pi - azim
End If
End If
End Function
If some Excel function has to be used, that is not defined in VB
like arcsin(x), then instead of defining the function on the
basis of some mathematical identity, one can call it by
refereeing to a special object Application as in the following
example:
Application.WorksheetFunction.asin(…)
or
WorksheetFunction.asin(…)
where asin is an Excel arcsin(..) function.
References 36
[1] https://www.exceltrick.com/excel-vba-basics/getting-familiar-with-vbe/
[2] https://msdn.microsoft.com/en-
us/library/office/ee814737%28v=office.14%29.aspx#odc_Office14_ta_GettingStartedWit
hVBAInExcel2010_VBAProgramming101
[2] Excel 2010 Developer Reference
https://msdn.microsoft.com/en-us/library/office/ff846392%28v=office.14%29.aspx
[3] Visual Basic for Applications language reference for Office 2010
https://msdn.microsoft.com/en-us/library/office/gg278919%28v=office.14%29.aspx
[4] Visual Basic for Applications language reference for Office 2013
https://msdn.microsoft.com/en-us/library/office/gg264383%28v=office.15%29.aspx
[7] MS Office Dev Center:
https://docs.microsoft.com/en-us/office/vba/excel/concepts/events-
worksheetfunctions-shapes/list-of-worksheet-functions-available-to-visual-basic
[8] Excel and VBA Solutions - http://www.globaliconnect.com/excel/
[9] https://docs.microsoft.com/pl-pl/office/vba/language/glossary/vbe-glossary#variable