Object Oriented Programming A programming concept which views programs as objects with properties...

Preview:

Citation preview

Object Oriented Programming

A programming concept which views programs as objects with properties and ways to manipulate the object and the properties.

Visual Basic

Objects / Properties / Methods

Property Adjective

Object Noun Part of the application

Attribute

Method Verb Action to dosomething

Visual Basic

Range (“A3”).select

Range is an object

select is a method

(“A3”) is a modifier for the object

Note that object separated from method by a .

Activesheet.name

Activesheet is an object

name is a property

Visual Basic

The result is the name of the active sheet

Procedures

Sub procedures return no values

Function procedures return a value

Function Procedures

Function Grade (exam1,exam2,exam3) as String

Sum = exam1+exam2+exam3

If sum > 95 then Grade = “A”Else if sum > 80 Grade = “B”Else Grade = “C”End if

End Function

The function name must be assigned the value to be returned!

Arguments to a function must be in the order specifiedin the function description:

Function Grade (exam1,exam2,exam3) as String

= Grade (90, 80, C5)

Note the “as String” to declare the type of value returned bythe function.

Sub Procedures

Sub Gc()‘ Lines beginning with ‘ are comments' Gc Macro' Puts gc in active cell & units in adjacent cell to right' Keyboard Shortcut: Ctrl+g' ActiveCell.FormulaR1C1 = "32.174" ActiveCell.Offset(0, 1).Range("A1").Select ActiveCell.FormulaR1C1 = "ft-lbm/lbf-s^2"End Sub

This was a recorded macro – macros are “Sub” procedures.

Review of some Excel Basics

Cell references of two types:

A1 Columns are alphabetic, rows are numeric

R1C1 R number Column number

B2 and R2C2 refer to the same cell

Can be set by the Tools / Options menus

(Note that the two methods are transposed –A1 – column first, then row R1C1 – row first, then column )

Formulae in Excel (A1 style)

A1 is a relative address --- it changes when the formula is copy /pasted

$A$1 is an absolute address --- it does not change via copy / paste

And can use mixed mode:

A$1 – A is relative, $1 is absolute

$A1 – A is absolute, 1 is relative

Formulae in Excel (R1C1 style)

R1C1 is an absolute address – it does not change under copy / paste

R[1]C[1] is a relative address – it does change under copy /paste

And can use mixed mode:

R1C[1] – R1 is absolute,

C[1] is relative

In VBA, can use either or both A1 and R1C1 styles

A1 style tends to be absolute

A1 style used with the “Range” property

Range(“A4”)

Can refer to individual cells with the “Cells” Property, which uses an R1C1 style

Cells(4,1)

In Excel, cells & ranges can be namedInsert / name menu

These names can be used in FormulaeVBA

VBA Variable Types

String A sequence of bytes containing charactersInteger 2 byte integerLong 4 byte integerSingle 4 byte real numberDouble 8 byte real numberVariant Can hold anything (but “expensive” to use)“Object” A class of data types used by Excel/VBA

Characters & Stings

For Excel, anything that is not a number or a formula is a string. If want a set of digits as a string, need to enclose in quote or quotation marks.

For VBA, need to define variable that will hold strings as string data types

Good programming practice is to declareall variables and their types via the“Dim” statement.

Visual Basic

Sub NameIt()Dim newname as Stringnewname = InputBox(“Enter a name for the worksheet”)

ActiveSheet.Name=newnameEnd Sub

“Object” data type

Many of the objects in Excel have their owndata type:

Dim r as RangeDim q as WorksheetDim z as Chart

About the only one we will use is the “Range”data type.

Option Explicit

Forces you to ‘Dim’ all variables

Helps prevent typos

Can set this as the default through the Tools/ Options menu.

Require variable declaration check box)

Visual Basic

All objects have properties

Most objects have methods

Will work with only a few of the many objects, methods and properties

To get a list of objects and properties, invoke the Object Browser

Visual Basic

Some of the objects

WorkbookWorksheetActiveSheetRangeFormChart

Note --- a “Cell” is not an object, but is a type of range object

Visual Basic

And to further confuse the issue objects can have objects as properties

And objects can be grouped into collections

Workbook = collection of worksheets

Visual Basic

Object Browser --- Just for a quick look

In VBA, press F2 or “View / Browser”

Select Excel from library list

Enter an object in the second list box

Use “F1” to get help on an object

Program module (Sub or Function) is made up of a series of steps to accomplish a task. Five major categories of steps:

Input /Output operations(Which are really calls to other modules)

Read 5, A

Assignment statements A = 5

Conditional statements If ( A > 5) then ….

Calls to other modules A = sqrt (12)

Iteration Statements For I = 1 to 6 … Next i

Expression evaluation inVBA

Operators in priority orderLeft to right

Operator Priority List ( )^- (unary minus)* /+ -

Comparison Operators (>, < …)

Logical Operators (NOT, AND, OR…)

Test = 2 + 3 ^2 > 5 AND (3-7)*2 > 6

(3-7) -43^2 9-4*2 -89+2 1111 > 5 True-8 > 6 FalseTrue AND False False

Thus, Test has the value “False”

Conditional Expressions

If / then / else end if

Select case …. End Case

If (expression) then

One or more expressions

else

One or more expressions

end if

If (expression ) then (expression)

Simple form

Select Case testexpression[Case expressionlist-n[statements-n]] ...

[Case Else[elsestatements] ]

End Select

Select Case Statement

Like a complex If / Then / ElseIf … / EndIf

We will not use it

Iteration Statements Used to execute a number of

statements repeatedly

Two major types ---For / Next Do / Loop

For counter to upperlimt step sizeStatements

Next counter

For Each cell In Selection Statements

cell.value = expression

Next cell

Note that “value” is a property of the “cell” object and is thecontents of the cell

Do while expression_is_true StatementsLoop

Do Statements

Loop while expression_is_true

Do Until expression_is_true StatementsLoop

Do Statements

Loop Until expression_is_true

To add develop a function (or sub)

First determine what function (or sub ) is to do, the steps to do it, and the needed arguments.

In VB, Insert

ModuleInsert

ProcedureSelect desired type Type name

Add arguments to argument list

To add develop a function (or sub)

Dim all variables

Write the code

Return to Excel & test

Some Simple Examples

Compute the factorial of number

Compute the sine of an angle from the series expansion

Public Function NFact(N) As Double‘ Assumes N is an integer > 1Dim I As IntegerNFact = 1I = 1Do While I <= N NFact = NFact * I I = I + 1 Loop

End Function

Simple function to compute n!. There is a worksheet functionto do this (Fact(n), but calling it is complicated.

Function to compute the sine of an angle (in radians)

Use a Taylor series expansion about 0 radians

Sine =

n

i

ii

i

angle1

)12(1(

!12

)1(

Function will take two argument – the angle and n, then numberOf terms in the series. It will return the approximate value of the sine. (In theory, n should be∞ )

Public Function MySine(angle As Single, nterms As Integer) As Double‘ Declare the variables.Dim J As Integer

‘ Initialize the value to zeroMySine = 0.0

‘ Compute the value by evaluating each term in the sumJ = 1Do While J <= ntermsMySine = MySine + ((-1) ^ (J + 1)) * (angle ^ (2 * J - 1)) / (NFact(2 * J - 1))J = J + 1

Loop

End Function