VB 6 Select-Case

In the previous article, you have learned about the if-then-else statements and how you can build a program in VB 6 that work on conditions. The problem with if-then-else structure is that it is very difficult to keep a track of all codes.

The Select-Case is a VB 6 feature that allows to select a case when the condition is met and execute a code. It is a more simplified version of if-then-else statements.

Syntax: Select-Case

The syntax for Select-Case is given below.

Select Case expression
   Case 1:
       some expression;
   Case 2:
       some expression;
   Case 3: 
       some expression;
   Case 4 To 8: 
       some expression;
   Case Is <= Total:
       some expression;
   Case Else:
       some default expression;
End Select

Select Case ‘expression‘ – Here the Select Case wants a variable or an expression to check if any Case match with it. If there is a match then execute codes under that case.

Case ‘value’ – A case has a number or expression that evaluates to a number. The code under case is executed when the Select Case condition is met.and its value match with the Case value.

End Select – This terminates the Select Case block.

The Case

Each of the case has a value associated with it. It may be in the form of number, or an expression.Let us see few examples below:

Case with number

Case 4: //Case with number and a colon

Case with range of values (expression)

Case 4 To 10: // Gives option to choose number between 4 and 10

Case with logic (expression)

Case Is >= 20: //Case condition evaluates to true, and code gets executed

When the case does not match, the last case is Case Else which executes the default statement.

Example Program: Calculator

Private Sub Command1_Click()
Dim physics_mark As Integer, maths_mark As Integer
Dim english_mark As Integer, average As Integer
Dim result As String

physics_mark = Val(Text3.Text)
maths_mark = Val(Text2.Text)
english_mark = Val(Text1.Text)
average = (physics_mark + maths_mark + english_mark) / 3

Select Case average
  Case Is <= 50:
        Text4.Text = "You Passed"
 
  Case Is <= 70:
        Text4.Text = "Good Marks"
    
  Case Is <= 90:
        Text4.Text = "Top Student"
    
  Case Is < 100:
        Text4.Text = "Exceptional"
    
  Case Else
        Text4.Text = "Sorry! You Failed"
    
End Select
End Sub

In the above program, students enter marks for 3 subjects – English, Mathematics, and Physics. The average of the marks is computed and using Select-Case the appropriate result is displayed.

Output – Select-Case

Output - Select-Case Program
Figure 1 – Output – Select-Case Program
post

VB 6 – If…Then…Else Statements

The conditional statements are very important to any programming language. In VB 6, the conditional statement change the direction of the program using If...Then ...Else construct.

The syntax for If...Then...Else is given below.

If condition Then
[Statements]
Else If condition 1 Then
...
[statements]
...
Else If condition n Then
...
[Statements]
...
Else
...
[Statements]
...
End If

If you look at the above syntax , the conditions are very important for If statements. If the condition 1 is false then another condition is checked and so on. The condition is met (True), then that statement block is executed. If no condition is met, then the last Else statement is executed.

Example Program: If…Then…Else

Consider the following example code, the program has a variable called day. If the day is 1, it is Monday, else it is Tuesday, and so on.

Private Sub Text1_Change()
Dim day As Integer
day = Val(Text1.Text)

If day = 1 Then
Text2.Text = "Monday"

ElseIf day = 2 Then
Text2.Text = "Tuesday"

ElseIf day = 3 Then
Text2.Text = "Wednesday"

ElseIf day = 4 Then
Text2.Text = "Thrusday"

ElseIf day = 5 Then
Text2.Text = "Friday"

ElseIf day = 6 Then
Text2.Text = "Saturday"

ElseIf day = 7 Then
Text2.Text = "Sunday"

Else
Text2.Text = "Enter Number Less Than Equal To 7"

End If
End Sub

If the number for variable day is greater than 7 , then default message is displayed – "Enter number less than equal to 7".

Output – If…Then…Else

The output of the above program is given below.

Output - If-Then-Else
Figure 1 – Output – If-Then-Else
post

VB 6 – UCase() and LCase()

