0% found this document useful (0 votes)
21 views6 pages

VB6 Variables and Data Types Guide

The document provides an overview of variables and data types in VB6, explaining how memory is utilized to store values in a program. It categorizes data types into numeric and non-numeric, detailing their characteristics and storage requirements. Additionally, it outlines rules for naming variables, methods for declaring them, and the scope and initialization of variables and constants.

Uploaded by

Ningombam Jimson
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views6 pages

VB6 Variables and Data Types Guide

The document provides an overview of variables and data types in VB6, explaining how memory is utilized to store values in a program. It categorizes data types into numeric and non-numeric, detailing their characteristics and storage requirements. Additionally, it outlines rules for naming variables, methods for declaring them, and the scope and initialization of variables and constants.

Uploaded by

Ningombam Jimson
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Variables and Data Type in VB6

Definition
The computer memory is made of small storage areas used to hold the things that a program needs
while it is running. As a programmer, we need to specify these things, or we provide them to the
computer; the computer then puts them in these storage areas. When we need one of them, we let the
computer know. The machine located it and makes it available to us to use as we see fit.
Variables are the names we give to computer memory locations which are used to store values in
a computer program. VB divides data into different types so that they are easier to manage when we
need to write the code involving those data. VB6 classifies the information mentioned above into two
major data types, they are the numeric data types and the non-numeric data types.

Numeric Data types


Numeric data types are types of data that consist of numbers that can be computed mathematically
with standard operators. In Visual Basic, numeric data are divided into 7 types, depending on the
range of values they can store.
Calculations that only involve round figures can use Integer or Long integer in the computation.
Programs that require high precision calculation need to use Single and Double decision data types,
they are also called floating point numbers. For currency calculation , you can use the currency data
types. Lastly, if even more precision is required to perform calculations that involve many decimal
points, we can use the decimal data types.
The table below lists the various numeric Data Types, what data they can store and how many
bytes they use.

Data type Storage Size Range


Byte 1 byte 0 to 255
Integer 2 bytes -32,768 to 32,767
Long 4 bytes -2,147,483,648 to 2,147,483,648
-3.402823E+38 to -1.401298E-45 for negative values
Single 4 bytes
1.401298E-45 to 3.402823E+38 for positive values.
-1.79769313486232e+308 to -4.94065645841247E-
Double 8 bytes 324 for negative values 4.94065645841247E-324 to
1.79769313486232e+308 for positive values.
Currency 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807
+/- 79,228,162,514,264,337,593,543,950,335 if no decimal
Decimal 12 bytes is use +/- 7.9228162514264337593543950335 (28 decimal
places).

Non-Numeric Data types


Nonnumeric data types are data that cannot be manipulated mathematically. Non-numeric data com-
prises string data types, date data types, boolean data types that store only two values (true or false),
object data type and Variant data type . The non-numeric data types are summarized in table below

1
Data type Storage Size Range
String(fixed Length of
1 to 65,400 characters
length) string
String(variable Length + 10
0 to 2 billion characters
length) bytes
Date 8 bytes January 1, 100 to December 31, 9999
Boolean 2 bytes True or False
Object 4 bytes Any embedded object
Variant(numeric) 16 bytes Any value as large as Double
Length+22
Variant(text) Same as variable-length string
bytes
By default Visual Basic variables are of variant data types. The variant data type can store numeric,
date/time or string data. When a variable is declared, a data type is supplied for it that determines
the kind of data they can store. A Variant can be used to declare any kind of variable. We can use
a variant when we can’t make up our mind regarding a variable but, as a beginning programmer, we
should avoid it.

Rules for naming a variable in VB


These are the rules to follow when naming elements in VB

• A variable name must begin with a letter.

• It must be less than 255 characters.

• No spacing is allowed.

• It must not begin with a number

• Period is not permitted

• Cannot use exclamation mark (!), or the characters @, &, $, #

• Cannot repeat names within the same level of scope.

Variable Declaration in VB
There are many ways of declaring variables in Visual Basic. Depending on where the variables are
declared and how they are declared, we can determine how they can be used by our application. The
different ways of declaring variables in Visual Basic are listed below

