variables / scope. variable memory location whose value can change as the program is running. used...

40
Variables / Scope

Upload: cori-murphy

Post on 18-Dec-2015

228 views

Category:

Documents


1 download

TRANSCRIPT

Variables / Scope

Variable

• Memory location whose value can change as the

program is running.

• Used to hold temporary information

• Used to control the type of data used in calculations– Val returns a Double-type, which is often larger than

necessary

• Can store only one piece of data at any time

• Data is processed faster

Data Types

• Byte• Boolean• Currency• Date• Double• Integer

• Long• Object• Single• String• Variant

Use the Appropriate Data Type

• Integer or Long - Used to store whole numbers

• Single, Double, Currency - Used to store numbers with a decimal fraction

• String - Used to store strings

• Boolean - Used to store Boolean values (True and False)

• Date - Used to store date and time information

• Object - Used to store a reference to an object

• Byte - Used to store binary data

• Variant - Flexible, but not efficient

Variable Names

• Should be meaningful

• First three characters should represent the data type

• Remainder of name should represent the variable’s purpose

Three-character Ids

• Byte byt• Boolean bln• Currency cur• Date/Time dtm• Double dbl• Integer int

• Long lng• Object obj• Single sng• String str• Variant vnt

Rules for Naming Variables

• Name must begin with a letter.

• Name can contain only letters, numbers, and the underscore. No punctuation characters or spaces are allowed.

• Name cannot exceeds 255 characters.

• Name cannot be a reserved word.

Creating (declaring) a Variable

• Dim variablename [As datatype]

• Public variablename [As datatype]

Assigning Values to Variables

• Assignment statement– variablename = value

• Examples: – sngHours = 38.5– curBonus = curSales * .1– strName = “Susan”

Constants

• Literal constant – an item of data whose

value cannot change while the program is running

• Examples: – 7

– “Janet”

• Symbolic constant– a memory location

whose contents cannot be changed while the program is running

• Examples: – conPi

– conRate

Scope of a Variable

• Indicates which procedures can use the variable

• Determined by where the Dim or Public statement is entered.

• Can be either global, form-level, or local.

Variable Scope

Global Variable: Defined using a Public declaration in the general declarations section of a module

Module/FormVariable: Defined using a Private or dim declaration in the general declarations section of a module or a form

Local Variable: defined using dim or static within a subprocedure or function

In general, when variables have the same name but different scope, the most local (closest) variable is used.

Local Variables

• Created with the Dim statement.• The Dim statement is entered in an object’s event

procedure (within a subprocedure or function)• Only the procedure in which it is declared can

use the variable.• Same name can be used in different procedures• Removed from memory when the procedure

ends.

Form-level Variables

• Created with the Dim statement.• The Dim statement is entered in a form’s General

declarations section. • Can be used by any of the procedures in the

form.• initialized when module/form is first opened

Removed from memory when the application ends.

Global Variables

• Created with the Public statement.• The Public statement is entered in a code module’s

General declarations section. • initialized when program starts• Used in multi-form projects and can be used by any

of the procedures in any of the project’s forms.• Removed from memory when the application ends.

Static Variables

• Static variables– defined using static instead of dim within a

subprocedure or function– acts like a local but is initialized only on first

use

Static Variable example

• Goal: count the number of times a routine is entered

private sub command1_click()dim counter as integercounter=counter+1debug.print counterend sub

• Does NOT work unless counter is declared using static instead of dim

Local vs Static Variables

• A local variable is defined in an event procedure, and it is removed from memory when that event procedure ends.

• A static variable also is defined in an event procedure, but it retains its value when that event procedure ends.

• A static variable is a special type of local variable.

Swapping

• To swap the contents of two variables:– assign the first variable’s value to a temporary

variable– assign the second variable’s value to the first

variable– assign the temporary variable’s value to the

second variable

Option Explicit Statement

• Doesn’t allow you to create variables “on the fly.”

• Enter in every form’s, and every code module’s, General declarations section.

• Use Tools, Options, Environment tab, Require Variable Declaration to have Visual Basic include Option Explicit in every new form and module.

Creating a Symbolic Constant

• A memory location whose value cannot change during run time.

• Syntax: [Public] Const constname [As datatype] = expression

• Examples:– Const conPi As Single = 3.141593– Public Const conMaxAge as Integer = 65

Scope of a Symbolic Constant

• Indicates which procedures can use the symbolic constant.

• Global: Public Const statement in a code module’s General declarations section.

• Form-level: Const statement in the form’s General declarations section.

• Local: Const statement in an event procedure.

Numeric Types

• Integer - 2 bytes of memour– a 16-bit signed integer – whole number between -32768 and 32767

• long - 4 bytes of memory– a 32-bit signed integer (+/- 2^31)– whole number between 2,147,483,648 and 2,147,483,648

• single - 4 bytes of memory– a single-precision decimal floating point number– +/- 1.401298e-45 to 3.402823e38

• double - - 8 bytes of memory– a double-precision decimal floating point number– +/- 4.94065645841247e-324 to 1.79769313486232e208

Arithmetic Operations (1)

