compmathbsc, english 5 october 2006 programming basics — continued arrays cycle statements:...

37
CompMathBSc, English CompMathBSc, English 5 October 2006 5 October 2006 Programming basics — continued Programming basics — continued Arrays Arrays Cycle Statements: Loops Cycle Statements: Loops Control Structures vs Conditions Control Structures vs Conditions Subs: Procedures and Functions Subs: Procedures and Functions File and data management (I/O) File and data management (I/O) Using the Object Browser Using the Object Browser First look on the IDE First look on the IDE [email protected] [email protected] u u

Upload: ira-potter

Post on 21-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

CompMathBSc, EnglishCompMathBSc, English

5 October 20065 October 2006

CompMathBSc, EnglishCompMathBSc, English

5 October 20065 October 2006

Programming basics — continuedProgramming basics — continued

ArraysArrays Cycle Statements: LoopsCycle Statements: Loops Control Structures vs ConditionsControl Structures vs Conditions Subs: Procedures and FunctionsSubs: Procedures and Functions File and data management (I/O)File and data management (I/O) Using the Object BrowserUsing the Object Browser First look on the IDEFirst look on the IDE

Programming basics — continuedProgramming basics — continued

ArraysArrays Cycle Statements: LoopsCycle Statements: Loops Control Structures vs ConditionsControl Structures vs Conditions Subs: Procedures and FunctionsSubs: Procedures and Functions File and data management (I/O)File and data management (I/O) Using the Object BrowserUsing the Object Browser First look on the IDEFirst look on the IDE

[email protected]@ch.bme.hu

Page 2: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

2/38

Constants (remark)Constants (remark)Constants (remark)Constants (remark)

Convention: use BLOCK letters to name constants e.g. Dim MYCONST = 100 easily recognised

Convention: use BLOCK letters to name constants e.g. Dim MYCONST = 100 easily recognised

Page 3: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

3/38

ArraysArraysArraysArrays

Problem: individual values that should be stored together data of the same type e.g. names of people in a class

Solutions:1. User-defined type (looser)2. Collection (even more looser)3. Array (tight) – a special collection

Problem: individual values that should be stored together data of the same type e.g. names of people in a class

Solutions:1. User-defined type (looser)2. Collection (even more looser)3. Array (tight) – a special collection

Page 4: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

4/38

Types of ArraysTypes of ArraysTypes of ArraysTypes of Arrays

Like by variables: Integer, Long -- usual Single, Double String Boolean –- rare Variant -- very rare

= types of values stored in the array must be of the same type

Like by variables: Integer, Long -- usual Single, Double String Boolean –- rare Variant -- very rare

= types of values stored in the array must be of the same type

Page 5: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

5/38

Dimensions – 1D, 2D, ...Dimensions – 1D, 2D, ...Dimensions – 1D, 2D, ...Dimensions – 1D, 2D, ...

1D array of 100: [1.00;2.82;3.63;4.11;..;100.75]

2D array of (3;5): [1 2 3 4 5 10 20 30 40 50 8 5 1 3 9]

= 3 rows and 5 columns --> 3x5 matrix 3D array: a cube 4D, 5D, 6D... (rare)

1D array of 100: [1.00;2.82;3.63;4.11;..;100.75]

2D array of (3;5): [1 2 3 4 5 10 20 30 40 50 8 5 1 3 9]

= 3 rows and 5 columns --> 3x5 matrix 3D array: a cube 4D, 5D, 6D... (rare)

Page 6: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

6/38

DeclarationDeclarationDeclarationDeclaration

Syntax:Dim MyArray(100) As Single Dim My2DArray(3,5) As Integer

and also:Dim MyArray(1 to 25) As SingleDim My2DArray(3, 8 to 12) As Integer

UBound(), LBound() Option Base 1

Syntax:Dim MyArray(100) As Single Dim My2DArray(3,5) As Integer

and also:Dim MyArray(1 to 25) As SingleDim My2DArray(3, 8 to 12) As Integer

UBound(), LBound() Option Base 1

Page 7: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

7/38

ElementsElementsElementsElements

just like individual variables identified by an index

e.g. ReadElement = MyArray(12) ReadElement must be a variable of the right

