Sie sind auf Seite 1von 7

Variables

Before using variables, you have to set aside memory space for themafter all, thats what they are,locations in memory. Usually, you use the Dim statement to declare variables, although you can also use the Private (declare a private variable), Public (declare a global variable), Static (declare a variable thatholds its value between procedure calls), ReDim (redimension a dynamic array), or Type (declare a userdefinedtype) keywords to declare variables

Visual Basic Data Types Data Type Boolean Integer Long (Integer) Single (Floating) Double (Floating) Currency Date Object String Variant Variable Declaration There are three ways for a variable to be typed (declared): 1. Default 2. Implicit 3. Explicit If variables are not implicitly or explicitly typed, they are assigned the variant type by default. The variant data type is a special type used by Visual Basic that can contain numeric, string, or date data. To implicitly type a variable, use the corresponding suffix shown above in the data type table. For example, TextValue$ = "This is a string" creates a string variable, while Amount% = 300 creates an integer variable. There are many advantages to explicitly typing variables. Primarily, we insure all computations are properly done, mistyped variable names are easily spotted, and Visual Basic will take care of insuring consistency in upper and lower case letters used in variable names. Because of these advantages, and because it is good programming practice, we will explicitly type all variables. Suffix None % & ! # @ None None $ None

To explicitly type a variable, you must first determine its scope. There are four levels of scope: _ Procedure level _ Procedure level, static _ Form and module level _ Global level Within a procedure, variables are declared using the Dim statement: Dim MyInt as Integer Dim MyDouble as Double Dim MyString, YourString as String Procedure level variables declared in this manner do not retain their value once a procedure terminates. To make a procedure level variable retain its value upon exiting the procedure, replace the Dim keyword with Static: Static MyInt as Integer Static MyDouble as Double Form (module) level variables retain their value and are available to all procedures within that form (module). Form (module) level variables are declared in the declarations part of the general object in the form's (module's) code window. The Dim keyword is used: Dim MyInt as Integer Dim MyDate as Date Global level variables retain their value and are available to all procedures within an application. Module level variables are declared in the declarations part of the general object of a module's code window. (It is advisable to keep all global variables in one module.) Use the Global keyword: Global MyInt as Integer Global MyDate as Date What happens if you declare a variable with the same name in two or more places? More local variables shadow (are accessed in preference to) less local variables. For example, if a variable MyInt is defined as Global in a module and declared local in a routine MyRoutine, while in MyRoutine, the local value of MyInt is accessed. Outside MyRoutine, theglobal value of MyInt is accessed.

Verifying Data Types You can change a variables type with ReDim in Visual Basic, assign objects to variables using Set, and even convert standard variables into arrays. For these and other reasons, Visual Basic has a number of data verification functions, which appear in Table 3.3, and you can use these functions to interrogate objects and determine their types. Table 3.3Data verification functions. Function IsArray() IsDate() IsEmpty() IsError() IsMissing() IsNull() IsNumeric() IsObject() Does This Returns True if passed an array Returns True if passed a date Returns True if passed variable is uninitialized Returns True if passed an error value Returns True if value was not passed for specified parameter in procedure call Returns True if passed NULL Returns True if passed a numeric value Returns True if passed an object

Converting Between Data Types Visual Basic supports a number of ways of converting from one type of variable to anotherin fact, thats one of the strengths of the language Visual Basic data conversion functions.
To Do This ANSI value to string String to lowercase or uppercase Date to serial number Decimal number to other bases Number to string One data type to another Date to day, month, weekday, or year Time to hour, minute, or second String to ASCII value String to number Use This Chr Format, LCase, UCase DateSerial, DateValue Hex, Oct Format, Str CBool, CByte, CCur, CDate, CDbl, CDec, CInt, CLng, CSng, CStr, CVar, CVErr, Fix, Int Day, Month, Weekday, Year Hour, Minute, Second Asc Val

The Dim Statement