• n=5 integer (long or short) or floating point• y=a+b y=a-b, y=a*b (add/subtract/multiply)• z=x / y divides two numbers and returns a

floating point • z=x mod y divides two numbers and returns only

the remainder.• z=x \ y divides two numbers and returns an

integer result

Arithmetic Operations (2)

• isnumeric(thing) returns TRUE if thing is numeric

• randomize(number) initializes the random number generator

• n=rnd(x) returns random number 0 <= x < 1• s=str(number) converts a number to a string• n=val(string) converts a string to a number• n=rgb(red,green,blue) returns RGB color value• n=sgn(x) returns 1,0,-1 if x is pos., zero, neg.

Boolean Operations (1)

• Consume 2 bytes of memory

• result = exp1 And exp2– true only if both exp1 AND exp2 are true

• result = expression1 or expression2– true if either or both exp1 OR exp2 are true

• result = NOT exp1– true if exp1 is false, false if expression is true

Comparisons

• x<y, x<=y, x=y, x<>y, x>y, x>=y where x, y can be strings or numbers

• y = a is b returns true if a & b are the same object• y = string like pattern• y=StrComp(string1, string2[, compare])

compares two strings based on the compare type• typeof object returns an object's type

– Can only be used as part of an if statement

if typeOf thing is label then thing.backcolor=vbGreen

String Operations

String Manipulation Functions

• Left(string, length)– returns the leftmost length characters in the

string

• Right(string, length) – returns the rightmost length characters in the

string

• Mid(string, start[, length])– returns length characters from string, beginning

with start

Instr Function

• Instr(start, string1, string2[,compare]– start is a numeric expression that sets the

starting position for the search– string1 is the string expression being searched– string2 is the string expression being sought– compare is either 0 (default; case-sensitive) or 1

(case-insensitive)– returns the starting position of string2 within

string1

Trim, LTrim, RTrim

• Trim(string) - removes leading and trailing spaces from a string

• LTrim(string) - removes leading spaces from a string

• RTrim(string) - removes trailing spaces from a string

String Concatenation

• Ampersand - &• Examples: (Assume strFirstName contains “Mary” and

sngSales contains 1000)

– “Hello “ & strFirstName– strFirstName & “ sold $“ & sngSales & “.”

• Results:– Hello Mary– Mary sold $1000.

String Operations (1)

• Strings consume 0-2 Billion bytes of memory, but on;y as much as needed - very efficient

• s=“Strings are always defined in quotes”• & - String coercion and concatenation• s=str(number) converts the number to a string• n=val(string) tries to convert the string to a number• s=ucase(string) converts string to upper case• s=lcase(string) converts string to lower case• string1=lset(string2) left justifies string2 in string1with

trailing spaces (there is also an rset)

String Operations (2)

• n=asc(string) converts first character to a 0-255 ASCII character code

• s=chr(character-code) returns a string containing the respective character

• s=hex(num) returns the hex value of num as a string (oct returns octal value)

• s=inputbox(prompt, title) Displays a prompt in a dialog box, waits for the user input and returns a String containing the contents of the text box

String Operations (3)

• n=len(string) returns integer length of string• s=ltrim(string) removes leading spaces• s=rtrim(string) removes trailing spaces• s=trim(string) removes surrounding spaces• s=space(n) returns a string of n spaces• s=left (string,n) returns the left n characters of

string• s=right(string,n) returns the right n characters of

string

String Operations (4)

• s=mid(string,start,n) Returns n characters beginning at character #start

• Mid(stringvar, start[, n]) = str2 replaces n characters in stringvar with characters in str2

• n=InStr(string1, string2) searches for string2 inside string1 and returns the integer position of the start

• s=string(n,char) returns an n-character string filled with char

Date / Time / Misc

Date/Time related Statements

• Date Data Types consume 8 bytes of memory• Date comparison - if somedate < #12/31/1993# then ….• d = Now - returns system date and time as date type• d = date - returns system date as date type• d$ = date$ - returns system date as string• d = time - returns system time as a date type• time = valid-time - sets the system time !!!!!!!!!!!!!• d$ = time$ - returns system time as a string• i = timer - integer number of seconds since midnight• n=weekday|month|day|year (date) Returns whole number

representing the weekday|month|day|year

• DateAdd() – Add value to a date• DateDiff() – Returns difference between 2 dates• DatePart() – Return parts from a date• Dim FirstDate As Date• Dim K As String • Dim N As Integer • Dim Msg • k= "m" ‘we will be adding months to our date • FirstDate = InputBox("Enter a date") ‘like 9/1/2001 • N = InputBox("Enter number of months to add") • Msg = "New date: " & DateAdd(k, N, FirstDate) • MsgBox Msg • The above program will return 12/1/2002 when we add 15

(months) to 9/1/2001. If k =“d”, and it will add days.

Misc

• beep - beeps the computer’s speaker (sort of)• n=vartype(variable) returns an integer

corresponding to variable type• n=rgb(red,green,blue) sets n to a long integer

representing a color made up of red, green, blue (0-255). 0,0,0 = black 255,255,255 = white

• n=qbcolor(x) where x is one of the 16 Quick Basic colors 0-15