In Visual Basic 6, there are two important functions to change a string to uppercase or lowercase. In this example, you will build a small application that takes a string and returns uppercase or lowercase version depending on user choice.

Program Code: UCase () and LCase()

First look at the code for first button – UpperCase.

Private Sub Command1_Click()
Text2.Text = UCase(Text1.Text)
End Sub

Now code for button – LowerCase.

Private Sub Command2_Click()
Text2.Text = LCase(Text1.Text)
End Sub

Output – UCase () and LCase()

Output - String Handling - LowerCase and UpperCase
Output – String Handling – Lowercase and Uppercase
post

VB 6 String Handling

Earlier you learned about the string data type. The VB 6 language has many functions to handle string types. In this article, we will present the list of those functions with examples.

There are two types of strings in VB 6 programming.

  • Variable length strings
  • Fixed length strings

To declare variable length string you can use following syntax.

'variable length string declaration
Dim myStr as String  
'fixed length string declaration
Dim myFixedStr as String * 20

You can notice that we are using asterisk (*) to specify the length of the string which is 20 characters.

String Handling Functions in VB 6

String FunctionsDescription
StrComp()Compares two strings
StrConv()Convert strings
Format(), LCase, UCaseConvert A string to lowercase
or uppercase
Space(), String()Create strings
Len()Get the length of the string
FormatFormat a string
LSet, RSetJustify a string
InStr, Left, Mid, Right, Trim,
LTrim, RTrim
Manipulate strings
Option Comparestring comparison values
Asc, ChrUse ASC II and ANSI values
String Handling Functions
post

VB 6 Declaring A Subroutine

A subroutine is a block of code like function that do a specific task. The difference between subroutine and function is that a subroutine does not return a value. However, you may pass arguments to a subroutine in VB 6.

The syntax for subroutine is given below, the keywords within square bracket ([]) are optional.

[Private | Public | Friend] [Static] Sub-name [(argument list)]
...
[Statements]
...
[Exist Sub]
...
[Statements]
...
End Sub

Public keyword allows procedures from all forms and modules to access the public procedures.

Private keyword only allows access to procedures from forms and modules where private procedure is declared.

Friend keyword used in class modules (modules that implement classes) allows the procedure to be visible throughout the project except to the controller of the instance of an object.

Static keyword preserve the value of local variable (those declared inside the procedure) between calls. You can call a procedure several times, it would not lose the value of a static local variable.

Argument list is a list of variables that it passed to the procedure. You can have multiple arguments each separated by a comma.

Argument List: Sub Procedure

Argument list has following syntax:

[Optional] [ByVal | ByRef] [ParamArray] varname [()] [As type] = [default value]

Optional means that the argument is not required.

ByVal means the argument is passed to the procedure by value. ByRef means that the argument is passed as a reference rather than the value.

ParamArray is the last argument in the argument list and it indicates that the final argument is an array of Variant elements.

Varname is the name of the argument being passed to the procedure.

type is the data type of the argument.

defualt value is a constant or a constant expression set when you use the [Optional] keyword.

Exit Sub cause the sub procedure to immediately exit itself.

End sub is to end the sub procedure.

Example: Sub Procedure

Here is an example of sub procedure.

Sub Matrix (Optional MatValues as Variant)
     If IsMissing (MatValues)  Then
    
    ' If value is not passed
     MsgBox("Value not passed to the Matrix")
    Else
    ...
   End If
End Sub

In the next article, we will learn about VB 6 function which is similar to sub procedure.

post

VB 6 Arrays

The VB 6 arrays hold data of a single type. In this article, you will learn about declaring, assigning, and various array handling techniques.

Types of  VB 6 Array