use the Dim statement: Dim [WithEvents] varname[([subscripts])] [As [New] [WithEvents]varname [([subscripts])] [As [New] type]] . . . type] [,

The WithEvents keyword is valid only in class modules. This keyword specifies that varname is an object variable used to respond to events triggered by an ActiveX object. The varname identifier is the name of the variable you are declaring. You use subscripts if youre declaring an array. The New keyword enables creation of an object. If you use New when declaring the object variable, a new instance of the object is created on first reference to it. This means you dont have to use the Set statement to assign the object reference. Heres an example: Dim DataSheet As New Worksheet The type argument specifies the data type of the variable, which may be Byte, Boolean, Integer, Long,Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, Variant, a user-defined type, or an object type. If you dont specify a type, the default isVariant, which means the variable can act as any type. Heres an example of declaring variables using Dim: Dim EmployeeID As Integer Dim EmployeeName As String Dim EmployeeAddress As String

Declaring Constants
Youve filled your code with numeric valuesand now its time to change them all as you start work on thenew version of the software. What a pain to have to track down and change all the numeric values (calledmagic numbers) throughout all the code. Isnt there a better way? There is: Use constants and declare them all in one place, then refer to the constants by name throughout the code instead of hardwiring numeric values in the code. When its time to change those values, you just change the constants, all in one well-defined part of the code. You declare constants in Visual Basic with the Const statement: [Public | Private] Const constname [As type] = expression The Public keyword is used at the module level to make a constant global. This keyword is not allowed inprocedures. The Private keyword is used at the module or form level to declare constants that are private,which means only available within the module or form where the declaration is made. Like the Public keyword, Private is not allowed in procedures (constants in procedures are always private anyway). The constname identifier is the actual name of the constant. The type identifier is the data type of the constant, which may be Byte, Boolean, Integer, Long, Currency, Single, Double, Date, String, or Variant.

The expression identifier holds the value you want for this constant. It may be a literal, other constant, or any combination that includes all arithmetic or logical operators (except the Is operator).

You can use a constant anywhere you can use any Visual Basic expression, and you usually use them for numeric or string values that you want to use many places in a program. That way, when you want to modify the value of the constant, you only have to change it in its declaration, not in many places around the program. Also, constants dont change their values, which can make them more useful than variables incertain circumstances.
.

Heres an example showing how to declare and use a constant: Private Sub Command1_Click() Const Pi = 3.14159 Dim Radius, Area Radius = 1# Area = Pi * Radius * Radius MsgBox ("Area = " & Str(Area)) End Sub

Procedures
Procedure:
Visual basic programs can be broken into smaller logical components called procedures. Procedures are useful for condensing repeated operations such as the frequently used calculations, text and controls manipulation etc. The benefits of using procedures in programming are: It is easier to debug a program with procedures, which breaks a program into discrete logical limits. Procedures used in one program can act as building block for other programs with slight modification. A procedure can be sub, function or property procedure

Sub Procedure
A sub procedure can be placed in standard, class and form modules. Each time the procedure is called, the statement between Sub and End Sub are executed. Syntax [private | public ] [ static] Sub Procedure_Name [ (arg_list)] [Statements] End Sub

Argument list is separated by commas. Each argument acts like a variable in the procedure. There are two type of sub procedures namely general procedures and event procedures.

Event Procedures
An event procedure is procedure block that contains the controls actual name, an underscore ( _ ), and the event name Syntax Private sub Form1_Load( ) Statement block End sub This is event for form1. Execute when load form.

General Procedures
A general procedure is declare when several event procedure perform the same action. It is good programming practice to write common statements in separate procedure and then call them in the event procedure

Function Procedures
Function are like sub procedures, except they return a value to calling procedure. They are especially useful for taking one or more pieces of data, called arguments and performing some tasks with them. Then function return value that indicate result of the task. e.g. The following function procedure calculates area of circle of given radius. Function Area(a as double) as double Area = 3.14 * a^2 End Function

Procedure scope
As with variables, you can restrict the scope of procedures, and you do that with the Private, Public, Friend, and Static keywords. The Private and Public keywords are the main keywords here; using them, you can specify if a subroutine or function is private to the module or form in which it is declared or public (that is, global) to all forms and modules. You use these keywords before the Sub or Function keywords like this: Private Function Returns7() Dim Retval Retval = 7 Returns7 = Retval End Function

You can also declare procedures as friend procedures with the Friend keyword. Friend procedures are usually used in class modules (they are not available in standard modules, although you can declare them in forms) to declare that the procedure is available outside the class, but not outside the current project. This restricts those functions from being called if the current project serves as an OLE automation server, for example. Besides the earlier declarations, you can also declare procedures as Static, which means that the variables in the procedure do not change between procedure calls, and that can be very useful in cases like this, where we support a counter variable that is incremented each time a function is called: Static Function Counter() Dim CounterValue as Integer CounterValue = CounterValue + 1 Counter = CounterValue End Sub That completes our overview of projects in memory nowweve seen how such projects are organized, what parts they have, and what scope their parts have. Well take a look at storing projects on disk next.

Das könnte Ihnen auch gefallen