type MyArray must have an index of 12 ‘Subscript out of range’

just like individual variables identified by an index

e.g. ReadElement = MyArray(12) ReadElement must be a variable of the right

type MyArray must have an index of 12 ‘Subscript out of range’

Page 8: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

8/38

Value assignmentValue assignmentValue assignmentValue assignment

I want the element of index 5 to be 8.314:

MyArray(5) = 8.314 with a string array:

MyStringArray(5) = ”8.314” filling up an array: with cycles (loops)

use For .. Next

I want the element of index 5 to be 8.314:

MyArray(5) = 8.314 with a string array:

MyStringArray(5) = ”8.314” filling up an array: with cycles (loops)

use For .. Next

Page 9: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

9/38

Dinamic ArraysDinamic ArraysDinamic ArraysDinamic Arrays

Problem: I don’t know the size of the array I need in design-time (depends on user input)

Solution: redimensioningSyntax: first: Dim MyDinArray()

later: ReDim MyDinArray(Rows, Cols) where Rows & Cols are variables (!)

= an elastic bag :)

Problem: I don’t know the size of the array I need in design-time (depends on user input)

Solution: redimensioningSyntax: first: Dim MyDinArray()

later: ReDim MyDinArray(Rows, Cols) where Rows & Cols are variables (!)

= an elastic bag :)

Page 10: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

10/38

LoopsLoopsLoopsLoops

Use-case: a block of statements must be repeated many times

Loop types: For .. Next --> I have a fix number (e.g. 25) Do .. Loop --> I have a limiting condition

Use-case: a block of statements must be repeated many times

Loop types: For .. Next --> I have a fix number (e.g. 25) Do .. Loop --> I have a limiting condition

Page 11: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

11/38

For .. NextFor .. NextFor .. NextFor .. Next

to run a block of statements a definite number of times e.g. 25

e.g. to fill up an array

For CurrentIndex = 1 To 32MyArray(CurrentIndex) =

CurrentIndex – 1Next CurrentIndex

to run a block of statements a definite number of times e.g. 25

e.g. to fill up an array

For CurrentIndex = 1 To 32MyArray(CurrentIndex) =

CurrentIndex – 1Next CurrentIndex

Page 12: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

12/38

For .. NextFor .. NextFor .. NextFor .. Next

Syntax example:For Count = 1 To 25

[statement1][statement2]

...[statementN]

Next Count

Syntax example:For Count = 1 To 25

[statement1][statement2]

...[statementN]

Next Count

Page 13: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

13/38

For .. NextFor .. NextFor .. NextFor .. Next

Stepping up (Step 2) or down (Step -2):

For Count = 1 To 30 Step 2 ’run 15 times

[statement1][statement2] ...[statementN]

Next Count

Stepping up (Step 2) or down (Step -2):

For Count = 1 To 30 Step 2 ’run 15 times

[statement1][statement2] ...[statementN]

Next Count

Page 14: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

14/38

Do .. LoopDo .. LoopDo .. LoopDo .. Loop

to run a block of statements an indefinite number of times

evaluates a condition to determine whether or not to continue running

types:1. evaluates at the start

While / Until

2. evaluates at the end While / Until

to run a block of statements an indefinite number of times

evaluates a condition to determine whether or not to continue running

types:1. evaluates at the start

While / Until

2. evaluates at the end While / Until

Page 15: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

15/38

Do .. Loop (1.)Do .. Loop (1.)Do .. Loop (1.)Do .. Loop (1.)

Syntax: (! logically opposites !)

Do While [Condition=True][block of statements]

Loop

Do Until [Condition=True][block of statements]

Loop

Syntax: (! logically opposites !)

Do While [Condition=True][block of statements]

Loop

Do Until [Condition=True][block of statements]

Loop

Page 16: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

16/38

Do .. Loop (2.)Do .. Loop (2.)Do .. Loop (2.)Do .. Loop (2.)

Syntax: (! logically opposites !)

Do [block of statements]

Loop While [Condition=True]

Do[block of statements]

Loop Until [Condition=True]

Syntax: (! logically opposites !)

Do [block of statements]

Loop While [Condition=True]

Do[block of statements]

Loop Until [Condition=True]

Page 17: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

17/38

