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

Post on 21-Jan-2016

215 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

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

goren@ch.bme.hugoren@ch.bme.hu

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

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

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

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)

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

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’

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

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 :)

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

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

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

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

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

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

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]

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

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

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

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

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

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

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

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

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

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

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

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

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)

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!!

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”

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

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

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

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

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

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

top related