• Explicit Declaration

• Using Option Explicit statement

• Scope of Variables

Explicit Declaration
Declaring a variable tells Visual Basic to reserve space in memory. It is not must that a variable
should be declared before using it. Automatically whenever Visual Basic encounters a new variable,
it assigns the default variable type and value. This is called implicit declaration. In Visual Basic, it
is a good practice to declare the variables before using them by assigning names and data types. The

2
variables are declared with a Dim statement to name the variable and its type. The As type clause in
the Dim statement allows to define the data type or object type of the variable. This is called explicit
declaration. The syantax is as follows:

Dim VariableNames As Data Type

Example for variable declaration

Dim strName as String


Dim num as Integer

If we want to declare more variables, we can declare them in separate lines or we may also combine
more in one line , separating each variable with a comma, as follows:

Dim Variable1 As DataType1, Variable2 As DataType2

Using Option Explicit statement


It may be convenient to declare variables implicitly, but it can lead to errors that may not be recognized
at run time. Say, for example a variable by name intcount is used implicitly and is assigned to a
value. In the next step, this field is incremented by 1 by the following statement

Intcount = Intcont + 1

This calculation will result in intcount yielding a value of 1 as intcount would have been initialized
to zero. This is because the intcount variable has been mistyped as intcont in the right hand
side of the second variable. But Visual Basic does not see this as a mistake and considers it to 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 the following
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 the module
for usage of any undeclared variables and reports an error to the user. The user can thus rectify the
error on seeing this error message.

Scope of variables
A variable is scoped to a procedure-level (local) or module-level variable depending on how it is
declared. The scope of a variable, procedure or object determines which part of the code in our
application are aware of the variable’s existence. A variable is declared in general declaration section
of e Form, and hence is available to all the procedures. Local variables are recognized only in the
procedure in which they are declared. They can be declared with Dim and Static 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. Other than using the Dim keyword to
declare the data, we can also use other keywords to declare the data. Three other keywords are private
,static and public.

1. Local Variables: A local variable is one that is declared inside a procedure. This variable
is only available to the code inside the procedure and can be declared using the Private
statements. The syntax for declaring a private/local variable is given below

Private VariableName as Datatype

3
However, Private is rarely used, we normally use Dim to declare a local variable. The
local variables exist as long as the procedure in which they are declared, is executing. Once a
procedure is executed, the values of its local variables are lost and the memory used by these
variables is freed and can be reclaimed. Variables that are declared with keyword Dim exist
only as long as the procedure is being executed.
2. Static Variables: Static variables are not reinitialized each time VB Invokes a procedure and
therefore retains or preserves value even when a procedure ends. In case we need to keep track
of the number of times 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 static variable is declared as given below.

Static VariableName as Datatype

The Static keyword declares a variable that is being used multiple times, even after a pro-
cedure has been terminated. Most variables created inside a procedure are discarded by Visual
Basic when the procedure is finished, static keyword preserves the value of a variable even after
the procedure is terminated.
3. Public Variables: When a variable is declared as global it is visible to all procedures and
modules that comprise the application. Global variables, as with Module level variables, must
be declared outside of any procedures in the Declarations section and must use the Public
keyword. The syntax for declaring a global variable is as follows:

Public VariableName as Datatype

Public is the keyword that declares a global variable, which means it can be used by all the
procedures and modules of the whole program.