You can divide VB 6 arrays into two sets – One-dimensional array and multi-dimensional arrays The VB \hspace{3px}6 can have a maximum of 60 dimensions. The arrays in VB \hspace{3px}6 are also classified based on keywords used to declare them:

  1. Regular \hspace{3px} arrays – It is declared using keyword Dim whole values remain variable.
  2. Dynamic \hspace{3px}arrays – A standard array can be expanded for more space; hence, it is called dynamic array. You can use keyword – ReDim to redeclare the array.
  3. Static \hspace{3 px} arrays– A static variable does change its value after exiting a procedure in which they were declared. static arrays do the same and retain their value between procedure calls.
  4. Private\hspace{3px} arrays – The scope is limited to the procedure in which it is defined. Use the keyword – Private to define the procedure.
  5. Public\hspace{3px} arrays – The scope is an entire program or module. Use the keyword Public in the module.
  6. Type \hspace{3px} arrays – This is for user-defined array types

Regular Arrays

The regular arrays are the usual way of declaring an array using the Dim statement. The syntax to declare a regular array is given below:

Dim [WithEvents]  variable_name [(Subscripts)] [As [New] type] [, [WithEvents] variable2_name [(Subscripts)] [As [New] type] ...
  • WithEvents – This is an optional parameter, and it is required when the variable is an object-variable type. An object-variable is used in modules with class or class modules.
  • Variable{\_}name – It is the user-defined name of the variable.
  • Subscripts – They are optional parameters. An integer value subscript value indicates the number of members in an array. There are two ways to declare subscript:
[lower To] upper

Example:

TotalAmount( 10 To 20)
  •  New – This is an optional parameter and required only when the variable is object-variable type.
  • type – Defines the variable type which can be one of the following: Byte, Boolean, Currency, Long, Double, Single, String and Date.

Example:

Regular Array Declarations
Figure 1 – Regular Array Declarations

Assigning Values to Regular Array Elements

To assign values to array elements refer to them using an index and then assign value like any normal variable.

For Example:

Private Sub BtnTax_Click()

   Dim salary(10) As Double
   Dim Location(10) As String
   Location(9) = "Nottingham"
   Location(7) = "France"

   Print Location(9)
   Print Location(7)
   
   salary(2) = 2003

End Sub

In the next section, we will discuss declaring dynamic arrays and assigning values to them.

Dynamic Arrays

A dynamic array does not have a fixed size, it is expanded dynamically. The Dim statement is used to declare an array without any subscript value (between the parentheses) .

For example,

Dim Accounts ( )  As Integer
Dim Employee( ) As String

The next step after declaring the array is to set the length of the array. Since this is a dynamic array we could increase the size multiple times.

The syntax:

ReDim [Preserve]  variable_name (subscript) [As type]
  • ReDim – To declare the size of the dynamic array.
  • Preserve – This keyword is to preserve the data while expanding the size of the existing array.
  • Variable\_name – User-defined name of the array.
  • Subscript – The value of subscript can be an integer or [lower To] upper.
  • type – This defines the data type of the array. It could be Byte, Boolean, Long, Single, Double, Currency, Date, Integer, and String.

Example:

Dynamic Array - ReDim Statement
Dynamic Array – ReDim Statement

Array ( ) Function in VB 6

The Array ( ) function is a special function in Vb 6 that takes array values and directly assign it to a variant type variable. The variant type variable becomes an array of the type supplied in the argument list.

Syntax:

Array(argument list)

Example:

Dim Tot As Variant
Tot = Array(23, 44, 56)

' Output the last element of the array, the size of the array is set automatically

Print Tot(2)

Summary of  Statements and Functions

Here is a list of array handling statements and functions provided by VB 6.

Statements or FunctionsDescription
Dim, Public, Static, ReDim, PrivateDeclare or Initialize an array
Erase, ReDimReinitialize an array
ArrayCreate an Array
IsArrayVerify an array
LBound, UBoundFind the upper or lower limit of an array
Option BaseChange default lower limit 0 to a non-negative integer value
post

VB 6 Variable Scope

The scope of a VB 6 variable decides the lifetime of that variable. There are 3 levels of scope for a variable in Visual Basic 6. In this article, you will learn about the scope of variables with examples in a Visual Basic 6 project.

Level of Scope

The scope in many programming languages is either a global scope or a local scope. We will list out the global scope and local scope for a variable in visual basic 6.

Visual Basic 6 has 3 levels of scope:

  1. Module Level with Public (Global)
  2. Form or Module level (Global only to the Module).
  3. Procedure Level (Local scope)

Module Level With Public

Variables declared in the general section of the code editor using keyword Public are visible in all forms and modules throughout the VB 6 Project.

Example:

In this example, we declared two variable – test and number – as integers in the (General) section of Module 1. These integers will be available throughout the project and you can manipulate as and when necessary.

Global Declaration using Public
Figure 1 – Global Declaration using Public

Form Or Module Level

In this level, the variable is declared under (General) section of Visual Basic code editor. The keywords – Dim, ReDim, Static and Private are used to declare the variables.

Example:

In the example below, the form name is  “Accounting” and we have declared two variable using Dim statement. The scope of these variables is limited to the form only.

Form Level Global Declarations
Figure 2 – Form Level Global Declarations using Dim Statement.

Procedure-Level

Each procedure in VB 6 has its own variables. Those variables are local to the procedure, and cannot be used elsewhere. The keyword – Public cannot be used for procedures.

Example:

Local Variable Declaration
Figure 3 – Local Variable Declaration

In the example above, the variable Number is local to the procedure Form_Load( ). This is because Form_Load ( )  procedure is by default a Private procedure. This form assigns a value of 1003 to variable Number when the form loads.

post

VB 6 Type Casting

Type casting in VB 6 means converting from one data type to another. The VB 6 language allows type conversion using functions.

Here is a list of functions with their description.

FunctionDescription
ChrANSI to string
Format, LCase, UCaseString to Lowercase or Uppercase
DateSerial, DateValueDate to Serial Number
Hex, OctDecimal to Hexadecimal or Oct
Format, StrNumber to Str
CBool, CInt, CByte, CLng,CCur, CDate, CDec, CSng, CVar, CStr,CVErr,CDbl, Fix, IntConvert from a data type to another
Day, Month, Weekday, YearDate to Day, Month, Weekday, or Year
Hour, Minute, SecondTime to Hour, Minute, or Second
AscString to ASCII value
TimeSerial, TimeValueTime to Serial number
ValString to number
post

VB 6 Variable Declarations

If you have added the forms and controls to the project, the visual basic language will make them work.  The visual basic 6 language is the code or instructions once an event like click happens.

In VB 6 language, you must learn the following things.

  1. Declare variables, constants, functions and subroutines.
  2. Use strings, operators, conditions, loops and handle math.
  3. Understand how VB 6 format financial data and dates.

In this article, you will learn to declare variables and constants. We will learn rest of topics in future articles.

Variable Declaration in VB6

The coding part in VB6 starts with a variable declaration. A variable in vb6 is a name that hold a value. Visual basic 6 is a typed language, similar to C/C++, Java that supports all kinds of data types.

Syntax:

Dim [WithEvents] variable name [([subscripts])] [As [New] type]

The keywords inside square bracket are optional. Let us discuss each of these keywords briefly.

WithEvents – tells that varname is object variable that respond to events by an active x object. varname is name of the variable.

Subscripts – use only when you are creating an array of variables or object variables.

New – use new keyword when you create new object. A new instance of the declared variable is created.

type – the type refers to data type of the variable, it is not a keyword. VB6 supports following data types.

Boolean
Byte
Integer
Long
Currency
Single
Double
Date
String (variable length)
String * [length]
Object
Variant

The default type is variant which takes value of any data type.

For example,

Dim Car As String
Dim Price As Integer

Multiple Variable Declaration

You can declare more than one variables at a time using the Dim statement.

Syntax:

Dim [WithEvents] variable1 name [([subscripts])] [As [New] type], [WithEvents] variable2 name [([subscripts])] [As [New] type], ...

Example #1

To understand the relationship between variables and controls consider the following example.

Step 1: Create a form and a button control similar to the figure below.

Figure 1 - Create Form and a Command button
Figure 1 – Create Form and a Command button

Step 2: Right click on the command button and select view code which will open visual basic code editor for that button control. Add the codes as given in the figure below.

Figure 2 - Code for Command button
Figure 2 – Code for Command button

Note that the red circle marks the control name and green circle indicates the event that triggers this code in the figure above.

The result of the code is given below when the command button is clicked.

Figure 3 - Result when button is clicked
Figure 3 – Result when button is clicked

Option Explicit

Sometimes we misspelled or use a variable without declaring it. Without declaration its type is variant, but misspenlt variable can cause problems.

In general section of code window at form or module level use Option Explicit statement forcing variable declaration.

Constant Declaration

Constants are values that we wish to keep fixed throughout the program. They are hard to track in a program, therefore VB6 allows you to declare all constants with a name and an optional type. The Const keyword is used to declare constants.

Syntax:

[Public | Private] Const constant_name [As type] = expression

Example #2

Private Sub Command1_Click()

Const side = 2.5
Dim Area
Area = side * side
MsgBox ("Area = " + Str(Area))

End Sub

When the button is clicked it will output area, but the constant value side will not be altered.

post

VB 6 Managing Projects

Visual basic open a project in design view where you can modify project properties like project name and description, version information, and other similar attributes. Managing VB 6 projects is easier than you may think.

The project tab in the visual basic standard toolbar contains project properties which allow us to change settings related to a visual basic project.

You can also add predefined forms, menus, and modules to your project using the visual component manager. A menu in the visual component manager can be reused in many different forms. Not an only menu, but you can add other types of components like class, modules, media forms, reports, documents, etc.

Naming a Visual Basic 6 Project

To name a visual basic project you must:

  • Specify a project name when you save the project file. Every project creates a .vbp file and requires user-specified name before you save it to a disk.
  • Specify a project name from project properties under the project tab.

Example:

We want to set the project name as MyFirstVBProgram. To set this name, go to project tab > select project properties > under general tab > project name, type the name for your project and a description under project description section.

Project Properties - Naming a Project
Project Properties – Naming a Project

Project Version Version Information

Larger vb projects need to keep version numbers and version information such as company name, software product name, license information, copyright information, legal trademarks, comments, etc.

You can set this information from project properties > make tab. The two options related to the project are:

  • Version number
  • Version description.

You can enter the project version number and other required details under version description. The project icon is the icon set for the startup form. Jump to next section for information on startup form.

Project version and version information
Project version and version information

After you convert your project into an EXE file (File menu > make MyFirstVBProgram.exe), right-click the file and go to properties > details tab. You can see the version information related to the project.

Version Information
Version Information

Startup Form for the Project

The startup form is the first form loaded in when the visual basic starts. You can decide the form or the object to load at startup in visual basic.

To set this value, go to project properties, under general tab> select the startup object from the drop-down and click ok.

Startup Object
Startup Object

In the figure above, the startup object is Form1 and loaded first.

Adding Predefined Components to a Project Form

Managing visual basic 6 projects needs two types of components frequently.

  • Predefined Components such as menu, modules, etc
  • ActiveX and Insertable objects such as MS Excel, MS Word, etc.

The predefined menu is added using visual basic component manager. If you have not installed the component manager, use the add-in tab to load it.

Add-In Manager
Add-In Manager

Under add-ins > click add-in manager and select the visual component manager 6.0 to install. If already installed, go to standard toolbar.

You can add the components by clicking on the visual component manager from the standard toolbar icon. This will open the window for the visual component manager.

Icon for Visual Component Manager
Icon for Visual Component Manager

Predefined Menu for Form

When the window for component manager is open, click Visual basic folder > open Templates folder and select the folder for predefined component you want to add to vb project.

For example, you want to add a File menu to the project form. Then select Menu folder under Templates in the visual component manager.

Visual Component Manager
Visual Component Manager

If nothing is found, create a new component by clicking on the “publish a new component” option on the top and finished the new component wizard.

Now you can select a new reusable component for your project.

Menu Component
Menu Component

Add ActiveX Controls

There are special controls called ActiveX that require that visual basic loads the necessary files. For example, you can connect SQL database to vb form using data grid control.

To enable the activex controls, go to project > components and select the components you want to install.

ActiveX Components
ActiveX Components

The tab insertable objects, let VB programmers insert MS Excel, MS Word, and other similar objects.

post