+ All Categories
Home > Documents > Scope of Variables and Constants A Variable or Constant may exist and be Visible for an entire...

Scope of Variables and Constants A Variable or Constant may exist and be Visible for an entire...

Date post: 21-Dec-2015
Category:
View: 217 times
Download: 0 times
Share this document with a friend
Popular Tags:
40
Scope of Variables and Constants A Variable or Constant may exist and be Visible for an entire project, for only one form, or for only one procedure Therefore, the visibility of a variable or constant is referred to as its Scope Visibility means that “can this variable be seenin this location The scope of a variable or constant is said to be Global, Module (Form) Level, or Local
Transcript

Scope of Variables and Constants

A Variable or Constant may exist and be Visible for an entire project, for only one form, or for only one

procedure

Therefore, the visibility of a variable or constant is referred to as its Scope

Visibility means that “can this variable be seen” in this location

The scope of a variable or constant is said to be Global, Module (Form) Level, or Local

Module Level variables or constants are accessible from all procedures of a Form

A Local variable or constant may be used only within the procedure in which it is declared

The Scope of a Variable declared with a DIM statement is determined by where the declaration statement is made

The Lifetime of a Variable is the period of time that the variable exists

The Lifetime of a Local variable is normally one execution of the procedure

The Lifetime of a Module Level variable is the entire time the Form is Loaded (generally the lifetime of the entire project)

Local Declarations

• Any variable you declare inside a procedure• The lifetime of the variable is one execution of

the procedure• Each time you execute (e.g. click on a command

button) a procedure, the local DIM statements are executed.

• Each variable is created as a “fresh” new one with an initial value of 0 for numeric datatypes or “” for string

• When the procedure finishes, its variables disappear, their memory locations are released

Local Declarations

Module-Level Declarations

• When you need to use a variable or constant in more than one procedure of a form

• Declare at module-level

[General] [Declarations]

Module-Level Declarations

Global Variables• Though you can declare global variables anywhere,

convention dictates that public variables be placed only in the standard code module.

• Examples of global and module level declarations in a SCM:– Public gcurTotalSalary as Currency 'global variable– Public Const gcurTAX_RATE as Single = .082 'global

constant– Dim mcurMySalary as Currecy 'module-only

variable

• If a procedure were to contain a variable declared locally whose name is the same as a global variable (a violation of unwritten convention for variable naming), then the local variable takes precedence. A local variable, when in scope, always preempts use of a global variable.

• The Private statement is rarely used, because that is the default (for “Dim”)

Static Variables

• Static variables are local to a procedure but retain their value for the life of a project. They are often used inside a procedure that counts things and must maintain that count. Static variables are initialized once only. Thereafter they are not initialized during the project:– Private Sub Something()– Static intCount as Integer 'initialized to 0 once

– intCount = intCount + 1 'remembered across invocations

– ···– End Sub

Standard Code Modules• Public procedures are“visible” to all forms• Public variables are visible to all forms• SCM has the extension .BAS• Create SCM: Project, Add Module• DIM variables in the code module are visible to

all procedures in the module, but not to procedures in the form modules.

• SCM modules do not have any event procedures because SCM has no events to which it can react. The SCM only has code and procedures.

Identifiers

• When you use variables and constants, it is important that you know their scope. Good programming practice to include scope information in naming conventions

• Use ‘m’ as a prefix to identify module-level declarations

• Use ‘g’ to identify variables with global scope

Multi-Form ProjectsWorking with more than one form in a project

The first form that VB displays is called the STARTUP FORM

To add another form; Project Menu/Add Form or select the icon from the shortcut toolbar

This form will be added to the project, and cam be viewed from the Project Explorer Window

Each form is a separate entity, and the code exists and is related only to the specific form

To move between each form:

FORMNAME.SHOWFORMNAME.HIDE

Form style can be 1 (modal) or the default value 0 (nonmodal)

Variables & Constants in Multi-form Projects

• Scope of variables:– Local: available inside a procedure– Static: inside procedure, but remembered– Module level: available anywhere in a form– Global: available across forms--anywhere

• Global variables declared with Public

• Variable prefix naming conventions: m for module, g for global

• Scope a variable as narrowly as possible

Referring to Other Forms’ Objects

• You can refer to txtName in another form called frmSummary this way:

frmSummary!txtName = …

or frmSummary!txtName.Font.Name = ...

• This implies that control names are unique within a form but need not be unique across forms.

An About Box• Acts like a Windows Help|About box

• Often displays information about the programmers, designers, and so on

• An about box is simply a modal form with an OK button and label boxes displaying information

