Welcome
to
TechRiz
Where tech enthusiasts come for the latest tech news,
Free downloads, free tutorials, articles and how
to's.
Description:
This is the TechRiz Free Tutorials page.
Visit every day to stay informed about the
latest tech news,
from security alerts to Hardware and software
updates. Enjoy your stay.
Week 3 – Visual Basic
Tutorial
Repetition
Structures in Visual
Basic
A repetition structure allows the
programmer to that an action is to
be repeated until given condition is
true.
Do While... Loop Statement
The Do While...Loop is used to execute
statements until a certain condition is met. The following Do
Loop counts from 1 to 100.
Dim number As Integer
number = 1
Do While number <= 100
number = number + 1
Loop
A variable number is initialized to 1 and then the Do While
Loop starts. First, the condition is tested; if condition is
true, then the statements are executed. When it gets to the
Loop it goes back to the Do and tests condition again. If
condition is False on the first pass, the statements are never
executed.
While... Wend Statement
A While...Wend statement behaves like
Do While...Loop statement. The following
While...Wend counts from 1 to
100
Dim number As Integer
number = 1
While number <=100
number = number + 1
Wend
Do...Loop While Statement
The Do...Loop While statement first executes
the statements and then test the condition after each
execution. The following program block illustrates the
structure:
Dim number As Long
number = 0
Do
number = number + 1
Loop 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
statements between 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... Loop structure tests a condition
for falsity. Statements in the body of a Do
Until...Loop are executed repeatedly as long as the
loop-continuation test evaluates to False.
An example for Do Until...Loop statement. The
coding is typed inside the click event of the command
button
Dim number As Long
number=0
Do Until number > 1000
number = number + 1
Print number
Loop
Numbers between 1 to 1000 will be displayed on the form as soon
as you click on the command button.
The For...Next Loop
The For...Next Loop is another way to make
loops in Visual Basic. For...Next repetition
structure handles all the details of counter-controlled
repetition. The following loop counts the numbers from 1 to
100:
Dim x As Integer
For x = 1 To 50
Print x
Next
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 2
Print x
Next
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 numbers horizontally the following method
can be used.
For x = 1 To 50
Print 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 Integer
For number = 1 To 10
If number = 4 Then
Print "This is number 4"
Else
Print number
End If
Next
In the output instead of number 4 you will get the "This is
number 4".
Exit For and Exit Do
Statement
A For...Next loop condition can be terminated
by an Exit For statement. Consider the
following statement block.
Dim x As Integer
For x = 1 To 10
Print x
If x = 5 Then
Print "The program exited at x=5"
End If
Next
The preceding code increments the value of x by 1 until it
reaches the condition x = 5. The Exit For
statement is executed and it terminates the
For...Next loop. The Following statement block
containing Do...While loop is terminated using
Exit Do statement.
Dim x As Integer
Do While x < 10
Print x
x = x + 1
If x = 5 Then
Print "The program is exited at x=5"
Exit Do
End If
Loop
With...End With
statement
When
properties are set for objects or methods are called, a lot of
coding is included that acts on the same object. It is easier
to read the code by implementing the With...End
With statement. Multiple properties can be set
and multiple methods can be called by using the
With...End
With statement. The code is executed more
quickly and efficiently as the object is evaluated only
once. 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 every
associated property or method. This makes the coding
simpler and efficient.
VB Array - Arrays in
Visual Basic 6
An array is a consecutive group of memory
locations that all have the same name and the same type.
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 lower
bounds and the elements have to lie within those bounds.
Each index number in an array is allocated individual
memory space and therefore users must evade declaring
arrays of larger size than 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 data
type.
Declaring
arrays
Arrays occupy space in memory. The
programmer specifies the array type and the number of
elements required by the array so that the compiler may
reserve the appropriate amount of memory. Arrays may be
declared as Public (in a code module), module or local.
Module arrays are declared in the general declarations
using keyword Dim or Private. Local arrays are declared
in a procedure using Dim or Static. 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 the program
execution.
Dynamic array :
The size of the array can be changed at the
run time- size changes during the program
execution.
Fixed-sized
Arrays
When an upper bound is specified in the
declaration, a Fixed-array is created. The upper limit
should always be within the range of long data
type.
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 6 elements, with index
numbers running from 0 to 5.
If we want to specify the lower limit, then
the parentheses should include both the lower and upper
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 represent
tables of values consisting of information arranged in
rows and columns. To identify a particular table element,
we must specify two indexes: The first (by convention)
identifies the element's row 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
than two 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 size
arrays. 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
Basically, you can create either static or
dynamic arrays. Static arrays must include a fixed number
of items, and this number must be known at compile time
so that the compiler can set aside the necessary amount
of memory. You create a static array using a Dim
statement with a constant 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 101
items.
Most programs don't use static arrays
because programmers rarely know at compile time how many
items you need and also because static arrays can't be
resized during execution. Both these issues 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 a module 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 String
End Sub
If you're creating an array that's local to
a procedure, you can do everything with a single ReDim
statement:
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 Option
Base 1 statement is placed at the beginning of the
module. My suggestion is this: Never use an Option Base
statement because it makes code reuse more difficult.
(You can't cut and paste routines without worrying about
the current Option Base.) If you want to explicitly use a
lower index 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 you
re-create a dynamic array, its contents are reset to 0
(or to an empty string) and you lose the data it
contains. If you want to resize an array without losing
its contents, use the ReDim Preserve command:
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 the
values 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 Basic
releases 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 the array has
two or more dimensions, you need to pass a second
argument to these functions to specify the dimension you
need:
Print LBound(Cells, 1) ' Displays 1,
lower index of 1st dimension
Print LBound(Cells) ' Same as above
Print UBound(Cells, 2) ' Displays 20, upper index of 2nd
dimension
' Evaluate total number of elements.
NumEls = (UBound(Cells) _ LBound(Cells) + 1) * _
(UBound(Cells, 2) _ LBound(Cells, 2) + 1)
Arrays
within UDTs
UDT structures can include both static and
dynamic arrays. Here's a sample structure that contains
both types:
Type MyUDT
StaticArr(100) As Long
DynamicArr() As Long
End 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
The
memory needed by a static array is allocated within the UDT
structure; for example, the StaticArr array in the preceding
code snippet takes exactly 400 bytes. Conversely, a dynamic
array in a UDT takes only 4 bytes, which form a pointer to the
memory area where the actual data is stored. Dynamic arrays are
advantageous when each individual UDT variable might host a
different number of array items. As with all dynamic arrays, if
you don't dimension a dynamic array within a UDT before
accessing its items, you get an error
9—"Subscript
out of range."
VB6 Arrays and variants (Visual Basic
6)
Visual Basic lets you store arrays in
Variant variables and then access the array items using
the Variant variable as if it were an array:
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 it
in 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
access the elements of the array through that
parameter:
' A polymorphic function that sums the
values in any array
Function ArraySum(arr As Variant) As Variant
Dim i As Long, result As Variant
For i = LBound(arr) To UBound(arr)
result = result + arr(i)
Next
ArraySum = result
End Function
The most interesting feature of the
preceding routine is that it works correctly with any
type of numeric one-dimensional array. It even works with
String arrays, but in that case you get the concatenation
of all items, not their sum. This procedure is extremely
powerful and reduces the amount 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. If you
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 this
case, you can still access the array elements through the
Variants, but if you don't know at compile time how many
dimensions the array has, your routine has to determine
that number before 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 Integer
Dim dummy as Long
On Error Resume Next
Do
dummy = UBound(arr, NumberOfDims + 1)
If Err Then Exit Do
NumberOfDims = NumberOfDims + 1
Loop
End Function
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 final
assignment 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
Variant
Dim 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 array
For i = LBound(arr) To UBound(arr)
result = result + arr(i)
Next
Case 2 ' Two-dimensional array
For i = LBound(arr) To UBound(arr)
For j = LBound(arr, 2) To UBound(arr, 2)
result = result + arr(i, j)
Next
Next
Case Else ' Not an array, or too many dimensions
Err.Raise 1001, , "Not an array or more than two
dimensions"
End Select
ArraySum2 = result
End Function
Often, if a Variant contains an array, you
don't know the basic type of that array in advance. The
VarType function returns the sum of the vbArray constant
(decimal 8192), plus the VarType of the data included in
the array. This lets you test that the array passed to a
routine is of a given type:
If VarType(arr) = (vbArray +
vbInteger) Then
' Array of integers
ElseIf VarType(arr) = (vbArray + vbLong) Then
' Array of Longs
ElseIf 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 Variant variable
holds an array, the TypeName function appends a pair of
empty parentheses to its result:
Print TypeName(arr) ' Displays
"Integer()"
As I've explained, you can either assign an
array to a Variant variable or you can pass an array as a
Variant parameter of a procedure. While the two
operations look very similar, they're substantially
different. To execute an assignment, Visual Basic makes a
physical copy of the array. As a result, the Variant
variable doesn't point to the original data but to the
copy; from this point 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 is physically
copied and the Variant simply works as an alias of the
array. You can reorder array items or modify their
values, and your changes are immediately reflected in the
original array.
|