Working with Numeric Variables (Unit 6) Visual Basic for Applications.
Variables in Visual Basic 6
-
Upload
alandrie-teddy -
Category
Documents
-
view
223 -
download
0
Transcript of Variables in Visual Basic 6
-
8/8/2019 Variables in Visual Basic 6
1/64
http://visualbasic.freetutes.com/learn-vb6
Variables in Visual Basic 6
Variables are the memory locations which are used to store values temporarily. A definednaming strategy has to be followed while naming a variable. A variable name must begin with analphabet letter and should not exceed 255 characters. It must be unique within the same scope. Itshould not contain any special character like %, &, !, #, @ or $.
There are many ways of declaring variables in Visual Basic. Depending on where the variablesare declared and how they are declared, we can determine how they can be used by ourapplication. The different ways of declaring variables in Visual Basic are listed below andelucidated in this section.
y Explicit Declarationy Using Option Explicit statementy Scope of Variables
Explicit Declaration
Declaring a variable tells Visual Basic to reserve space in memory. It is not must that a variableshould be declared before using it. Automatically whenever Visual Basic encounters a newvariable, it assigns the default variable type and value. This is called implicit declaration. Thoughthis type of declaration is easier for the user, to have more control over the variables, it isadvisable to declare them explicitly. The variables are declared with a Dim statement to name thevariable and its type. The As type clause in the Dim statement allows to define the data type orobject type of the variable. This is called explicit declaration.
-
8/8/2019 Variables in Visual Basic 6
2/64
Syntax
Dim variable [As Type]
For example,
Dim strName As StringDim intCounter As Integer
Using Option Explicit statement
It may be convenient to declare variables implicitly, but it can lead to errors that may not berecognized at run time. Say, for example a variable by name intcountis used implicitly and isassigned to a value. In the next step, this field is incremented by 1 by the following statement
Intcount = Intcount + 1
This calculation will result in intcountyielding a value of 1 as intcount would have beeninitialized to zero. This is because the intcount variable has been mityped as incont in the righthand side of the second variable. But Visual Basic does not see this as a mistake and considers itto be new variable and therefore gives a wrong result.
In Visual Basic, to prevent errors of this nature, we can declare a variable by adding thefollowing statement to the general declaration section of the Form.
Option Explicit
This forces the user to declare all the variables. The Option Explicit statement checks in themodule for usage of any undeclared variables and reports an error to the user. The user can thusrectify the error on seeing this error message.
The Option Explicit statement can be explicitly placed in the general declaration section of eachmodule using the following steps.
y Click Options item in the Tools menuy Click the Editor tab in the Options dialog boxy Check Require Variable Declaration option and then click the OK button
Scope of variables
A variable is scoped to a procedure-level (local) or module-level variable depending on how it isdeclared. The scope of a variable, procedure or object determines which part of the code in ourapplication are aware of the variable's existence. A variable is declared in general declarationsection of e Form, and hence is available to all the procedures. Local variables are recognizedonly in the procedure in which they are declared. They can be declared with Dim and Static
-
8/8/2019 Variables in Visual Basic 6
3/64
keywords. If we want a variable to be available to all of the procedures within the same module,or to all the procedures in an application, a variable is declared with broader scope.
Local Variables
A local variable is one that is declared inside a procedure. This variable is only available to thecode inside the procedure and can be declared using the Dim statements as given below.
Dim sum As Integer
The local variables exist as long as the procedure in which they are declared, is executing. Oncea procedure is executed, the values of its local variables are lost and the memory used by thesevariables is freed and can be reclaimed. Variables that are declared with keyword Dim exist onlyas long as the procedure is being executed.
Static Variables
Static variables are not reinitialized each time Visual Invokes a procedure and therefore retainsor preserves value even when a procedure ends. In case we need to keep track of the number oftimes a command button in an application is clicked, a static counter variable has to be declared.These static variables are also ideal for making controls alternately visible or invisible. A staticvariable is declared as given below.
Static intPermanent As Integer
Variables have a lifetime in addition to scope. The values in a module-level and public variablesare preserved for the lifetime of an application whereas local variables declared with Dim exist
only while the procedure in which they are declared is still being executed. The value of a localvariable can be preserved using the Static keyword. The follwoing procedure calculates therunning total by adding new values to the previous values stored in the static variable value.
Function RunningTotal ( )Static AccumulateAccumulate = Accumulate + numRunningTotal = AccumulateEnd Function
If the variable Accumulate was declared with Dim instead of static, the previously accumulated
values would not be preserved accross calls to the procedure, and the procedure would return thesame value with which it was called. To make all variables in a procedure static, the Statickeyword is placed at the beginning of the procedure heading as given in the below statement.
Static Function RunningTotal ( )
Example
-
8/8/2019 Variables in Visual Basic 6
4/64
The following is an example of an event procedure for a CommandButton that counts anddisplays the number of clicks made.
Private Sub Command1_Click ( )Static Counter As Integer
Counter = Counter + 1Print CounterEnd Sub
The first time we click the CommandButton, the Counter starts with its default value of zero.Visual Basic then adds 1 to it and prints the result.
Module Levele Variables
A module level variable is available to all the procedures in the module. They are declared usingthe Public or the Private keyword. If you declare a variable using a Private or a Dim statement in
the declaration section of a modulea standard BAS module, a form module, a class module,and so onyou're creating a private module-level variable. Such variables are visible only fromwithin the module they belong to and can't be accessed from the outside. In general, thesevariables are useful for sharing data among procedures in the same module:
' In the declarative section of any modulePrivate LoginTime As Date ' A private module-level variableDim LoginPassword As String ' Another private module-level variable
You can also use the Public attribute for module-level variables, for all module types exceptBAS modules. (Public variables in BAS modules are global variables.) In this case, you're
creating a strange beast: a Public module-level variable that can be accessed by all procedures inthe module to share data and that also can be accessed from outside the module. In this case,however, it's more appropriate to describe such a variable as a property:
' In the declarative section of Form1 modulePublic CustomerName As String ' A Public property
You can access a module property as a regular variable from inside the module and as a customproperty from the outside:
' From outside Form1 module...
Form1.CustomerName = "JohnS
mith"
The lifetime of a module-level variable coincides with the lifetime of the module itself. Privatevariables in standard BAS modules live for the entire life of the application, even if they can beaccessed only while Visual Basic is executing code in that module. Variables in form and classmodules exist only when that module is loaded in memory. In other words, while a form is active(but not necessarily visible to the user) all its variables take some memory, and this memory isreleased only when the form is completely unloaded from memory. The next time the form is re-
-
8/8/2019 Variables in Visual Basic 6
5/64
created, Visual Basic reallocates memory for all variables and resets them to their default values(0 for numeric values, "" for strings, Nothing for object variables).
Public vs Local Variables
A variable can have the same name and different scope. For example, we can have a publicvariable named R and within a procedure we can declare a local variable R. References to thename R within the procedure would access the local variable and references to R outside theprocedure would access the public variable.
Related Topics
y VB6 Data Types, Modules and Operatorsy Procedures in Visual Basic 6y Control Structures in VB6 - If...Then...Else Statement, Select...Case Statementy Loops in Visual Basic 6y Arrays in Visual Basic 6
Visual Basic 6 (VB6) Data Types, Modules
and Operators
Visual Basic uses building blocks such as Variables, Data Types, Procedures, Functions andControl Structures in its programming environment. This section concentrates on theprogramming fundamentals of Visual Basic with the blocks specified.
Modules
-
8/8/2019 Variables in Visual Basic 6
6/64
Code in Visual Basic is stored in the form of modules. The three kind of modules are FormModules, Standard Modules and Class Modules. A simple application may contain a singleForm, and the code resides in that Form module itself. As the application grows, additionalForms are added and there may be a common code to be executed in several Forms. To avoid theduplication of code, a separate module containing a procedure is created that implements the
common code. This is a standard Module.
Class module (.CLS filename extension) are the foundation of the object oriented programmingin Visual Basic. New objects can be created by writing code in class modules. Each module cancontain:
Declarations : May include constant, type, variable and DLL procedure declarations.
Procedures : A sub function, or property procedure that contain pieces of code that can beexecuted as a unit.
These are the rules to follow when naming elements in VB - variables, constants, controls,procedures, and so on:
y A name must begin with a letter.y May be as much as 255 characters long (but don't forget that somebody has to type the
stuff!).y Must not contain a space or an embedded period or type-declaration characters used to
specify a data type; these are ! # % $ & @y Must not be a reserved word (that is part of the code, like Option, for example)y The dash, although legal, should be avoided because it may be confused with the minus
sign. Instead of First-name use First_name or FirstName.
Data types in Visual Basic 6
By default Visual Basic variables are of variant data types. The variant data type can storenumeric, date/time or string data. When a variable is declared, a data type is supplied for it thatdetermines the kind of data they can store. The fundamental data types in Visual Basic includingvariant are integer, long, single, double, string, currency, byte and boolean. Visual Basic supportsa vast array of data types. Each data type has limits to the kind of information and the minimumand maximum values it can hold. In addition, some types can interchange with some other types.A list of Visual Basic's simple data types are given below.
1. Numeric
Byte Store integer values in the range of 0 - 255
Integer Store integer values in the range of (-32,768) - (+ 32,767)
LongStore integer values in the range of (- 2,147,483,468) - (+2,147,483,468)
-
8/8/2019 Variables in Visual Basic 6
7/64
Single Store floating point value in the range of (-3.4x10-38) - (+ 3.4x1038)
Double Store large floating value which exceeding the single data type value
Currencystore monetary values. It supports 4 digits to the right of decimal pointand 15 digits to the left
2. String
Use to store alphanumeric values. A variable length string can store approximately 4 billioncharacters
3. Date
Use to store date and time values. A variable declared as date type can store both date and timevalues and it can store date values 01/01/0100 up to 12/31/9999
4. Boolean
Boolean data types hold either a true or false value. These are not stored as numeric values andcannot be used as such. Values are internally stored as -1 (True) and 0 (False) and any non-zerovalue is considered as true.
5. Variant
Stores any type of data and is the default Visual Basic data type. In Visual Basic if we declare avariable without any data type by default the data type is assigned as default.
Operators in Visual Basic
Arithmetical Operators
Operators Description Example Result
+ Add 5+5 10
- Substract 10-5 5
/ Divide 25/5 5
\ Integer Division 20\3 6* Multiply 5*4 20
^ Exponent (power of) 3^3 27
Mod Remainder of division 20 Mod 6 2
& String concatenation"George"&""&"Bush"
"George Bush"
-
8/8/2019 Variables in Visual Basic 6
8/64
Relational Operators
Operators Description Example Result
> Greater than 10>8 True
< Less than 10= Greater than or equal to 20>=10 True
-
8/8/2019 Variables in Visual Basic 6
9/64
Sub Procedures
A sub procedure can be placed in standard, class and form modules. Each time the procedure iscalled, the statements between Sub and End Sub are executed. The syntax for a sub procedure isas follows:
[Private | Public] [Static] Sub Procedurename [( arglist)][ statements]End Sub
arglist is a list of argument names separated by commas. Each argument acts like a variable inthe procedure. There are two types ofSub Procedures namely general procedures and eventprocedures.
Event Procedures
An event procedure is a procedure block that contains the control's actual name, anunderscore(_), and the event name. The following syntax represents the event procedure for aForm_Load event.
Private Sub Form_Load()....statement block..End Sub
Event Procedures acquire the declarations as Private by default.
General Procedures
A general procedure is declared when several event procedures perform the same actions. It is agood programming practice to write common statements in a separate procedure (generalprocedure) and then call them in the event procedure.
In order to add General procedure:
y The Code window is opened for the module to which the procedure is to be added.y The AddProcedure option is chosen from the Tools menu, which opens an Add
Procedure dialog box as shown in the figure given below.y The name of the procedure is typed in the Name textboxy UnderType, Sub is selected to create a Sub procedure,Function to create a Function
procedure orProperty to create a Property procedure.y UnderScope, Public is selected to create a procedure that can be invoked outside the
module, or Private to create a procedure that can be invoked only from within themodule.
-
8/8/2019 Variables in Visual Basic 6
10/64
We can also create a new procedure in the current module by typing Sub ProcedureName,Function ProcedureName, or Property ProcedureName in the Code window. A Functionprocedure returns a value and a Sub Procedure does not return a value.
Function Procedures
Functions are like sub procedures, except they return a value to the calling procedure. They areespecially useful for taking one or more pieces of data, called arguments and performing sometasks with them. Then the functions returns a value that indicates the results of the taskscomplete within the function.
The following function procedure calculates the third side or hypotenuse of a right triangle,where A and B are the other two sides. It takes two arguments A and B (of data type Double) and
finally returns the results.
Function Hypotenuse (A As Double, B As Double) As DoubleHypotenuse = sqr (A^2 + B^2)End Function
The above function procedure is written in the general declarations section of the Code window.A function can also be written by selecting the AddProcedure dialog box from the Tools menuand by choosing the required scope and type.
Property Procedures
A property procedure is used to create and manipulate custom properties. It is used to create readonly properties for Forms, Standard modules and Class modules.Visual Basic provides three kindof property procedures-Property Let procedure that sets the value of a property, Property Getprocedure that returns the value of a property, and Property Set procedure that sets the referencesto an object.
-
8/8/2019 Variables in Visual Basic 6
11/64
Related Topics
y VB6 Data Types, Modules and Operatorsy Variables in Visual Basic 6y Control Structures in VB6 - If...Then...Else Statement, Select...Case Statementy
Loops in Visual Basic 6y Arrays in Visual Basic 6
Control Structures in Visual Basic 6.0
Control Statements are used to control the flow of program's execution. Visual Basic supportscontrol structures such as if... Then, if...Then ...Else, Select...Case, and Loop structures such asDo While...Loop, While...Wend, For...Next etc method.
If...Then selection structure
The If...Then selection structure performs an indicated action only when the condition is True;otherwise the action is skipped.
Syntax of the If...Then selection
If ThenstatementEnd If
-
8/8/2019 Variables in Visual Basic 6
12/64
e.g.: If average>75 ThentxtGrade.Text = "A"End If
If...Then...Else selection structure
The If...Then...Else selection structure allows the programmer to specify that a different action isto be performed when the condition is True than when the condition is False.
Syntax of the If...Then...Else selection
If ThenstatementsElsestatementsEnd If
e.g.: If average>50 ThentxtGrade.Text = "Pass"ElsetxtGrade.Text = "Fail"End If
Nested If...Then...Else selection structure
Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Else
selection structures inside If...Then...E
lse structures.
Syntax of the Nested If...Then...Else selection structure
You can use Nested If either of the methods as shown above
Method 1
If < condition 1 > ThenstatementsElseIf < condition 2 > Then
statementsElseIf < condition 3 > ThenstatementsElseStatements
End If
Method 2
-
8/8/2019 Variables in Visual Basic 6
13/64
If < condition 1 > ThenstatementsElseIf < condition 2 > ThenstatementsE
lseIf < condition 3 > ThenstatementsElseStatementsEnd IfEnd IfEndIf
e.g.: Assume you have to find the grade using nested if and display in a text box
If average > 75 ThentxtGrade.Text = "A"ElseIf average > 65 ThentxtGrade.Text = "B"ElseIf average > 55 ThentxtGrade.text = "C"
ElseIf average > 45 ThentxtGrade.Text = "S"ElsetxtGrade.Text = "F"End If
Select...Case selection structure
Select...Case structure is an alternative to If...Then...ElseIf for selectively executing a singleblock of statements from among multiple block of statements. Select...case is more convenient touse than the If...Else...End If. The following program block illustrate the working ofSelect...Case.
Syntax of the Select...Case selection structure
Select Case Index
Case 0StatementsCase 1StatementsEnd Select
e.g.: Assume you have to find the grade using select...case and display in the text box
-
8/8/2019 Variables in Visual Basic 6
14/64
Dim average as Integer
average = txtAverage.TextSelect Case averageCase 100 To 75
txtGrade.Text ="A"Case 74 To 65txtGrade.Text ="B"Case 64 To 55txtGrade.Text ="C"Case 54 To 45txtGrade.Text ="S"Case 44 To 0txtGrade.Text ="F"Case ElseMsgBox "Invalid average marks"E
ndS
elect
Note: In this example I have used a message box function. In later lessons you will learn how touse message box functions.
Related Topics
y Loops in Visual Basic 6y Exit For and Exit Do Statement in Visual Basic 6y Date and Time Functions in VB6y Procedures in Visual Basic 6y
Arrays in Visual Basic 6
Loops (Repetition Structures) in Visual Basic
6
A repetition structure allows the programmer to that an action is to be repeated until givencondition is true.
Do While... Loop Statement
document.write('
-
8/8/2019 Variables in Visual Basic 6
15/64
4490EBF4CF5B&publisher=148&ypos=317&zone=1&url=http%3a%2f%2fvisualbasic.fre
etutes.com%2flearn-vb6%2flesson4.html&country=ID&userguid=00000000-0000-0000-
0000-000000000000&placement=8294&creative=7704" target="_blank">');
The Do While...Loop is used to execute statements until a certain condition is met. Thefollowing Do Loop counts from 1 to 100.
Dim number As Integer
number = 1Do While number
-
8/8/2019 Variables in Visual Basic 6
16/64
Donumber = number + 1Loop While number < 201
The programs executes the statements between Do and Loop While structure in any case. Then it
determines whether the counter is less than 501. If so, the program again executes the statementsbetween Do and Loop While else exits the Loop.
Do Until...Loop Statement
Unlike the Do While...Loop and While...Wend repetition structures, the Do Until... Loopstructure tests a condition for falsity. Statements in the body of a Do Until...Loop are executedrepeatedly as long as the loop-continuation test evaluates to False.
An example forDo Until...Loop statement. The coding is typed inside the click event of thecommand button
Dim number As Longnumber=0Do Until number > 1000number = number + 1Print numberLoop
Numbers between 1 to 1000 will be displayed on the form as soon as you click on the commandbutton.
The For...Next Loop
The For...Next Loop is another way to make loops in Visual Basic. For...Next repetitionstructure handles all the details of counter-controlled repetition. The following loop counts thenumbers from 1 to 100:
Dim x As IntegerFor x = 1 To 50Print xNext
In order to count the numbers from 1 yo 50 in steps of 2, the following loop can be used
For x = 1 To 50 Step 2Print xNext
-
8/8/2019 Variables in Visual Basic 6
17/64
The following loop counts numbers as 1, 3, 5, 7..etc
The above coding will display numbers vertically on the form. In order to display numbershorizontally the following method can be used.
For x = 1 To 50Print x & Space$ (2);Next
To increase the space between the numbers increase the value inside the brackets after the &Space$.
Following example is a For...Next repetition structure which is with the If condition used.
Dim number As IntegerFor number = 1 To 10
If number = 4 ThenPrint "This is number 4"ElsePrint numberEnd IfNext
In the output instead of number 4 you will get the "This is number 4".
Related Topics
yControl
Structures - If...Then / if...Then...
Else /
Select Case
Statements
y Exit For and Exit Do Statement in Visual Basic 6y Date and Time Functions in VB6y Procedures in Visual Basic 6y Arrays in Visual Basic 6
Control Structures in Visual Basic 6.0
-
8/8/2019 Variables in Visual Basic 6
18/64
Control Statements are used to control the flow of program's execution. Visual Basic supportscontrol structures such as if... Then, if...Then ...Else, Select...Case, and Loop structures such asDo While...Loop, While...Wend, For...Next etc method.
If...Then selection structure
The If...Then selection structure performs an indicated action only when the condition is True;otherwise the action is skipped.
Syntax of the If...Then selection
If ThenstatementE
nd If
e.g.: If average>75 ThentxtGrade.Text = "A"End If
If...Then...Else selection structure
The If...Then...Else selection structure allows the programmer to specify that a different action isto be performed when the condition is True than when the condition is False.
Syntax of the If...Then...Else selection
If ThenstatementsElsestatementsEnd If
-
8/8/2019 Variables in Visual Basic 6
19/64
e.g.: If average>50 ThentxtGrade.Text = "Pass"ElsetxtGrade.Text = "Fail"
End If
Nested If...Then...Else selection structure
Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Elseselection structures inside If...Then...Else structures.
Syntax of the Nested If...Then...Else selection structure
You can use Nested If either of the methods as shown above
Method 1
If < condition 1 > ThenstatementsElseIf < condition 2 > ThenstatementsElseIf < condition 3 > ThenstatementsElse
StatementsEnd If
Method 2
If < condition 1 > ThenstatementsElseIf < condition 2 > ThenstatementsElseIf < condition 3 > ThenstatementsElse
StatementsEnd IfEnd IfEndIf
e.g.: Assume you have to find the grade using nested if and display in a text box
-
8/8/2019 Variables in Visual Basic 6
20/64
If average > 75 ThentxtGrade.Text = "A"ElseIf average > 65 ThentxtGrade.Text = "B"
ElseIf average > 55 Then
txtGrade.text = "C"ElseIf average > 45 ThentxtGrade.Text = "S"ElsetxtGrade.Text = "F"End If
Select...Case selection structure
Select...Case structure is an alternative to If...Then...ElseIf for selectively executing a singleblock of statements from among multiple block of statements. Select...case is more convenient to
use than the If...Else...End If. The following program block illustrate the working ofSelect...Case.
Syntax of the Select...Case selection structure
Select Case IndexCase 0StatementsCase 1StatementsEnd Select
e.g.: Assume you have to find the grade using select...case and display in the text box
Dim average as Integer
average = txtAverage.TextSelect Case averageCase 100 To 75txtGrade.Text ="A"Case 74 To 65txtGrade.Text ="B"
Case 64 To 55txtGrade.Text ="C"Case 54 To 45txtGrade.Text ="S"Case 44 To 0txtGrade.Text ="F"Case Else
-
8/8/2019 Variables in Visual Basic 6
21/64
MsgBox "Invalid average marks"End Select
Note: In this example I have used a message box function. In later lessons you will learn how touse message box functions.
Related Topics
y Loops in Visual Basic 6y Exit For and Exit Do Statement in Visual Basic 6y Date and Time Functions in VB6y Procedures in Visual Basic 6y Arrays in Visual Basic 6
ExitF
or andEx
it DoS
tatement in Visualbasic 6
A For...Next loop condition can be terminated by an Exit For statement. Consider the followingstatement block.
Dim x As IntegerFor x = 1 To 10
Print xIf x = 5 ThenPrint "The program exited at x=5"Exit ForEnd IfNext
-
8/8/2019 Variables in Visual Basic 6
22/64
The preceding code increments the value of x by 1 until it reaches the condition x = 5. The ExitFor statement is executed and it terminates the For...Next loop. The Following statement blockcontaining Do...While loop is terminated using Exit Do statement.
Dim x As Integer
Do While x < 10Print xx = x + 1If x = 5 ThenPrint "The program is exited at x=5"
Exit DoEnd IfLoop
With...End With statement
When properties are set for objects or methods are called, a lot of coding is included that acts onthe same object. It is easier to read the code by implementing theWith...End Withstatement.Multiple properties can be set and multiple methods can be called by using the With...End Withstatement. The code is executed more quickly and efficiently as the object is evaluated onlyonce. The concept can be clearly understood with following example.
With Text1.Font.Size = 14.Font.Bold = True.ForeColor = vbRed.Height = 230
.Text = "Hello World"End With
In the above coding, the object Text1, which is a text box is evaluated only once instead of everyassociated property or method. This makes the coding simpler and efficient.
Related Topics
y Control Structures - If...Then / if...Then...Else / Select Case Statementsy Loops in Visual Basic 6y Date and Time Functions in VB6y Procedures in Visual Basic 6y Arrays in Visual Basic 6
Date and Time Functions in Visual Basic 6
-
8/8/2019 Variables in Visual Basic 6
23/64
Not only does Visual Basic let you store date and time information in the specific Date data type,it also provides a lot of date- and time-related functions. These functions are very important in allbusiness applications and deserve an in-depth look. Date and Time are internally stored as
numbers in Visual Basic. The decimal points represents the time between 0:00:00 and 23:59:59hours inclusive.
The system's current date and time can be retrieved using the Now, Date and Time functions inVisual Basic. The Now function retrieves the date and time, while Date function retrieves onlydate and Time function retrieves only the time.
To display both the date and time together a message box is displayed use the statement givenbelow.
MsgBox "The current date and time of the system is" & Now
Here & is used as a concatenation operator to concentrate the string and the Now function.Selective portions of the date and time value can be extracted using the below listed functions.
Function Extracted Portion
Year ( ) Year (Now)
Month ( ) Month (Now)
Day ( ) Day (Now)
WeekDay ( ) WeekDay (Now)
Hour ( ) Hour (Now)
Minute ( ) Minute (Now)
Second ( ) Second (Now)
-
8/8/2019 Variables in Visual Basic 6
24/64
The calculation and conversion functions related to date and time functions are listed below.
Function Description
DateAdd ( ) Returns a date to which a specific interval has been added
DateDiff ( ) Returns a Long data type value specifying the interval betweenthe two values
DatePart ( ) Returns an Integer containing the specified part of a given date
DateValue ( ) Converts a string to a Date
TimeValue ( ) Converts a string to a time
DateSerial ( ) Returns a date for specified year, month and day
DateDiffFunctionThe DateDiff function returns the intervals between two dates in terms of years, months or days.The syntax for this is given below.
DateDiff (interval, date1, date2[, firstdayofweek[, firstweekofyear]])
Format Function
The format function accepts a numeric value and converts it to a string in the format specified bythe format argument. The syntax for this is given below.
Format (expression[, format[, firstdayofweek[, firstweekofyear]]])
The Format function syntax has these parts:
Part Description
Expression Required any valid expression
format Optional. A valid named or user-defined format expression.
firstdayofweek Optional. A contant that specifies the first day of the week.
firstweekofyear Optional. A contant that specifies the first week of the year
More on Date and Time in Visual Basic 6
y Getting and Setting the Current Date and Timey Building and Extracting Date and Time Values
-
8/8/2019 Variables in Visual Basic 6
25/64
y Date Arithmeticy Format Options for Date and Time Values
Getting and Setting the Current Date and
Time
Strictly speaking, Date and Time aren't functions: They're properties. In fact, you can use them toeither retrieve the current date and time (as Date values) or assign new values to them to modifythe system settings:
Print Date & " " & Time ' Displays "8/14/98 8:35:48 P.M.".
' Set a new system date using any valid date format.Date = "10/14/98"Date = "October 14, 1998"
To help you compare the outcome of all date and time functions, all the examples in this sectionassume that they're executed at the date and time shown in the preceding code snippet: October17, 2008, 9:25:33 p.m.
The outdated Date$ and Time$ properties can also be used for the same task. They're Stringproperties, however, and therefore recognize only the mm/dd/yy or mm/dd/yyyy formats and thehh:mm:ss and hh:mm formats, respectively. For this reason, it's usually better to use the new $-
less functions.
The Now function returns a Date value that contains the current date and time:
Print Now ' Displays "10/17/2008 9:25:33 P.M.".
But the time-honored Timer function returns the number of seconds elapsed from midnight andis more accurate than Now because the Timer function includes fractional parts of seconds. (The
-
8/8/2019 Variables in Visual Basic 6
26/64
actual accuracy depends on the system.) This function is often used for benchmarking a portionof code:
StartTime = Timer' Insert the code to be benchmarked here.
Print Timer -S
tartTime
The preceding code suffers from some inaccuracy: The StartTime variable might be assignedwhen the system tick is about to expire, so your routine could appear to take longer than itactually does. Here's a slightly better approach:
StartTime = NextTimerTick' Insert the code to be benchmarked here.Print Timer _StartTime
' Wait for the current timer tick to elapse.
Function NextTimerTick() AsS
ingleDim t As Singlet = TimerDo: Loop While t = TimerNextTimerTick = Timer
End Function
If you're using the Timer function in production code, you should be aware that it's reset atmidnight, so you always run the risk of introducing unlikely but potentially serious errors. Try tospot the bug in this routine, which adds a CPU-independent pause in your code:
' WARNING: this procedure has a bug.Sub BuggedPause(seconds As Integer)Dim start As Singlestart = TimerDo: Loop Until Timer _ start >= secondsEnd Sub
The bug manifests itself very rarelyfor example, if the program asks for a 2-second pause at11:59:59 p.m. Even if this probability is small, the effect of this minor bug is devastating andyou'll have to press Ctrl+Alt+Del to kill your compiled application. Here's a way to work aroundthis issue:
' The correct version of the procedureSub Pause(seconds As Integer)Const SECS_INDAY = 24! * 60 * 60 ' Seconds per dayDim start As Singlestart = TimerDo: Loop Until (Timer + SECS_INDAY - start) Mod SECS_INDAY >= seconds
End Sub
-
8/8/2019 Variables in Visual Basic 6
27/64
More on Date and Time in Visual Basic 6
y Date and Time Functions in Visual Basic 6y Getting and Setting the Current Date and Timey Building and Extracting Date and Time Valuesy
Date Arithmeticy Format Options for Date and Time Values
Building and Extracting Date and Time
Values - VB6 Date & Time
document.write('');
There are many ways to assemble a Date value. For example, you can use a Date constant, suchas the following:
StartDate = #10/17/2008 9:25:33 P.M.#
but more often you'll build a Date value using one of the many functions that VBA gives you.The DateSerial function builds a Date value from its year/month/day components; similarly, theTimeSerial function builds a Time value from its hour/minute/second components:
Print DateSerial(2008, 10, 17) ' Displays "10/17/2008"Print TimeSerial(12, 20, 30) ' Displays "12:20:30 P.M."' Note that they don't raise errors with invalid arguments.Print DateSerial(2008, 4, 31) ' Displays "5/1/2008"
The DateSerial function is also useful for determining indirectly whether a particular year is aleap year:
Function IsLeapYear(year As Integer) As Boolean' Are February 29 and March 1 different dates?
-
8/8/2019 Variables in Visual Basic 6
28/64
IsLeapYear = DateSerial(year, 2, 29) DateSerial(year, 3, 1)End Function
The DateValue and TimeValue functions return the date or time portions of their argument,which can be a string or a Date expression:
' The date a week from nowPrint DateValue(Now + 7) ' Displays "10/17/2008"
A bunch of VBA functions let you extract date and time information from a Date expression orvariable. The Day, Month, and Year functions return date values, whereas the Hour, Minute, andSecond functions return time values:
' Get information about today's date.y = Year(Now): m = Month(Now): d = Day(Now)' These functions also support any valid date format.
Print Year("10/17/2008 9:25:33 P.M.") ' Displays "2008"
The Weekday function returns a number in the range 1 through 7, which corresponds to the dayof the week of a given Date argument:
Print Weekday("10/17/2008") ' Displays "6" (= vbFriday)
The Weekday function returns 1 when the date is the first day of the week. This function islocale aware, which means that under different localizations of Microsoft Windows it couldconsider the first day of the week to be different from vbSunday. In most cases, this conditiondoesn't affect the structure of your code. But if you want to be sure that 1 means Sunday, 2
means Monday, and so on, you can force the function to return a consistent value under allWindows systems, as follows:
Print Weekday(Now, vbSunday)
Although using the optional second argument forces the function to return the correct value, itdoesn't change the system localization. If you next call the Weekday function without the secondargument, it will still consider the first day of the week to be what it was before.
Finally you can extract any date and time information from a Date value or expression using theDatePart function, for which the syntax is
Result = DatePart(Interval, Date, [FirstDayOfWeek], [FirstWeekOfYear])
You'll rarely need to resort to this function because you can do most of your calculations usingthe other functions I've shown you so far. In two cases, however, this function is really useful:
' The quarter we are inPrint DatePart("q", Now) ' Displays "3"
-
8/8/2019 Variables in Visual Basic 6
29/64
' The week number we are in (# of weeks since Jan 1st)Print DatePart("ww", Now) ' Displays "33"
The first argument can be one of the String constants listed in the following table. For moreinformation about the two optional arguments, see the description of the DateAdd function in the
next section.
Possible values forthe interval argument in DatePart, DateAdd, andDateDiff functions.
Setting Description
"yyyy" Year
"q" Quarter
"m" Month
"y" Day of the year (same as d)
"d" Day
"w" Weekday
"ww" Week
"h" Hour
"n" Minute
"s" Second
More on Date and Time in Visual Basic 6
y Date and Time Functions in Visual Basic 6y Getting and Setting the Current Date and Timey Building and Extracting Date and Time Valuesy Date Arithmeticy Format Options for Date and Time Values
Date Arithmetic - VB6 Date & Time
In most cases, you don't need any special functions to perform date arithmetic. All you need toknow is that the integer part in a Date variable holds the date information, and the fractional partholds the time information:
' 2 days and 12 hours from nowPrint Now + 2 + #12:00# ' Displays "8/17/2008 8:35:48 A.M."
For more sophisticated date math, you can use the DateAdd function, for which the syntax is thefollowing:
NewDate = DateAdd(interval, number, date)
-
8/8/2019 Variables in Visual Basic 6
30/64
The interval is a string that indicates a date or time unit (see table below), number is the numberof units you are adding, and date is the starting date. You can use this function to add andsubtract date and time values:
' The date three months from now
Print DateAdd("m", 3, Now) ' Displays "11/14/2008 8:35:48 P.M."' One year ago (automatically accounts for leap years)Print DateAdd("yyyy", -1, Now) ' Displays "8/14/2007 8:35:48 P.M."' The number of months since Jan 30, 2008Print DateDiff("m", #1/30/2008#, Now) ' Displays "7"' The number of days since Jan 30, 2008 _ you can use "d" or "y".Print DateDiff("y", #1/30/2008#, Now) ' Displays "196"' The number of entire weeks since Jan 30, 2008Print DateDiff("w", #1/30/2008#, Now) ' Displays "28"' The number of weekends before 21st century - value
-
8/8/2019 Variables in Visual Basic 6
31/64
y Date and Time Functions in Visual Basic 6y Getting and Setting the Current Date and Timey Building and Extracting Date and Time Valuesy Date Arithmeticy Format Options for Date and Time Values
Date Arithmetic - VB6 Date & Time
The most important and flexible function for formatting date and time values is the Formatfunction. This function gives you seven different, named formats for date and time:
y General Date (date and time in general format; only the date if the fractional part is 0;only the time if the integer part is 0)
y Long Date (for example, Friday, October 17, 2008, but results vary depending on yourlocale)
y Medium Date (for example, 17-Oct-2008)y Short Date (for example, 10/17/2008)y Long Time (for example, 8:35:48)y Medium Time (for example, 8:35 A.M.)y Short Time (for example, 8:35 in a 24 hour format)
You also have a few special characters with which you can build your own custom date and timeformat strings, including one- and two-digit day and month numbers, complete or abbreviated
month and weekday names, a.m/p.m. indicators, week and quarter numbers, and so on:
' mmm/ddd = abbreviated month/weekday,' mmmm/dddd = complete month/weekdayPrint Format(Now, "mmm dd, yyyy (dddd)") ' "Aug 14, 1998 (Friday)"' hh/mm/ss always use two digits, h/m/s use one or two digitsPrint Format(Now, "hh:mm:ss") ' "20:35:48"Print Format(Now, "h:mm AMPM") ' "8:35 P.M."
-
8/8/2019 Variables in Visual Basic 6
32/64
' y=day in the year, ww=week in the year, q=quarter in the year' Note how a backslash can be used to specify literal characters.Print Format(Now, "mm/dd/yy (\d\a\y=y \w\e\e\k=ww \q\u\a\r\t\e\r=q)")' Displays "08/14/98 (day=226 week=33 quarter=3)"
Visual Basic 6 has introduced the new FormatDateTime function. It's far less flexible than thestandard Format function and permits only a subset of the Format function's named formats. Theonly advantage of the FormatDateTime function is that it's also supported under VBScript and socan contribute to the ease of porting pieces of code from Visual Basic and VBA to VBScript andvice versa. Its syntax is
result = FormatDateTime(Expression, [NamedFormat])
where NamedFormat can be one of the following intrinsic constants: 0-vbGeneralDate (thedefault), 1-vbLongDate, 2-vbShortDate, 3-vbLongTime, or 4-vbShortTime. Here are a fewexamples:
Print FormatDateTime(Now) ' "8/14/98 8:35:48 P.M."Print FormatDateTime(Now, vbLongDate) ' "Saturday, August 15, 1998"Print FormatDateTime(Now, vbShortTime) ' "20:35"
Visual Basic 6 also includes two new functions related to date formatting. The MonthNamefunction returns the complete or abbreviated name of a month, whereas the WeekdayNamefunction returns the complete or abbreviated name of a weekday. Both are locale aware, so youcan use them to list month and weekday names in the language the operating system has beenconfigured for:
Print MonthName(2) ' "February"Print MonthName(2, True) ' "Feb"Print WeekdayName(1, True) ' "Sun"
More on Date and Time in Visual Basic 6
y Date and Time Functions in Visual Basic 6y Getting and Setting the Current Date and Timey Building and Extracting Date and Time Valuesy Date Arithmeticy Format Options for Date and Time Values
VB Array - Arrays in Visual Basic 6
-
8/8/2019 Variables in Visual Basic 6
33/64
An array is a consecutive group of memory locations that all have the same name and the sametype. To refer to a particular location or element in the array, we specify the array name and the
array element position number.
The Individual elements of an array are identified using an index. Arrays have upper and lowerbounds and the elements have to lie within those bounds. Each index number in an array isallocated individual memory space and therefore users must evade declaring arrays of larger sizethan required. We can declare an array of any of the basic data types including variant, user-defined types and object variables. The individual elements of an array are all of the same datatype.
Declaring arrays
Arrays occupy space in memory. The programmer specifies the array type and the number ofelements required by the array so that the compiler may reserve the appropriate amount ofmemory. Arrays may be declared as Public (in a code module), module or local. Module arraysare declared in the general declarations using keyword Dim or Private. Local arrays are declaredin a procedure using Dim orStatic. Array must be declared explicitly with keyword "As".
There are two types of arrays in Visual Basic namely:
Fixed-size array : The size of array always remains the same-size doesn't change during theprogram execution.
Dynamic array : The size of the array can be changed at the run time- size changes during theprogram execution.
Fixed-sized Arrays
When an upper bound is specified in the declaration, a Fixed-array is created. The upper limitshould always be within the range of long data type.
-
8/8/2019 Variables in Visual Basic 6
34/64
Declaring a fixed-array
Dim numbers(5) As Integer
In the above illustration, numbers is the name of the array, and the number 6 included in the
parentheses is the upper limit of the array. The above declaration creates an array with 6elements, with index numbers running from 0 to 5.
If we want to specify the lower limit, then the parentheses should include both the lower andupper limit along with the To keyword. An example for this is given below.
Dim numbers (1 To 6 ) As Integer
In the above statement, an array of 10 elements is declared but with indexes running from 1 to 6.
A public array can be declared using the keyword Public instead of Dim as shown below.
Public numbers(5) As Integer
Multidimensional Arrays
Arrays can have multiple dimensions. A common use of multidimensional arrays is to representtables of values consisting of information arranged in rows and columns. To identify a particulartable element, we must specify two indexes: The first (by convention) identifies the element'srow and the second (by convention) identifies the element's column.
Tables or arrays that require two indexes to identify a particular element are called two
dimensional arrays. Note that multidimensional arrays can have more than two dimensions.Visual Basic supports at least 60 array dimensions, but most people will need to use more thantwo or three dimensional-arrays.
The following statement declares a two-dimensional array 50 by 50 array within a procedure.
Dim AvgMarks ( 50, 50)
It is also possible to define the lower limits for one or both the dimensions as for fixed sizearrays. An example for this is given here.
Dim Marks ( 101 To 200, 1 To 100)
An example for three dimensional-array with defined lower limits is given below.
Dim Details( 101 To 200, 1 To 100, 1 To 100)
Static and dynamic arrays
-
8/8/2019 Variables in Visual Basic 6
35/64
Basically, you can create either static or dynamic arrays. Static arrays must include a fixednumber of items, and this number must be known at compile time so that the compiler can setaside the necessary amount of memory. You create a static array using a Dim statement with aconstant argument:
' This is a static array.Dim Names(100) As String
Visual Basic starts indexing the array with 0. Therefore, the preceding array actually holds 101items.
Most programs don't use static arrays because programmers rarely know at compile time howmany items you need and also because static arrays can't be resized during execution. Both theseissues are solved by dynamic arrays. You declare and create dynamic arrays in two distinct steps.In general, you declare the array to account for its visibility (for example, at the beginning of amodule if you want to make it visible by all the procedures of the module) using a Dim
command with an empty pair of brackets. Then you create the array when you actually need it,using a ReDim statement:
' An array defined in a BAS module (with Private scope)Dim Customers() As String...Sub Main()' Here you create the array.ReDim Customer(1000) As StringEnd Sub
If you're creating an array that's local to a procedure, you can do everything with a single ReDimstatement:
Sub PrintReport()' This array is visible only to the procedure.ReDim Customers(1000) As String' ...End Sub
If you don't specify the lower index of an array, Visual Basic assumes it to be 0, unless an OptionBase 1 statement is placed at the beginning of the module. My suggestion is this: Never use anOption Base statement because it makes code reuse more difficult. (You can't cut and pasteroutines without worrying about the current Option Base.) If you want to explicitly use a lowerindex different from 0, use this syntax instead:
ReDim Customers(1 To 1000) As String
Dynamic arrays can be re-created at will, each time with a different number of items. When youre-create a dynamic array, its contents are reset to 0 (or to an empty string) and you lose the data
-
8/8/2019 Variables in Visual Basic 6
36/64
it contains. If you want to resize an array without losing its contents, use the ReDim Preservecommand:
ReDim Preserve Customers(2000) As String
When you're resizing an array, you can't change the number of its dimensions nor the type of thevalues it contains. Moreover, when you're using ReDim Preserve on a multidimensional array,you can resize only its last dimension:
ReDim Cells(1 To 100, 10) As Integer...ReDim Preserve Cells(1 To 100, 20) As Integer ' This works.ReDim Preserve Cells(1 To 200, 20) As Integer ' This doesn't.
Finally, you can destroy an array using the Erase statement. If the array is dynamic, Visual Basicreleases the memory allocated for its elements (and you can't read or write them any longer); if
the array is static, its elements are set to 0 or to empty strings.
You can use the LBound and UBound functions to retrieve the lower and upper indices. If thearray has two or more dimensions, you need to pass a second argument to these functions tospecify the dimension you need:
Print LBound(Cells, 1) ' Displays 1, lower index of 1st dimensionPrint LBound(Cells) ' Same as abovePrint UBound(Cells, 2) ' Displays 20, upper index of 2nd dimension' Evaluate total number of elements.NumEls = (UBound(Cells) _ LBound(Cells) + 1) * _
(U
Bound(Cells, 2) _ LBound(Cells, 2) + 1)
Arrays within UDTs
UDT structures can include both static and dynamic arrays. Here's a sample structure thatcontains both types:
Type MyUDTStaticArr(100) As LongDynamicArr() As LongEnd Type
...Dim udt As MyUDT' You must DIMension the dynamic array before using it.ReDim udt.DynamicArr(100) As Long' You don't have to do that with static arrays.udt.StaticArr(1) = 1234
-
8/8/2019 Variables in Visual Basic 6
37/64
The memory needed by a static array is allocated within the UDT structure; for example, theStaticArr array in the preceding code snippet takes exactly 400 bytes. Conversely, a dynamicarray in a UDT takes only 4 bytes, which form a pointer to the memory area where the actualdata is stored. Dynamic arrays are advantageous when each individual UDT variable might hosta different number of array items. As with all dynamic arrays, if you don't dimension a dynamic
array within aU
DT before accessing its items, you get an error 9"S
ubscript out of range."
More Topics on Visual Basic 6 Arrays
y Visual Basic 6 Arrays and variantsy Assigning and returning arraysy Byte arraysy Inserting and deleting items using arraysy Sorting using Arraysy Arrays of arrays
See Also
y Control Arrays in Visual Basic 6y User-Defined-Data typesy Constants, Data Type Conversion, Visual Basic Built-in Functionsy VB6 - Date and Time Functionsy Variables in Visual Basic 6y Visual Basic 6 Procedures
VB6 Arrays and variants (Visual Basic 6)
Visual Basic lets you store arrays in Variant variables and then access the array items using theVariant variable as if it were an array:
-
8/8/2019 Variables in Visual Basic 6
38/64
ReDim Names(100) As String, var As Variant' Initialize the Names array (omitted).var = Names() ' Copy the array into the Variant.Print var(1) ' Access array items through the Variant.
You can even create an array of Variant elements on the fly using the Array function and store itin a Variant variable:
' Arrays returned by the Array() function are zero-based.Factorials = Array(1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800)
Likewise, you can pass an array to a procedure that expects a Variant parameter and then accessthe elements of the array through that parameter:
' A polymorphic function that sums the values in any arrayFunction ArraySum(arr As Variant) As Variant
Dim i As Long, result As VariantFor i = LBound(arr) To UBound(arr)result = result + arr(i)NextArraySum = result
End Function
The most interesting feature of the preceding routine is that it works correctly with any type ofnumeric one-dimensional array. It even works with String arrays, but in that case you get theconcatenation of all items, not their sum. This procedure is extremely powerful and reduces theamount of code you have to write to deal with different kinds of arrays. But you should be aware
that accessing array items through a Variant parameter noticeably slows down the execution. Ifyou need the best performance, write specific routines that process specific types of arrays.
You can also pass a multidimensional array to a routine that expects a Variant parameter. In thiscase, you can still access the array elements through the Variants, but if you don't know atcompile time how many dimensions the array has, your routine has to determine that numberbefore proceeding. You can get this value using a trial-and-error approach:
' This routine returns the number of dimensions of the array' passed as an argument, or 0 if it isn't an array.Function NumberOfDims(arr As Variant) As IntegerDim dummy as LongOn Error Resume NextDodummy = UBound(arr, NumberOfDims + 1)IfErr Then Exit DoNumberOfDims = NumberOfDims + 1LoopEnd Function
-
8/8/2019 Variables in Visual Basic 6
39/64
It's perfectly legal to use the function name inside a function's code as if it were a local variable,as the previous code snippet does. Often this technique lets you save a local variable and a finalassignment before exiting the routine, which indirectly makes your code run slightly faster.
Here's a modified ArraySum routine that uses NumberOfDims and works with both one- and
two-dimensional arrays:
Function ArraySum2(arr As Variant) As VariantDim i As Long, j As Long, result As Variant' First check whether we can really work with this array.Select Case NumberOfDims(arr)Case 1 ' One-dimensional arrayFor i = LBound(arr) To UBound(arr)result = result + arr(i)NextCase 2 ' Two-dimensional array
For i = LBound(arr) ToU
Bound(arr)For j = LBound(arr, 2) To UBound(arr, 2)result = result + arr(i, j)NextNextCase Else ' Not an array, or too many dimensions
Err.Raise 1001, , "Not an array or more than two dimensions"End SelectArraySum2 = resultEnd Function
Often, if a Variant contains an array, you don't know the basic type of that array in advance. TheVarType function returns the sum of the vbArray constant (decimal 8192), plus the VarType ofthe data included in the array. This lets you test that the array passed to a routine is of a giventype:
If VarType(arr) = (vbArray + vbInteger) Then' Array of integersElseIf VarType(arr) = (vbArray + vbLong) Then' Array of LongsElseIf VarType(arr) And vbArray Then' An array of another type (just tests a bit)End If
You can also test whether a Variant holds an array using the IsArray function. When a Variantvariable holds an array, the TypeName function appends a pair of empty parentheses to its result:
Print TypeName(arr) ' Displays "Integer()"
-
8/8/2019 Variables in Visual Basic 6
40/64
As I've explained, you can either assign an array to a Variant variable or you can pass an array asa Variant parameter of a procedure. While the two operations look very similar, they'resubstantially different. To execute an assignment, Visual Basic makes a physical copy of thearray. As a result, the Variant variable doesn't point to the original data but to the copy; from thispoint on, all the manipulations you do through the Variant variable don't affect the original array.
Conversely, if you call a procedure and pass an array as a Variant parameter, no data isphysically copied and the Variant simply works as an alias of the array. You can reorder arrayitems or modify their values, and your changes are immediately reflected in the original array
More Topics on Visual Basic 6 Arrays
y Arrays in Visual Basic 6y Assigning and returning arraysy Byte arraysy Inserting and deleting items using arraysy Sorting using Arraysy
Arrays of arrays
See Also
y Control Arrays in Visual Basic 6y User-Defined-Data typesy Constants, Data Type Conversion, Visual Basic Built-in Functionsy Date and Time Functionsy Variables in Visual Basic 6y Visual Basic 6 Procedures
Assigning and returning arrays in Visual
Basic 6
-
8/8/2019 Variables in Visual Basic 6
41/64
Visual Basic 6 adds two important features to arrays. First, you can perform assignmentsbetween arrays. Second, you can write procedures that return arrays. You can assign arrays onlyof the same type and only if the target is a dynamic array. (The latter condition is necessarybecause Visual Basic might need to resize the target array.)
ReDim a(10, 10) As IntegerDim b() As Integer' Fill the a array with data (omitted).b() = a() ' This works!
It's no surprise that native assignment commands are always faster than the correspondingForNext loops that copy one item at a time. The actual increment in speed heavily depends onthe data type of the arrays and can vary from 20 percent to 10 times faster. A native assignmentbetween arrays also works if the source array is held in a Variant. Under Visual Basic 4 and 5,you could store an array in a Variant, but you couldn't do the oppositethat is, retrieve an arraystored in a Variant variable and store it back in an array of a specific type. This flaw has been
fixed in Visual Basic 6:
Dim v As Variant, s(100) As String, t() As String' Fill the s() array (omitted).v = s() ' Assign to a Variant.t() = v ' Assign from a Variant to a dynamic string array.
You often use the capacity to assign arrays to build functions that return arrays. Notice that pairof brackets at the end of the first line in the following procedure:
Function InitArray(first As Long, Last As Long) As Long()
ReDim result(first To Last) As LongDim i As LongFor i = first To Lastresult(i) = iNextInitArray = resultEnd Function
The new capability of returning arrays lets you write highly versatile array routines. Visual Basic6 itself includes a few new string functionsnamely Join, Split, and Filterthat rely on it.(You'll find more about these new string functions in Chapter 5). Here are two examples of whatyou can do with this intriguing feature:
' Returns a portion of a Long array' Note: fails if FIRST or LAST are not validFunction SubArray(arr() As Long, first As Long, last As Long, _newFirstIndex As Long) As Long()Dim i As LongReDim result(newFirstIndex To last _ first + newFirstIndex) As Long
-
8/8/2019 Variables in Visual Basic 6
42/64
For i = first To lastresult(newFirstIndex + i - first) = arr(i)NextSubArray = result
End Function
' Returns an array with all the selected items in a ListBoxFunction SelectedListItems(lst As ListBox) As String()Dim i As Long, j As LongReDim result(0 To lst.SelCount) As StringFor i = 0 To lst.ListCount - 1If lst.Selected(i) Thenj = j + 1result(j) = lst.List(i)End IfNextS
electedListItems = resultEnd Function
More Topics on Visual Basic 6 Arrays
y Arrays in Visual Basic 6y Visual Basic 6 Arrays and variantsy Byte arraysy Inserting and deleting items using arraysy Sorting using Arraysy Arrays of arrays
See Also
y Control Arrays in Visual Basic 6y User-Defined-Data typesy Constants, Data Type Conversion, Visual Basic Built-in Functionsy Date and Time Functionsy Variables in Visual Basic 6y Visual Basic 6 Procedures
Byte Arrays in VB6 (Visual Basic 6)
-
8/8/2019 Variables in Visual Basic 6
43/64
Byte arrays are somewhat special because Visual Basic lets you directly assign strings to them.In this case, Visual Basic performs a direct memory copy of the contents of the string. Because
all Visual Basic 5 and 6 strings are Unicode strings (two bytes per character), the target array isredimensioned to account for the actual string length in bytes (which you can determine usingthe LenB function). If the string contains only characters whose code is in the range 0 through255 (the case if you work with Latin alphabets), every other byte in the array will be 0:
Dim b() As Byte, Text As StringText = "123"b() = Text ' Now b() contains six items: 49 0 50 0 51 0
It's also possible to perform the opposite operation:
Text = b()
This special treatment reserved for Byte arrays is meant to ease the conversion from old VisualBasic 3 applications that use strings to hold binary data, as I explained in "The Byte Data Type"section, earlier in this chapter. You can exploit this feature to create blindingly fast stringroutines when you have to process each individual character in a string. For example, see howquickly you can count all the spaces in a string:
' NOTE: this function might not work with non-Latin alphabets.Function CountSpaces(Text As String) As LongDim b() As Byte, i As Long
b() = TextFor i = 0 To UBound(b) Step 2' Consider only even-numbered items.' Save time and code using the function name as a local variable.If b(i) = 32 Then CountSpaces = CountSpaces + 1NextEnd Function
-
8/8/2019 Variables in Visual Basic 6
44/64
The preceding routine is about three times faster than a regular routine, which uses Asc andMid$ functions to process all the characters in the argument, and even faster if you turn on theRemove Array Bounds Check compiler optimization. The only drawback of this technique is thatit isn't Unicode-friendly because it considers only the least significant byte in each 2-bytecharacter. If you plan to convert your application to some language that relies on Unicode
Japanese, for exampleyou should stay clear of this optimization technique.
More Topics on Visual Basic 6 Arrays
y Arrays in Visual Basic 6y Visual Basic 6 Arrays and variantsy Assigning and returning arraysy Inserting and deleting items using arraysy Sorting using Arraysy Arrays of arrays
See Also
y Control Arrays in Visual Basic 6y User-Defined-Data typesy Constants, Data Type Conversion, Visual Basic Built-in Functionsy Date and Time Functionsy Variables in Visual Basic 6y Visual Basic 6 Procedures
Inserting and deleting items using Arrays-Visual Basic 6
-
8/8/2019 Variables in Visual Basic 6
45/64
Some of the most common operations you perform on arrays are inserting and deleting items,shifting all the remaining elements toward higher indices to make room or toward lower indicesto fill the "hole" a deletion has left. You usually do this with a ForNext loop, and you can evenwrite generic array procedures that work with any type of array (with the usual restrictions aboutarrays ofUDTs and fixed-length strings that can't be passed to a Variant parameter):
Sub InsertArrayItem(arr As Variant, index As Long, newValue As Variant)Dim i As LongFor i = UBound(arr) - 1 To index Step -1arr(i + 1) = arr(i)Nextarr(index) = newValueEnd Sub
Sub DeleteArrayItem(arr As Variant, index As Long)Dim i As Long
For i = index ToU
Bound(arr) - 1arr(i) = arr(i + 1)Next' VB will convert this to 0 or to an empty string.arr(UBound(arr)) = EmptyEnd Sub
If your application works intensively with arrays, you might find that an approach based onForNext loops is too slow. In some cases, you can considerably speed up these operations byusing the RtlMoveMemory API function, which many Visual Basic programmers know under itspopular alias name, CopyMemory.1 This function lets you move a block of bytes from one
memory address to another memory address and works correctly even if the two areas partiallyoverlap. Here's the code that inserts a new item in an array of Longs:
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _(dest As Any, source As Any, ByVal numBytes As Long)
Sub InsertArrayItemLong(arr() As Long, index As Long, newValue As Long)' We let VB evaluate the size of each item using LenB().If index < UBound(arr) ThenCopyMemory arr(index + 1), arr(index), _(UBound(arr) _ index) * LenB(arr(index))End Ifarr(index) = newValueEnd Sub
Sub DeleteArrayItemLong(arr() As Long, index As Long)If index < UBound(arr) ThenCopyMemory arr(index), arr(index + 1), _(UBound(arr) _ index) * LenB(arr(index))
-
8/8/2019 Variables in Visual Basic 6
46/64
End Ifarr(index) = EmptyEnd Sub
IMPORTANT NOTE: The prerequisite for using the CopyMemory API function is that data
must be stored in contiguous memory locations, so you absolutely can't use it to insert or removeelements in String and Object arrays, nor in arrays ofUDTs that contain conventional strings,object references, or dynamic arrays. (Fixed-length strings and static arrays inUDTs are OK,though.)
Note that while you can't use the preceding routines for arrays other than Long arrays, thestatements in the procedure body can be recycled for another data type without any change,thanks to the use of the LenB function. Therefore, you can derive new array functions that workfor other data types by simply modifying the procedure's name and its parameter list. Forexample, you can create a new function that deletes an item in a Double array by editing just thefirst line of code (shown in boldface):
Sub DeleteArrayItemDouble(arr() As Double, index As Long)' All the other statements here are the same as in DeleteArrayItemLong' ...End Sub
More Topics on Visual Basic 6 Arrays
y Arrays in Visual Basic 6y Visual Basic 6 Arrays and variantsy Assigning and returning arraysy
Byte arraysy Sorting using Arraysy Arrays of arrays
See Also
y Control Arrays in Visual Basic 6y User-Defined-Data typesy Constants, Data Type Conversion, Visual Basic Built-in Functionsy Date and Time Functionsy Variables in Visual Basic 6y Visual Basic 6 Procedures
Sorting Data using Arrays - Visual Basic 6
-
8/8/2019 Variables in Visual Basic 6
47/64
Sorting is an operation that you often perform on arrays. As you probably know, there are dozensof different sort algorithms, each one with its strengths and weaknesses. I found that the Shell
Sort algorithm works well in most cases, and I've prepared a generic routine that sorts any one-dimensional array of a data type compatible with the Variant type, either in ascending ordescending order:
Sub ShellSortAny(arr As Variant, numEls As Long, descending As Boolean)Dim index As Long, index2 As Long, firstItem As LongDim distance As Long, value As Variant' Exit if it is not an array.If VarType(arr) < vbArray Then Exit SubfirstItem = LBound(arr)' Find the best value for distance.
Dodistance = distance * 3 + 1Loop Until distance > numEls' Sort the array.Dodistance = distance \ 3For index = distance + firstItem To numEls + firstItem - 1value = arr(index)index2 = indexDo While (arr(index2 - distance) > value) Xor descendingarr(index2) = arr(index2 - distance)
index2 = index2 - distanceIf index2 - distance < firstItem Then Exit DoLooparr(index2) = valueNextLoop Until distance = 1End Sub
-
8/8/2019 Variables in Visual Basic 6
48/64
More Topics on Visual Basic 6 Arrays
y Arrays in Visual Basic 6y Visual Basic 6 Arrays and variantsy Assigning and returning arraysy
Byte arraysy Inserting and deleting items using arraysy Arrays of arrays
See Also
y Control Arrays in Visual Basic 6y User-Defined-Data typesy Constants, Data Type Conversion, Visual Basic Built-in Functionsy Date and Time Functionsy Variables in Visual Basic 6y
Visual Basic 6 Procedures
Arrays of arrays in VB6 (Visual Basic 6)
While you can create two-dimensional arrays in Visual Basic, their structure isn't really flexiblefor at least two reasons: All rows in the array must have the same number of elements, and you
can use ReDim Preserve to change the number of columns but you can't add new rows. The firstpoint is especially important because it often leads you to declare an array that's far too large foryour needs, thus allocating a lot of memory that in most cases remains largely unused. You cansolve both problems using a structure known as an array of arrays.
The technique is conceptually simple: Since you can store an array in a Variant variable, you canbuild an array of Variants, where each item holds an array. Each subarraya row of this pseudo-
-
8/8/2019 Variables in Visual Basic 6
49/64
arraycan hold a different number of elements, and you don't need to use more memory than isstrictly necessary.
Here's an example, based on an imaginary PIM (Personal Information Manager) program. In this
program, you need to keep track of a list of appointments for each day of the year. The simplestsolution would be to use an array in which each row corresponds to a day in the year and eachcolumn to a possible appointment. (For the sake of simplicity, let's assume that eachappointment's data can be held in a string.)
ReDim apps(1 To 366, 1 To MAX_APPOINTMENTS) As String
Of course, you now have the problem of setting a reasonable value for theMAX_APPOINTMENTS symbolic constant. It should be high enough to account for all possibleappointments in a day but not too high because you might be wasting a lot of memory withoutany real reason. Let's see how the array of arrays technique can help us save memory without
posing any artificial limit to your application:
' A module-level variableDim apps(1 To 366) As Variant
' Add an appointment for a given day.Sub AddNewAppointment(day As Integer, description As String)Dim arr As VariantIf IsEmpty(apps(day)) Then' This is the first appointment for this day.apps(day) = Array(description)E
lse' Add the appointment to those already scheduled.arr = apps(day)ReDim Preserve arr(0 To UBound(arr) + 1) As Variantarr(UBound(arr)) = descriptionapps(day) = arrEnd IfEnd Sub
-
8/8/2019 Variables in Visual Basic 6
50/64
' Extract all the appointments for a given day.Sub ListAppointments(day As Integer, lst As ListBox)Dim i As LongFor i = 0 To UBound(apps(1))lst.AddItem apps(1)(i)
NextEnd Sub
In this example, I kept the code as simple as possible and used an array of Variant arrays. Youcould save even more memory if each row of this array were built using an array of a morespecific data type (String, in this case). Note the special syntax used to address an item in anarray of arrays:
' Change the description for the Nth appointment.apps(day)(n) = newDescription
Nothing keeps you from extending this concept further, introducing an array of arrays of arrays,and so on. If you're dealing with arrays in which each row can vary considerably in length, thisapproach is going to save you a lot of memory and, in most cases, improve your overallperformance too. A key feature of an array of arrays is that you can process entire rows of yourpseudo-array as if they were single entities. For example, you can swap them, replace them, addand delete them, and so on.
' Move the January 1st appointments to January 2nd.apps(2) = apps(1)apps(1) = Empty
Finally, an important advantage of this technique is that you can add new rows without losing thecurrent contents of the array. (Remember that you can use ReDim Preserve on regular arraysonly to modify the number of columns, not the number of rows.)
' Extend the appointment book for another nonleap year.ReDim Preserve apps(1 to UBound(apps) + 365) As Variant
More Topics on Visual Basic 6 Arrays
y Arrays in Visual Basic 6y Visual Basic 6 Arrays and variantsy
Assigning and returning arraysy Byte arraysy Inserting and deleting items using arraysy Sorting using Arrays
-
8/8/2019 Variables in Visual Basic 6
51/64
See Also
y Control Arrays in Visual Basic 6y User-Defined-Data typesy Constants, Data Type Conversion, Visual Basic Built-in Functionsy
Date and Time Functionsy Variables in Visual Basic 6y Visual Basic 6 Procedures
Control Arrays in Visual Basic 6
A control array is a group of controls that share the same name type and the same event
procedures. Adding controls with control arrays uses fewer resources than adding multiplecontrol of same type at design time.
A control array can be created only at design time, and at the very minimum at least one controlmust belong to it. You create a control array following one of these three methods:
y You create a control and then assign a numeric, non-negative value to its Index property;you have thus created a control array with just one element.
y You create two controls of the same class and assign them an identical Name property.Visual Basic shows a dialog box warning you that there's already a control with thatname and asks whether you want to create a control array. Click on the Yes button.
y You select a control on the form, press Ctrl+C to copy it to the clipboard, and then pressCtrl+V to paste a new instance of the control, which has the same Name property as theoriginal one. Visual Basic shows the warning mentioned in the previous bullet.
Control arrays are one of the most interesting features of the Visual Basic environment, and theyadd a lot of flexibility to your programs:
-
8/8/2019 Variables in Visual Basic 6
52/64
y Controls that belong to the same control array share the same set of event procedures; thisoften dramatically reduces the amount of code you have to write to respond to a user'sactions.
y You can dynamically add new elements to a control array at run time; in other words, youcan effectively create new controls that didn't exist at design time.
y Elements of control arrays consume fewer resources than regular controls and tend toproduce smaller executables. Besides, Visual Basic forms can host up to 256 different
control names, but a control array counts as one against this number. In other words,control arrays let you effectively overcome this limit.
The importance of using control arrays as a means of dynamically creating new controls at runtime is somewhat reduced in Visual Basic 6, which has introduced a new and more powerfulcapability.
Don't let the term array lead you to think control array is related to VBA arrays; they'recompletely different objects. Control arrays can only be one-dimensional. They don't need to be
dimensioned:E
ach control you add automatically extends the array. The Index propertyidentifies the position of each control in the control array it belongs to, but it's possible for acontrol array to have holes in the index sequence. The lowest possible value for the Indexproperty is 0. You reference a control belonging to a control array as you would reference astandard array item:
Text1(0).Text = ""
Sharing Event Procedures
Event procedures related to items in a control array are easily recognizable because they have an
extra Index parameter, which precedes all other parameters. This extra parameter receives theindex of the element that's raising the event, as you can see in this example:
Private Sub Text1_KeyPress(Index As Integer, KeyAscii As Integer)MsgBox "A key has been pressed on Text1(" & Index & ") control"End Sub
The fact that multiple controls can share the same set of event procedures is often in itself a goodreason to create a control array. For example, say that you want to change the background colorof each of your TextBox controls to yellow when it receives the input focus and restore itsbackground color to white when the user clicks on another field:
Private Sub Text1_GotFocus(Index As Integer)Text1(Index).BackColor = vbYellowEnd SubPrivate Sub Text1_LostFocus(Index As Integer)Text1(Index).BackColor = vbWhiteEnd Sub
-
8/8/2019 Variables in Visual Basic 6
53/64
Control arrays are especially useful with groups of OptionButton controls because you canremember which element in the group has been activated by adding one line of code to theirshared Click event. This saves code when the program needs to determine which button is theactive one:
' A module-level variableDim optFrequencyIndex As Integer
Private Sub optFrequency_Click(Index As Integer)' Remember the last button selected.optFrequencyIndex = IndexEnd Sub
Creating Controls at Run Time
Control arrays can be created at run time using the statements
y Load object (Index %)y Unload object (Index %)
Where object is the name of the control to add or delete from the control array. Index % is thevalue of the index in the array. The control array to be added must be an element of the existingarray created at design time with an index value of 0. When a new element of a control array isloaded, most of the property settings are copied from the lowest existing element in the array.
Following example illustrates the use of the control array.
* Open a Standard EXE project and save the Form as Calculator.frm and save the Project asCalculater.vbp.
* Design the form as shown below.
Object Property Setting
FormCaption
Name
Calculator
frmCalculator
CommandButton
Caption
Name
Index
1
cmd
0
CommandButtonCaption 2
-
8/8/2019 Variables in Visual Basic 6
54/64
Name
Index
cmd
1
CommandButton
Caption
Name
Index
3
cmd
2
CommandButton
Caption
Name
Index
4
cmd
3
CommandButton
Caption
Name
Index
5
cmd
4
CommandButton
Caption
Name
Index
6
cmd
5
CommandButton
Caption
Name
Index
7
cmd
6
CommandButton
Caption
Name
Index
8
cmd
7
CommandButton
Caption
Name
Index
9
cmd
8
CommandButton
Caption
Name
0
cmd
-
8/8/2019 Variables in Visual Basic 6
55/64
Index 10
CommandButton
Caption
Name
Index
.
cmd
11
CommandButtonCaption
Name
AC
cmdAC
CommandButtonCaption
Name
+
cmdPlus
CommandButtonCaption
Name
-
cmdMinus
CommandButtonCaption
Name
*
cmdMultiply
CommandButtonCaption
Name
/
cmdDivide
CommandButtonCaption
Name
+/-
cmdNeg
TextBoxName
Text
txtDisplay
( empty )
CommandButtonCaption
Name
=
cmdEqual
-
8/8/2019 Variables in Visual Basic 6
56/64
The following variables are declared inside the general declaration
Dim Current As DoubleDim Previous As DoubleDim Choice As String
Dim Result As Double
The following code is entered in the cmd_Click( ) (Control Array) event procedure
Private Sub cmd_Click(Index As Integer)txtDisplay.Text = txtDisplay.Text & cmd(Index).Caption'&is the concatenation operatorCurrent = Val(txtDisplay.Text)End Sub
The following code is entered in the cmdAC_Click ( ) event procedure
Private Sub cmdAC_Click()Current = Previous = 0txtDisplay.Text = ""End Sub
The below code is entered in the cmdNeg_Click( ) procedure
Private Sub cmdNeg_Click()Current = -CurrenttxtDisplay.Text = CurrentE
ndS
ub
The following code is entered in the click events of the cmdPlus, cmdMinus, cmdMultiply,cmdDevide controls respectively.
Private Sub cmdDevide_Click()txtDisplay.Text = ""Previous = CurrentCurrent = 0Choice = "/"End Sub
Private Sub cmdMinus_Click()txtDisplay.Text = ""Previous = CurrentCurrent = 0Choice = "-"End Sub
-
8/8/2019 Variables in Visual Basic 6
57/64
Private Sub cmdMultiply_Click()txtDisplay.Text = ""Previous = CurrentCurrent = 0Choice = "*"E
ndS
ub
Private Sub cmdPlus_Click()txtDisplay.Text = ""Previous = CurrentCurrent = 0Choice = "+"End Sub
To print the result on the text box, the following code is entered in the cmdEqual_Click ( ) eventprocedure.
Private Sub cmdEqual_Click()
Select Case Choice
Case "+"Result = Previous + CurrenttxtDisplay.Text = ResultCase "-"Result = Previous - CurrenttxtDisplay.Text = Result
Case "*"Result = Previous * CurrenttxtDisplay.Text = ResultCase "/"Result = Previous / CurrenttxtDisplay.Text = ResultEnd Select
Current = Result
End Sub
Save and run the project. On clicking digits of user's choice and an operator button, the outputappears.
Iterating on the Items of a Control Array
Control arrays often let you save many lines of code because you can execute the samestatement, or group of statements, for every control in the array without having to duplicate the
-
8/8/2019 Variables in Visual Basic 6
58/64
code for each distinct control. For example, you can clear the contents of all the items in an arrayof TextBox controls as follows:
For i = txtFields.LBound To txtFields.UBoundtxtFields(i).Text = ""
Next
Here you're using the LBound and UBound methods exposed by the control array object, whichis an intermediate object used by Visual Basic to gather all the controls in the array. In general,you shouldn't use this approach to iterate over all the items in the array because if the array hasholes in the Index sequence an error will be raised. A better way to loop over all the items of acontrol array is using the ForEach statement:
Dim txt As TextBoxForEach txt In txtFieldstxt.Text = ""
Next
A third method exposed by the control array object, Count, returns the number of elements itcontains. It can be useful on several occasions (for example, when removing all the controls thatwere added dynamically at run time):
' This code assumes that txtField(0) is the only control that was' created at design time (you can't unload it at run time).Do While txtFields.Count > 1Unload txtFields(txtFields.UBound)Loop
Arrays ofMenu Items
Control arrays are especially useful with menus because arrays offer a solution to theproliferation of menu Click events and, above all, permit you to create new menus at run time.An array of menu controls is conceptually similar to a regular control array, only you set theIndex property to a numeric (non-negative) value in the Menu Editor instead of in the Propertieswindow.
There are some limitations, though: All the items in an array of menu controls must be adjacentand must belong to the same menu level, and their Index properties must be in ascending order
(even though holes in the sequence are allowed). This set of requirements severely hinders yourability to create new menu items at run time. In fact, you can create new menu items in well-defined positions of your menu hierarchynamely, where you put a menu item with a nonzeroIndex valuebut you can't create new submenus or new top-level menus.
Now that you have a thorough understanding of how Visual Basic's forms and controls work,you're ready to dive into the subtleties of the Visual Basic for Applications (VBA) language.
-
8/8/2019 Variables in Visual Basic 6
59/64
User-Defined Data Types in Visual Basic 6
Variables of different data types when combined as a single variable to hold several relatedinformations is called a User-Defined data type.
A Type statement is used to define a user-defined type in the General declaration section of aform or module. User-defined data types can only be private in form while in standard modulescan be public or private. An example for a user defined data type to hold the product details is asgiven below.
Private Type ProductDetailsProdID as StringProdName as String
Price as CurrencyEnd Type
The user defined data type can be declared with a variable using the Dim statement as in anyother variable declaration statement. An array of these user-defined data types can also bedeclared. An example to consolidate these two features is given below.
Dim ElectronicGoods as ProductDetails ' One RecordDim ElectronicGoods(10) as ProductDetails ' An array of 11 records
A User-Defined data type can be referenced in an application by using the variable name in the
procedure along with the item name in the Type block. Say, for example if the text property of aTextBox namely text1 is to be assigned the name of the electronic good, the statement can bewritten as given below.
Text1.Text = ElectronicGoods.ProdName
If the same is implemented as an array, then the statement becomes
Text1.Text = ElectronicGoods(i).ProdName
User-defined data types can also be passed to procedures to allow many related items as one
argument.
Sub ProdData( ElectronicGoods as ProductDetails)Text1.Text = ElectronicGoods.ProdNameText1.Text = ElectronicGoods.PriceEnd Sub
-
8/8/2019 Variables in Visual Basic 6
60/64
Related Topics
y Control Structures - If...Then / if...Then...Else / Select Case Statementsy Loops in Visual Basic 6y Date and Time Functions in VB6y
Constants, Data Type Conversion, Visual Basic Built-in Functionsy Working with controls in Visual Basic 6
Constants, Data Type Conversion, Visual
Basic Built-in Functions
Constants
Constants are named storage locations in memory, the value of which does not change duringprogram Execution. They remain the same throughout the program execution. When the userwants to use a value that never changes, a constant can be declared and created. The Conststatement is used to create a constant. Constants can be declared in local, form, module or globalscope and can be public or private as for variables. Constants can be declared as illustratedbelow.
Public Const gravityconstant AsS
ingle = 9.81
Predefined Visual Basic Constants
The predefined constants can be used anywhere in the code in place of the actual numeric values.This makes the code easier to read and write.
For example consider a statement that will set the window state of a form to be maximized.
-
8/8/2019 Variables in Visual Basic 6
61/64
Form1.Windowstate = 2
The same task can be performed using a Visual Basic constant
Form1.WindowState = vbMaximized
Data Type Conversion
Visual Basic