Constant in VB6
Constants are different from variables in the sense that their values do not change during the running of
the program. Constants, once declared and initialized cannot be changed (hence the name constant’
and are declared using the Visual Basic Const keyword. The syntax for declaring variables is as
follows:
Const constName As datatype = value
Generally, in visual basic the constant field values are set at compile-time and those values will never
be changed.

Initializing Visual Basic Variables


Visual Basic variables may be initialized either during the declaration, or after the declaration. Unless
there is a good reason to do otherwise, it is recommended that variables be initialized during the
declaration.
Initialization is performed using the Visual Basic assignment operator (=). To initialize a single
variable when it is declared:
Dim num As Integer = 5
When declaring multiple variables each variable may be initialized in the declaration line:
Dim strName As String = "Fred", num1 As Integer = 5

4
Assigning New Values to Visual Basic Variables
Once a variable has been declared, a new value can be assigned to the variable at any time using the
variable name and the assignment (=) operator. In the following sample Visual Basic code, a variable
is declared and initialized to 10. It is then re-assigned the value of 20:

Dim num As Integer = 10


num = 20

Scope of a Variable and Constant in VB


Variables and constants can be declared anywhere in a Visual Basic project. It is important to un-
derstand, therefore, that where and how the variable is declared dictates the scope of that variable.
The scope of a variable relates to where else in the application source code the variable is accessible.
There are four levels of scope in a Visual Basic application:

1. Block Level Scope: When a variable or constant is declared in a distinct code structure (such
as an If statement or Do loop), the variable is only visible and accessible to the code within that
structure. For example, in the following code the intCustCount variable is only accessible to
code within the If statement:

If blnNewCustomer Then
Dim intCustCount As Integer
For intCustCount = 1 to 50
Do ReadCustRecord()
Next InCustCount
End if

2. Procedure Level Scope: Variables and constants declared within a Visual Basic procedure (i.e.
a Function or Subroutine) are only visible and accessible to code within that procedure (for
details of Visual Basic procedures see Visual Basic Modules and Procedures. For example, the
variable intResult in the following code is only visible to code within the function:

Public Function PercentageOf(ByVal value1 As Integer,


ByVal value2 As Integer) As Integer
Dim intResult As Integer
intResult = (value1 / value2) * 100
Return intResult
End Function

3. Module Level Scope: When a variable or constant is declared outside of any procedures or code
structures in a Module it is deemed to have module level scope. This means that the variable or
constant is visible to all Visual Basic code contained in the same module, regardless of whether
that code is located in a procedure or not. There is a section at the top of each module called the
Declarations Section for this purpose. The Declaration section is located above all procedures
and code in a module.

4. Global Scope: When a variable or constant is declared as global it is visible to all procedures
and modules that comprise the application. Global variables and constants, as with Module
level variables, must be declared outside of any procedures in the Declarations section and
must use the Public keyword. The syntax for declaring a global variable is as follows:

5
Public variableName As dataType

Similarly, a global constant is defined using the following syntax:

Public Const constName As dataType

Suffixes for Literals


Literals are values that we assign to a data. In some cases, we need to add a suffix behind a literal
so that VB can handle the calculation more accurately. For example, we can use num=1.3089# for a
Double type data. Some of the suffixes are displayed in Table below:

Suffix Literal
& Long
! Single
# Double
@ Currency
In addition, we need to enclose string literals within two quotations and date and time literals within
two # sign. Strings can contain any characters, including numbers. The following are few examples:

Name="Turban, John."
TelNumber="1800-900-888-777"
LastDay=#31-Dec-00#
ExpTime=#12:00 am#

Common questions

Powered by AI

Explicit variable declaration in Visual Basic offers several advantages over implicit declaration by increasing code clarity and reducing runtime errors . Explicitly declaring variables with the 'Dim' or other specific keywords ensures that memory is allocated intentionally and allows the programmer to specify data types, which aids in both memory management and type checking . This reduces the risk of errors due to mistyped variable names, as such errors are caught at compile-time when Option Explicit is used . Implicit declaration, conversely, can lead to subtle bugs where mistyped variable names create new variables rather than throwing errors, a pitfall that explicit declaration avoids, enhancing reliability and maintainability in code .

Public variables in Visual Basic, declared with the keyword 'Public', have global scope, meaning they can be accessed by any procedure or module within the application, providing versatile and extensive accessibility . In contrast, private variables, primarily declared within procedures using 'Private' or 'Dim', are local to the procedure, only accessible within the scope of that procedure and not outside it . This limited accessibility ensures encapsulation and helps in managing variable states within complex applications, granting control over variable access and potential modifications .

In Visual Basic, variable scope defines where a variable is accessible within an application and is classified into block level, procedure level, module level, and global scope . Block level scope limits a variable to a specific code block, such as within an If statement, making it inaccessible outside the block . Procedure level scope confines a variable to a procedure, thus it cannot be accessed outside that function or subroutine . Module level scope allows a variable to be accessible to any code within the same module, regardless of procedures . Global scope extends the variable's visibility to all procedures and modules within the application, providing the most extensive access range . Understanding scope is crucial for effective memory management and ensuring variables are modified and accessed properly throughout different parts of a program.

In Visual Basic, the 'Dim' keyword is used for declaring local variables within procedures, establishing procedural scope, and the variables exist only during the execution of that procedure . The 'Static' keyword, however, is used to declare variables that retain their values even after a procedure ends, which is useful for maintaining state across multiple procedure invocations, like tracking the number of times an action occurs . The 'Public' keyword declares global variables, giving them application-wide accessibility, making them ideal for values that need to be consistent and shared across different modules and procedures within an application . These keywords cater to different use-cases based on scope, lifespan, and application needs, enhancing code modularity and functionality .

Variant data types in Visual Basic are versatile, allowing the storing of different data types (numeric, string, date/time) without specifying a distinct data type at the time of declaration, which provides flexibility in handling dynamic data input . However, excessive use of variant data types can lead to inefficient memory usage and reduce the clarity of the code because the data type isn't explicitly stated, which can make the code harder to read and maintain . Moreover, using variants can introduce performance overhead due to type checking at runtime, as the compiler cannot optimize for specific data types during compilation. As such, variants are best used sparingly when flexibility is essential, but not as a default data type choice due to these potential drawbacks .

Implicit declaration in Visual Basic allows variables to be used without prior declaration, which can lead to subtle errors if a variable name is mistyped, as VB creates a new variable for the mistyped name without any warning . For instance, if 'intcount' is incorrectly typed as 'intcont', VB treats 'intcont' as a new variable initialized to zero, leading to incorrect calculations . The Option Explicit statement prevents such errors by forcing the programmer to explicitly declare all variables, which allows VB to catch undeclared variables and alert the user to potential mistyped names or missing declarations. This helps in maintaining code accuracy and reduces logical errors in the application .

Constants in Visual Basic are different from variables in that they are immutable; once set, their values cannot change throughout the application's runtime, ensuring consistency . Constants are declared using the 'Const' keyword, and their values are specified at compile-time, contributing to efficient memory usage and preventing accidental changes . A common use-case for constants is defining fixed configuration values or environmental parameters, like tax rates or application-specific paths, which should remain unchanged to ensure system integrity and predictable behavior . In contrast, variables can be assigned new values, allowing flexibility but requiring careful management to avoid unintended side effects.

Static variables in Visual Basic are crucial because they retain their values even after the procedure that declares them has finished executing . While regular local variables are re-initialized every time a procedure is invoked and lose their values once the procedure ends, static variables maintain their state across multiple invocations of the procedure . This feature is useful for applications where the procedure needs to remember the state or need to track information such as the number of times a button is clicked, thereby allowing for persistent state within a static context across calls .

In Visual Basic, the string data type is used for text and can have a fixed length of up to 65,400 characters or a variable length of up to 2 billion characters, requiring storage equal to the length of the string plus 10 bytes for variable-length strings . On the other hand, the currency data type, designed for monetary calculations to avoid rounding errors, is an 8-byte data type that provides high precision within a range suitable for financial calculations [-922,337,203,685,477.5808 to 922,337,203,685,477.5807]. While strings are for textual data, currency is specifically tailored for handling financial data with precision .

Literals in Visual Basic represent fixed values that are directly assigned to variables without computation and are crucial for defining constants such as numeric values, strings, and date/time . Suffixes play a significant role by explicitly defining the intended data type of a numeric literal, thereby enhancing precision and accuracy in calculations. For instance, appending '&' for Long, '!' for Single, and '#' for Double ensures that the variable's type aligns with the precision required by the computation, which can prevent unexpected results due to type coercion . Effective use of literals with suffixes ensures data integrity and performance optimization, as the Visual Basic compiler can handle arithmetic operations accurately when it knows the specific type of the value being worked with. This is particularly important in financial applications where precision is crucial and numeric type mistakes could lead to significant computational errors .

You might also like