You are on page 1of 15

1

infotica
vbafaculty@gmail.com

Operator Precedence
When several operations occur in an expression, each part is evaluated and
resolved in a predetermined order called operator precedence.
When expressions contain operators from more than one category, arithmetic
operators are evaluated first, comparison operators are evaluated next, and
logical operators are evaluated last. Comparison operators all have equal
precedence; that is, they are evaluated in the left-to-right order in which they
appear. Arithmetic and logical operators are evaluated in the following order of
precedence:
Arithmetic

Comparison

Logical

Exponentiation (^)

Equality (=)

Not

Negation ()

Inequality (<>)

And

Multiplication and division (*, /)

Less than (<)

Or

Integer division (\)

Greater than (>)

Modulus arithmetic (Mod)

Less than or equal to (<=)

Addition and subtraction (+, )

Greater than or equal to (>=)

String concatenation (&)

Like

When multiplication and division occur together in an expression, each operation


is evaluated as it occurs from left to right. When addition and subtraction occur
together in an expression, each operation is evaluated in order of appearance
from left to right. Parentheses can be used to override the order of precedence
and force some parts of an expression to be evaluated before others. Operations
within parentheses are always performed before those outside. Within
parentheses, however, operator precedence is maintained.
The string concatenation operator (&) is not an arithmetic operator, but in
precedence, it does follow all arithmetic operators and precede all comparison
operators.
The Like operator is equal in precedence to all comparison operators, but is
actually a pattern-matching operator.

BRANCHING

IIf Function
Returns one of two parts, depending on the evaluation of an expression.
Syntax
IIf(expr, truepart, falsepart)
The IIf function syntax has these named arguments:
Part

Description

expr

Required. Expression you want to evaluate.

truepart

Required. Value or expression returned if expr is True.

falsepart

Required. Value or expression returned if expr is False.

Remarks

infotica
vbafaculty@gmail.com

IIf always evaluates both truepart and falsepart, even though it returns only
one of them. Because of this, you should watch for undesirable side effects. For
example, if evaluating falsepart results in a division by zero error, an error
occurs even if expr is True.
Sub iifEx1()
Dim a As Integer
'inputbox :
'to read a value from the user
'Purpose : the bigger of the 2 given no's
a = InputBox("Enter first number")
Dim b As Integer
b = InputBox("enter second number", "Reading B...", 100)
MsgBox "The bigger value is " & IIf(a > b, a, b)
End Sub
Sub iifEx2()
'Read sales-amount & calc. commission
Dim samt As Double, comm As Double
samt = Range("A1")
comm = IIf(samt >= 1000000, samt * 0.5, 1000)
'code
Range("b1") = Round(comm, 2) 'rounded to 2 decimal places
End Sub
Sub iifEx3()
Range("b1") = IIf(Range("A1") Mod 4 = 0, "Leap", "Not a leap")
End Sub

If...Then...Else Statement
Conditionally executes a group of statements, depending on the value of an
expression.
Syntax
If condition Then [statements] [Else elsestatements]
Or, you can use the block form syntax:

infotica
vbafaculty@gmail.com