• You can use VB’s About Dialog template

A Splash Screen

• Splash screen displays while product loads

• Create: Project, Add Form, then select Splash Screen

• Splash screen loads first instead of main form

• Place splash screen load statement in Sub Main procedure in Standard Code Module

Writing General Procedures

• Often you will encounter programming situations in which multiple procedures perform the same operation

• This condition can occur when the user can select either a command button or a menu option to do the same thing

• Instead of retyping the code, you can write reusable code in a general procedure and call it from both event procedures

General Procedures• General procedures respond when

specifically called by other procedures

• They are not event driven

• They are used to “package” a commonly used series of instructions

• Invoke general procedures by calling them

• Select Tools, Add Procedure to insert one

Creating a New Sub Procedure

• STEP 1: Display the Code window for the form

• STEP 2: Select Add Procedure from the Tools menu

• STEP 3: Enter a name in the Add Procedure dialog box

• STEP 4: Select Private for Scope. Choosing Public makes a procedure available from other project modules. Note: Leave the Type set to sub for now

• STEP 5: Click OK

•Unlike event procedures you have used up to this point, general procedures must be explicitly called.

•You can create procedures or functions

•Functions return a single value, procedures do not

•Both functions and sub procedures can have arguments

•You pass information into a sub procedure or a function through its arguments

• Arguments must be typed in the prototype:– Private Sub DoSomething(Arg1 as String, Arg2 as

Integer)– •••– End Sub

• Functions are typed in addition to their arguments:

• Private Function CalcInterest(Arg1 as Currency) As Currency– CalcInterest = <expression> 'return answer this way

• End Function• Place functions in same place as event sub

procedures

Passing Variables to Procedures

• You may need to use the value of a variable in one procedure, and also in a second procedure that is called from the first. You could declare the variable as module level, but that approach makes it visible to all other procedures. You can keep the scope as narrow as possible by declaring it locally and passing it to any called procedures

Functions vs. Sub Procedures

• A sub procedure is a procedure that performs actions.

• A function procedure may perform an action, but it also returns a value (the return value) to the point from which it is called

• Examples of function declaration:

Private Function curCommission(ByVal curSalesAmount As Currency) As Currency

If curSalesAmount < 1000 Then curCommission = 0 ElseIF curSalesAmount <= 2000 Then curCommission = .15 * curSalesAmount Else curCommission = .20 * curSalesAmount End IfEnd Function

Calling the Commission Function:Dim curSales as CurrencyIf IsNumeric(txtSales.Text) Then

curSales = Val(txtSales) lblCommission.Caption = curCommission(curSales)

End If

Note: Name of argument being passed

Private Function curCommission(ByVal curSalesAmount As Currency) As Currency

If curSalesAmount < 1000 Then curCommission = 0 ElseIF curSalesAmount <= 2000 Then curCommission = .15 * curSalesAmount Else curCommission = .20 * curSalesAmount End IfEnd Function

Name of argument received

• Notice in the preceding example that the argument named in the function does not have the same name as the argument named in the function definition.

• When the function is called, a copy of curSales is passed to the function and is assigned to the named argument, curSales Amount.

• As the calculations are done (inside the function), for every reference to curSalesAmount, the value of curSales is actually used.

Passing Variables to Procedures

• You may need to use the value of a variable in one procedure and also in a second procedure that is called from the first

• You could declare the variable as Module level, but that approach makes the variable visible to all procedures

• To keep the scope of the variable as narrow as possible, consider declaring the variable as local and passing it to any called procedures

Passing arguments ByVal and ByRef

• When you pass an argument you may pass it ByVal or ByRef.

• The ByVal sends a copy of the argument’s value to the procedure so that procedure cannot alter the original value.

• ByRef sends a reference indicating where the value is stored in memory, allowing the called procedure to actually change the argument’s original value.

Passing arguments ByVal and ByRef

• You can specify how you want to pass the argument by using the ByVal or ByRef keyword before the argument.

• If you don’t specify ByVal or ByRef, arguments are passed by reference.

Private Sub Commission(ByVal curSalesAmount As Currency)

Len and InStr Functions

• The functions Len and InStr operate on strings but produce numbers

• The function Len gives the number of characters in a string.

• The function InStr searches for the occurrence of one string in another and gives the position at which the string is found

• Both functions return a value

ExamplesLen(“UCC”) is 3

Len(“University College Cork”) is 23

Len(“ ”) is 0

InStr(“Cork”, “University College Cork”) is 20

InStr(“ ”, “University College Cork”) is 11

InStr(“city”, “University College Cork”) is 0


Recommended