Nested loopsNested loopsNested loopsNested loops

Two or more loops in one another:Do Until Error < 0.001

[statement1]For Count = 1 To 100

[block]Next Count[more statements]

Loop

Two or more loops in one another:Do Until Error < 0.001

[statement1]For Count = 1 To 100

[block]Next Count[more statements]

Loop

Do not nest in more than 3-4 levels depth

Do not nest in more than 3-4 levels depth

Page 18: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

18/38

Dealing with conditionsDealing with conditionsDealing with conditionsDealing with conditions

evaluating a condition: True/False or Cases

branching: 2, 3, 4 ... N selection structure:

2 branches (T/F) --> If..Then..Else 3-4 branches --> If..Then..ElseIf..Else more branches --> Select Case

evaluating a condition: True/False or Cases

branching: 2, 3, 4 ... N selection structure:

2 branches (T/F) --> If..Then..Else 3-4 branches --> If..Then..ElseIf..Else more branches --> Select Case

Page 19: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

19/38

If..Then..ElseIf..Then..ElseIf..Then..ElseIf..Then..Else

Syntax:If [Condition=True] Then [block of statements]Else ‘this happens if

Condition=False [another block of statements]

End If

Syntax:If [Condition=True] Then [block of statements]Else ‘this happens if

Condition=False [another block of statements]

End If

Page 20: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

20/38

If..Then..ElseIf..ElseIf..Then..ElseIf..ElseIf..Then..ElseIf..ElseIf..Then..ElseIf..Else

Syntax:If [Condition1 = True] Then [block of statements]1

ElseIf [Condition2 = True] Then [block of statements]2

ElseIf [Condition3 = True] Then [block of statements]3

Else ‘this happens if all Conditions are False

[block of statements]4

End If

Syntax:If [Condition1 = True] Then [block of statements]1

ElseIf [Condition2 = True] Then [block of statements]2

ElseIf [Condition3 = True] Then [block of statements]3

Else ‘this happens if all Conditions are False

[block of statements]4

End If

Page 21: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

21/38

Select CaseSelect CaseSelect CaseSelect Case

Syntax:Select Case [MyVariable] Case [Value1]

[block of statements]1

Case [Value2] [block of statements]2 …

Case [ValueN][block of statements]N

Case Else[else-block of statements]

End Select

Syntax:Select Case [MyVariable] Case [Value1]

[block of statements]1

Case [Value2] [block of statements]2 …

Case [ValueN][block of statements]N

Case Else[else-block of statements]

End Select

Page 22: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

22/38

In one rowIn one rowIn one rowIn one row

in simple cases:

If [Condition=True] Then [statement]1 Else [statement]2

in simple cases:

If [Condition=True] Then [statement]1 Else [statement]2

Page 23: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

23/38

Nested IfNested IfNested IfNested If

If..Then..(ElseIf..)Else structures can be nested into each other, but consider the extent of this:

If [Condition1 = True] Then [block of statements]1

If [Condition2 = True] Then [block of statements]2

End If [block of statements]3

Else [block of statements]4

End If

If..Then..(ElseIf..)Else structures can be nested into each other, but consider the extent of this:

If [Condition1 = True] Then [block of statements]1

If [Condition2 = True] Then [block of statements]2

End If [block of statements]3

Else [block of statements]4

End If

Page 24: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

24/38

Organization of codeOrganization of codeOrganization of codeOrganization of code

Scope (Subs and variables) Private or Public (Global)

Return value no return value --> Procedure (Sub) yes, of a specified type --> Function

Modules and Forms WorkBook Object > WorkSheet Object

Scope (Subs and variables) Private or Public (Global)

Return value no return value --> Procedure (Sub) yes, of a specified type --> Function

Modules and Forms WorkBook Object > WorkSheet Object

Page 25: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

25/38

ScopeScopeScopeScope

Private seen within the current Sub

Public (default) seen within the current Module

Global only for variables seen from anywhere hazard! --> rare

Private seen within the current Sub

Public (default) seen within the current Module

Global only for variables seen from anywhere hazard! --> rare

Page 26: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

26/38

ProcedureProcedureProcedureProcedure

no return value (usually) General form:

Public Sub SubName([Arg1], [Arg2])