If condition Then
[statements]
[ElseIf condition-n Then
[elseifstatements]

...
[Else
[elsestatements]]
End If
The If...Then...Else statement syntax has these parts:
Part

Description

condition

Required. One or more of the following two types of expressions:


A numeric expression or string expression that evaluates to True or
False. If condition is Null, condition is treated as False.
An expression of the form TypeOf objectname Is objecttype. The
objectname is any object reference and objecttype is any valid object
type. The expression is True if objectname is of the object type specified
by objecttype; otherwise it is False.

statements

Optional in block form; required in single-line form that has no Else


clause. One or more statements separated by colons; executed if
condition is True.

condition-n

Optional. Same as condition.

elseifstatements

Optional. One or more statements executed if associated condition-n is


True.

elsestatements

Optional. One or more statements executed if no previous condition or


condition-n expression is True.

Remarks
You can use the single-line form (first syntax) for short, simple tests. However,
the block form (second syntax) provides more structure and flexibility than the
single-line form and is usually easier to read, maintain, and debug.

'Single line IF
'*Else is an optional part
'*Single line needs no 'End IF'
Sub ifEx1()
Dim SalesAmount As Double
SalesAmount = Sheets("sheet1").Range("a1")

infotica
vbafaculty@gmail.com

If SalesAmount >= 1000000 Then Range("B1") = SalesAmount *


0.5
'true
End Sub
Sub ifEx2()
Dim SalesAmount As Double
SalesAmount = Sheets("sheet1").Range("a1")
If SalesAmount >= 1000000 Then Range("B1") = SalesAmount *
0.5 Else _
Range("B1") = 1000
End Sub
Sub ifEx3()
'multiline
'*End IF is required
Dim SalesAmount As Double
SalesAmount = Sheets("sheet1").Range("a1")
If SalesAmount >= 1000000 Then
Sheets("sheet1").Range("B1") = Round(SalesAmount * 0.5, 2)
Else
Sheets("sheet1").Range("B1") = 1000
End If
End Sub

'Criteria
'Sales-made

'comm

infotica
vbafaculty@gmail.com

'>=1000000

50%

'>=700000

25%

'>=300000

15%

'otherwise

1000

Sub ifEx4()
'multiline
'*End IF is required
Dim SalesAmount As Double
SalesAmount = Sheets("sheet1").Range("a1")
If SalesAmount >= 1000000 Then
Sheets("sheet1").Range("B1") = Round(SalesAmount * 0.5, 2)
ElseIf SalesAmount >= 700000 Then
Sheets("sheet1").Range("B1") = Round(SalesAmount * 0.25, 2)
ElseIf SalesAmount >= 300000 Then
Sheets("sheet1").Range("B1") = Round(SalesAmount * 0.15, 2)
Else
Sheets("sheet1").Range("B1") = 1000
End If
End Sub

'
Sub ifEx5()
'multiline
'*End IF is required

infotica
vbafaculty@gmail.com

Dim SalesAmount As Double


With Sheets("sheet1")
SalesAmount = .Range("a1")
If SalesAmount >= 1000000 Then
.Range("B1") = Round(SalesAmount * 0.5, 2)
ElseIf SalesAmount >= 700000 Then
.Range("B1") = Round(SalesAmount * 0.25, 2)
ElseIf SalesAmount >= 300000 Then
.Range("B1") = Round(SalesAmount * 0.15, 2)
Else
.Range("B1") = 1000
End If
End With
End Sub
'Read marks, validate and find grade along with average
'Nested IF : One IF may contain one/more IF's

Sub NestedIFex()
'0 is the default value of a numeric variable
'EMPTY is the default of a variant variable
Dim m1 As Integer, m2 As Integer, m3 As Integer
m1 = InputBox("m1")
m2 = InputBox("m2")
m3 = InputBox("m3")

infotica
vbafaculty@gmail.com

Dim tot As Integer, Result As String, Avrg As Single


tot = m1 + m2 + m3
Avrg = Round(tot / 3, 2)
'check whether the student has secured pass-marks
'in all subjects
If m1 >= 40 And m2 >= 40 And m3 >= 35 Then 'Main/Outer
'find grade
If Avrg >= 60 Then 'Sub/Inner/Nested
Result = "A"
ElseIf Avrg >= 50 Then
Result = "B"
Else
Result = "C"
End If
Else
Result = "Fail"
End If

MsgBox "Total Marks " & tot & vbNewLine & _


"Average Marks " & Avrg & vbNewLine & _
"Result " & Result, vbInformation, "Result"
End Sub

infotica
vbafaculty@gmail.com

'Localswindow (View menu) : displays the values of all


'variables from the current program in break-mode(f8)

Select Case Statement

Select Case works like a partial IF i.e, it can take only one input.
Executes one of several groups of statements, depending on the value of an
expression.
Syntax
Select Case testexpression
[Case expressionlist-n
[statements-n]]

...
[Case Else
[elsestatements]]
End Select
The Select Case statement syntax has these parts:
Part

Description

testexpression

Required. Any numeric expression or string expression.

expressionlistn

Required if a Case appears. Delimited list of one or more of the following


forms: expression, expression To expression, Is comparisonoperator
expression. The To keyword specifies a range of values. If you use the To
keyword, the smaller value must appear before To. Use the Is keyword
with comparison operators (except Is and Like) to specify a range of
values. If not supplied, the Is keyword is automatically inserted.

statements-n

Optional. One or more statements executed if testexpression matches any


part of expressionlist-n.

elsestatements

Optional. One or more statements executed if testexpression doesn't


match any of the Case clause.

Remarks
If testexpression matches any Case expressionlist expression, the statements
following that Case clause are executed up to the next Case clause, or, for the
last clause, up to End Select. Control then passes to the statement following
End Select. If testexpression matches an expressionlist expression in more than
one Case clause, only the statements following the first match are executed.
The Case Else clause is used to indicate the elsestatements to be executed if no
match is found between the testexpression and an expressionlist in any of the
other Case selections. Although not required, it is a good idea to have a Case
Else statement in your Select Case block to handle unforeseen testexpression
values. If no Case expressionlist matches testexpression and there is no Case
Else statement, execution continues at the statement following End Select.

infotica
vbafaculty@gmail.com

You can use multiple expressions or ranges in each Case clause. For example,
the following line is valid:

Case 1 To 4, 7 To 9, 11, 13, Is > MaxNumber


The Is comparison operator is not the same as the Is keyword used in the Select Case statement.

You also can specify ranges and multiple expressions for character strings. In the
following example, Case matches strings that are exactly equal to

everything
, strings that fall between

nuts
and

soup
in alphabetic order, and the current value of

TestItem
:

Case "everything", "nuts" To "soup", TestItem


Select Case statements can be nested. Each nested Select Case statement
must have a matching End Select statement.

'Built-ins Contd.
?weekday(date)
2

?weekday(date,vbMonday)
1

?weekdayname(weekday(date))
Monday

10

infotica
vbafaculty@gmail.com

?month(date)
7
?MonthName(month(date))
July

Sub selectCaseEx1()
Dim wcode As Integer
wcode = InputBox("Enter weekday-code(1 to 7) ")
Select Case wcode
Case 1: MsgBox "Su"
Case 2
MsgBox "Mo"
Case 3: MsgBox "Tu"
Case 4: MsgBox "We"
Case 5: MsgBox "Th"
Case 6: MsgBox "Fr"
Case 7: MsgBox "Sa"
Case Else: MsgBox "Wrong weekday-code", vbCritical, "Invalide
Code"
End Select
End Sub
'Note : to comment/uncomment a block of lines, use
'Comment Block/Uncomment Block options from 'Edit' toolbar

Sub selectCaseEx1()
Dim Age As Integer, result As String
Age = InputBox("Enter age(1 to 100) ")

11

infotica
vbafaculty@gmail.com

Select Case Age


Case 1 To 12: result = "Child"
Case 13 To 19: result = "Teenage"
Case 20 To 35: result = "Youth"
Case 36 To 50: result = "Middl age"
Case 51 To 60: result = "Old age"
Case 61 To 100: result = "Sr citizen"
Case Else: result = "Praise the LORD"
End Select
MsgBox result, vbInformation
End Sub
'Note : A range or list of values can be used in select case
'Ex : Case 11, 1 To 12, 123, Is > 1000: result = "working"

Sub getPanType()
'Where exactly I need a variabe?
'All input items+All output items(Excl. input)
'+Loop variables + Addl. counters
'+Addl. variables that work like splitters
'+PlaceHolders

'What is given?
'What to do?
'How to do?

Dim strPanID As String * 10, strPanType As String

12

infotica
vbafaculty@gmail.com

strPanID = Range("a1")

Select Case UCase(Mid(strPanID, 4, 1)) ' 1 char from 4th position


Case "M": strPanType = "Minor"
Case "P": strPanType = "Person"
Case "T": strPanType = " Trust"
Case "H": strPanType = " Hindu United Family"
Case "S": strPanType = " Society"
Case "B": strPanType = " Bank"
Case "C": strPanType = " Company"
Case "F": strPanType = " Firm"
End Select

Range("B1") = strPanType
Columns.AutoFit
End Sub

13

infotica
vbafaculty@gmail.com

14

infotica
vbafaculty@gmail.com

*Goto

LOOPING

Loop
A loop is a programming construct that repeats code
Loops in VBA
3 loops
For, While & Do
'i' is the commonly used variable with loops
ITERATION : cycle
Note : Any loop can contain one/more of same or other type of
Loops as sub loops
FOR
It is number-based i.e, it works/runs for fixed no. of times
[Offer valid from 1-jan-2014 to 3-jan-2014 (1 to 3)]
*It has 2 syntaxes
*Its second syntax (FOR each loop) is used to loop through
Objects
WHILE & DO
Condition based
i.e, run as long as the conditional part is True
[Offer valid till the stock lasts]

For...Next Statement
Repeats a group of statements a specified number of times.

15

infotica
vbafaculty@gmail.com

Syntax
For counter = start To end [Step step]
[statements]
[Exit For]
[statements]
Next [counter]
The ForNext statement syntax has these parts:
Part

Description

counter

Required. Numeric variable used as a loop counter. The variable can't be a


Boolean or an array element.

start

Required. Initial value of counter.

end

Required. Final value of counter.

step

Optional. Amount counter is changed each time through the loop. If not
specified, step defaults to one.

statements

Optional. One or more statements between For and Next that are executed
the specified number of times.

Remarks
The step argument can be either positive or negative. The value of the step
argument determines loop processing as follows:
Value

Loop executes if

Positive or 0

counter <= end

Negative

counter >= end

After all statements in the loop have executed, step is added to counter. At this
point, either the statements in the loop execute again (based on the same test
that caused the loop to execute initially), or the loop is exited and execution
continues with the statement following the Next statement

Sub print1to10()
'in immediate window
Dim i As Integer
For i = 1 To 10
'the default STEP value is 1
Debug.Print i
Next
End Sub

You might also like