[statements]End Sub

no return value (usually) General form:

Public Sub SubName([Arg1], [Arg2])

[statements]End Sub

Page 27: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

27/38

FunctionFunctionFunctionFunction

Syntax:Public Function MyFunction(MyArg As Integer) As Integer

[statements] End Function

Value: reached under the name MyFunction e.g. MyFunction = 5 * MyArg

Syntax:Public Function MyFunction(MyArg As Integer) As Integer

[statements] End Function

Value: reached under the name MyFunction e.g. MyFunction = 5 * MyArg

Page 28: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

28/38

Handling eventsHandling eventsHandling eventsHandling events

Event Watching in Windows (auto) Event --> warns all programs running Handled event: procedure call

e.g. Private Sub Workbook_Activate() … End Sub

Event Watching in Windows (auto) Event --> warns all programs running Handled event: procedure call

e.g. Private Sub Workbook_Activate() … End Sub

Page 29: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

29/38

File managementFile managementFile managementFile management

open files read from files write to files

we will use only text files (txt)

open files read from files write to files

we will use only text files (txt)

Page 30: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

30/38

File managementFile managementFile managementFile management

FileNum = FreeFile ‘Integer, 0-255Open ”MyText.txt” As #FileNum Access

Read[do something with data]

Close #FileNum ‘Never forget!!

FileNum = FreeFile ‘Integer, 0-255Open ”MyText.txt” As #FileNum Access

Read[do something with data]

Close #FileNum ‘Never forget!!

Page 31: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

31/38

Data output (in xls)Data output (in xls)Data output (in xls)Data output (in xls)

Cells(Row,Col)=”Message”Cells(Row,Col)=”Message”

Page 32: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

32/38

VB for Excel IDEVB for Excel IDEVB for Excel IDEVB for Excel IDE

Project Explorer Properties Window Working area Immediate Window ToolBox (on the WorkSheet) Toolbars: Standard, Debug, Edit,

UserForm Object Browser

Project Explorer Properties Window Working area Immediate Window ToolBox (on the WorkSheet) Toolbars: Standard, Debug, Edit,

UserForm Object Browser

Page 33: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

33/38

Object BrowserObject BrowserObject BrowserObject Browser

tree structure functions and parameters

IsNumeric(), Left(), Right(), Mid(), Trim(), CStr(), Cint(), …

return types to use a function in a branch:MyCosValue = VBA.Math.Cos(MyDoubleVar)

... use dots between levels

tree structure functions and parameters

IsNumeric(), Left(), Right(), Mid(), Trim(), CStr(), Cint(), …

return types to use a function in a branch:MyCosValue = VBA.Math.Cos(MyDoubleVar)

... use dots between levels

Page 34: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

34/38

InputBox()InputBox()InputBox()InputBox()

Built-in function Syntax:MyNewValue = InputBox(Prompt, Title,

Default)String variable Question Def.

value

Built-in function Syntax:MyNewValue = InputBox(Prompt, Title,

Default)String variable Question Def.

value

Page 35: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

35/38

Readable codeReadable codeReadable codeReadable code

End of statement: auto Begin each statement in a new row

e.g. 2 statements in a row: [statement1] : [statement2]

Groups: statments with a similar function e.g. declarations, output statements, value

assignments etc.

Loops: start lines with a Tab inside

End of statement: auto Begin each statement in a new row

e.g. 2 statements in a row: [statement1] : [statement2]

Groups: statments with a similar function e.g. declarations, output statements, value

assignments etc.

Loops: start lines with a Tab inside

Page 36: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

36/38

Literature onlineLiterature onlineLiterature onlineLiterature online

You can find the links on our site, just do not forget to do look it up;).

VisualBasic.about.com MSDN VB eBook VBA Tutorial (with example)

+ The 10 Commandments of VB

You can find the links on our site, just do not forget to do look it up;).

VisualBasic.about.com MSDN VB eBook VBA Tutorial (with example)

+ The 10 Commandments of VB

Page 37: CompMathBSc, English 5 October 2006 Programming basics — continued  Arrays  Cycle Statements: Loops  Control Structures vs Conditions  Subs: Procedures

See you next week:)See you next week:)See you next week:)See you next week:)