Rules for variables:

These are the rules to follow when naming elements in VB - variables, constants, controls, procedures, and so on:

  • A name must begin with a letter.
  • May be as much as 255 characters long (but don't forget that somedy has to type the stuff!).
  • Must not contain a space or an embedded period or type-declaration characters used to specify a data type ; these are ! # % $ & @
  • Must not be a reserved word (that is part of the code, like Option, for example).
  • The dash, although legal, should be avoided because it may be confused with the minus sign. Instead of Family-name use Family_name or FamilyName.

Data types

Data type / Storage size / Range
Byte / 1 byte / 0 to 255
Boolean / 2 bytes / True or False
Integer / 2 bytes / -32,768 to 32,767
Long (long integer) / 4 bytes / -2,147,483,648 to 2,147,483,647
Single (single-precision floating-point) / 4 bytes / -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values
Double (double-precision floating-point) / 8 bytes / -1.79769313486232E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values
Currency (scaled integer) / 8 bytes / -922,337,203,685,477.5808 to 922,337,203,685,477.5807
Decimal / 14 bytes / +/-79,228,162,514,264,337,593,543,950,335 with no decimal point; +/-7.9228162514264337593543950335 with 28 places to the right of the decimal; smallest non-zero number is +/-0.0000000000000000000000000001
Date / 8 bytes / January 1, 100 to December 31, 9999
Object / 4 bytes / Any Object reference
String (variable-length) / 10 bytes + string length / 0 to approximately 2 billion
String (fixed-length) / Length of string / 1 to approximately 65,400
Variant (with numbers) / 16 bytes / Any numeric value up to the range of a Double
Variant (with characters) / 22 bytes + string length / Same range as for variable-length String
User-defined (using Type) / Number required by elements / The range of each element is the same as the range of its data type.

In all probability, in 90% of your applications you will use at most six types: String, Integer, Long, Single, Boolean and Date. The Variant type is often used automatically when type is not important. A Variant-type field can contain text or numbers, depending on the data that is actually entered. It is flexible but it is not very efficient in terms of storage.

Declaring variables

Declaring a variable means giving it a name, a data type and sometimes an initial value. The declaration can beexplicitorimplicit.
Anexplicit declaration:variable is declared in the Declarations Section or at the beginning of a Procedure. An explicit declaration looks like:

Dim MyNumber As Integer

Now the variableMyNumberexists and a 2-byte space has been reserved for it.
Animplicit declaration:the variable is declared "on the fly", its data type is deduced from other variables. For example:

Dim Total1 As Integer'Explicit declaration
Dim Total2 As Integer'Explicit declaration
Total3 = Total1 + Total2 'Implicit declaration

Total3 is not formally declared but is implied, it is "arrived at" from the other declarations.
It is never a good idea to have implicit declarations. It goes against the rules for clarity, readability and ease of use of the code.
To make sure that this rule is followed, start the Declarations with theOption Explicitclause. This tells the compiler to consider implicit declarations as errors and forces the programmer to declare everything explicitly.
Other examples of declarations:

Dim MyName As String
Dim StudentDOB As Date
Dim Amount5, Amount6, Amount7

In the last example the type assigned to each variable will be: Variant. It is the default type when none is specified.
There can be multiple explicit declarations in a statement:

Dim EmpName As String, SalaryMonth As Currency, SalaryYear As Currency

In this final example, what are the types assigned to the three variables:

Dim Amount1, Amount2, Amount3 As Single

All Single-precision floating point, you say.Wrong!Only Amount3 is Single. Amount1 and Amount2 are considered Variant because VB specifies that each variable in a statement must be explicitly declared. Thus Amount1 and Amount2 take the default data type.

Constants

Constants are different from variables in the sense that their values do not change during the running of the program.

Declaring a Constant

The format to declare a constant is

ConstConstant NameAsData Type = Value

Example 5.3

Const Pi As Single=3.142

Const Temp As Single=37

Const Score As Single=100

The Scope of variables

The termScoperefers to whether the variable is available outside the procedure in which it appears. The scope isprocedure-levelormodule-level.
A variable declared with Dim at the beginning of a procedure is only available in that procedure. When the procedure ends, the variable disappears. Consider the following example:
Option Explicit
Dim Total2 As Integer
Private Sub Command1_Click ()
Dim Total1 As Integer
Static Total3 As Integer
Total1 = Total1 + 1
Total2 = Total2 + 1
Total3 = Total3 + 1
End Sub
Private Sub Command2_Click ()
Dim Total1 As Integer
Total1 = Total1 + 1
Total2 = Total2 + 1
Total3 = Total3 + 1
End Sub
Every time Button1 is clicked, Total1 is declared as a new variable during the execution of that clicked event. It is aprocedure-levelvariable. It will always stay at 1. The same for the Button2 event: Total1 is a new variable in that procedure. When the procedure ends, Total1 disappears.
Total2 is declared in the Declarations section (outside both command functions). It is amodule-levelvariable, meaning it is available to every control(function) in this Form. When Button1 is clicked, it increments by 1 and it retains that value. When Button2 is clicked, Total2 is incremented from its previous value, even if it came from the Button1 event.
Total3 shows another way of retaining the value of a local variable. By declaring it withStaticinstead of Dim, the variable acts like a module-level variable, although it is declared in a procedure.
Another scope indicator that you will see when you study examples of code isPrivateandPublic. This determines whether a procedure is available only in this Form (module) or if it is available to any module in the application. For now, we will work only with Private procedures.

Operators

Mathematical and Text operators
Operator / Definition / Example / Result
^ / Exponent (power of) / 4 ^ 2 / 16
* / Multiply / 5 * 4 / 20
/ / Divide / 20 / 4 / 5
+ / Add / 3 + 4 / 7
- / Subtract / 7 - 3 / 4
Mod / Remainder of division / 20 Mod 6 / 2
\ / Integer division / 20 \ 6 / 3
String concatenation / "Joan" & " " & "Smith" / "Joan Smith"

Note that the order of operators is determined by the usual rules in programming. When a statement includes multiple operations the order of operations is:
Parentheses ( ), ^, *, /, \, Mod, +, -

Logical operators
Operator / Definition / Example / Result
= / Equal to / 9 = 11 / False
Greater than / 11 > 9 / True
Less than / 11 < 9 / False
>= / Greater or equal / 15 >= 15 / True
<= / Less or equal / 9 <= 15 / True
Not equal / 9 > 9 / False
AND / Logical AND / (9 = 9) AND (7 = 6) / False
OR / Logical OR / (9 = 9) OR (7 = 6) / True

CONTROL STRUCTURES:

Control Statements are used to control the flow of program's execution.There are 3 types of control structure in all programming languages:

1) sequential control structure

2) Selective control structure –> If… then.. else, select case

3) Repetitive(Iteration) control structure.--> while, do…. loop while, for …next

If...Then...Else

Ifcondition1Then
statements1
Else
statements2
End If
If condition1 is True, then statements1 block is executed; Else, condition1 is not True, therefore statements2 block gets executed. The structure must be terminated with the End If statement.
The Else clause is optional. In a simple comparison, statements1 get executed or not.
Ifcondition1Then
statements1
End If 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 theIf...Thenselection

If <condition> Then
statement
End If

e.g.: If average>75 Then
txtGrade.Text = "A"
End If

If...Then...Else selection structure

TheIf...Then...Elseselection structure allows the programmer to specify that a different action is to be performed when the condition is True than when the condition is False.

Syntax of theIf...Then...Elseselection

If <condition > Then
statements
Else
statements
End If

e.g.: If average>50 Then
txtGrade.Text = "Pass"
Else
txtGrade.Text = "Fail"
End If

Nested If...Then...Else selection structure

NestedIf...Then...Elseselection structures test for multiple cases by placingIf...Then...Elseselection structures insideIf...Then...Elsestructures.

You can use Nested If either of the methods as shown below

Method 1

If < condition 1 > Then
statements
ElseIf < condition 2 > Then
statements
ElseIf < condition 3 > Then
statements
Else
Statements
End If

Method 2

If < condition 1 > Then
statements
Else
If < condition 2 > Then
statements
Else
If < condition 3 > Then
statements
Else
Statements
End If
End If
EndIf

e.g.: Assume you have to find the grade using nested if and display in a text box

If average > 75 Then
txtGrade.Text = "A"
ElseIf average > 65 Then
txtGrade.Text = "B"
ElseIf average > 55 Then
txtGrade.text = "C"
ElseIf average > 45 Then
txtGrade.Text = "S"
Else
txtGrade.Text = "F"
End If

Select...Case selection structure

Select...Casestructure is an alternative toIf...Then...ElseIffor selectively executing a single block of statements from among multiple block of statements.Select...caseis more convenient to use than theIf...Else...End If.The following program block illustrate the working ofSelect...Case.

Syntax of theSelect...Caseselection structure

Select Case Index
Case 0
Statements
Case 1
Statements
End 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.Text
Select Case average
Case 100 To 75
txtGrade.Text ="A"
Case 74 To 65
txtGrade.Text ="B"
Case 64 To 55
txtGrade.Text ="C"
Case 54 To 45
txtGrade.Text ="S"
Case 44 To 0
txtGrade.Text ="F"
Case Else
MsgBox "Invalid average marks"
End Select

Sample example: to select size for your shirt.

SelectCaseShirtSize
Case1
SizeName.Caption="Small"
Case2
SizeName.Caption="Medium"
Case3
SizeName.Caption="Large"
Case4
SizeName.Caption="ExtraLarge"
CaseElse
SizeName.Caption="Unknownsize"
End Select

While...End While

Runs a series of statements as long as a given condition isTrue. Here statements are executed only if the condition is true. Otherwise the statements are not executed.

While condition

[statements]

[Exit While]

[statements]

End While

Use aWhile...End Whilestructure when you want to repeat a set of statements an indefinite number of times, as long as a condition remainsTrue.

IfconditionisTrue, all of thestatementsrun until theEnd Whilestatement is encountered. Control then returns to theWhilestatement andconditionis again checked. Ifconditionis stillTrue, the process is repeated. If it isFalse, control passes to the statement following theEnd Whilestatement

This example uses theWhile...End Whilestructure to increment a counter variable. The statements in the loop run as long as the condition evaluates toTrue.

Here the statements are executed only if the given condition is true.

Example:

Dim counter AsInteger = 0

While counter < 20

counter += 1

' Insert code to use current value of counter.

EndWhile

MsgBox("While loop ran "CStr(counter) & " times"

Do...loop While

Repeats a block of statements while aBooleancondition isTrueor until the condition becomesTrue

Here the statements are executed atleast once before checking the while condition.

This the syntax of do…loop while

Do
Block of one or more VB statements
Loop While condition

The above example can be rewritten as

Do

TextBox1.Text=counter
counter+=1

Loop while counter>20

For...Next

When the number of iterations of the loop is known, it is better to use the For...Next rather than the Do...Loop.
Forcounter = startToend
statements
Next
1) The counter is set to the value of start.
2) Counter is checked to see if it is greater than end; if yes, control passes to the statement after the Next; if not the statements are executed.
3)At Next, counter is incremented and goes back to step 2).

TheFor...NextLoop is another way to make loops in Visual Basic.For...Nextrepetition 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 to 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

Example for FOR

*The program will enter number 1 to 10 into the list box.

Dim counter as Integer

For counter=1 to 10

ListBox1.Items.Add (counter)

Next

Example 11.1b

* The program will calculate the sum of the numbers as follows:

sum=0+10+20+30+40+......

Dim counter , sum As Integer

For counter=1 to 100 step 10

sum+=counter

ListBox1.Items.Add (sum)

Next

MsgBox ( ) Function

The objective of MsgBox is to produce a pop-up message box and prompt the user to click on a command button before he /she can continues. This format is as follows:

yourMsg=MsgBox(Prompt, Style Value, Title)

The first argument, Prompt, will display the message in the message box. The Style Value will determine what type of command buttons appear on the message box, please refer Table 10.1 for types of command button displayed. The Title argument will display the title of the message board.

Table 10.1: Style Values
Style Value / Named Constant / Buttons Displayed
0 / vbOkOnly / Ok button
1 / vbOkCancel / Ok and Cancel buttons
2 / vbAbortRetryIgnore / Abort, Retry and Ignore buttons.
3 / vbYesNoCancel / Yes, No and Cancel buttons
4 / vbYesNo / Yes and No buttons
5 / vbRetryCancel / Retry and Cancel buttons

We can use named constant in place of integers for the second argument to make the programs more readable. In fact, VB6 will automatically shows up a list of names constant where you can select one of them.

Example: yourMsg=MsgBox( "Click OK to Proceed", 1, "Startup Menu")

and yourMsg=Msg("Click OK to Proceed". vbOkCancel,"Startup Menu")

are the same.

The InputBox( ) Function

An InputBox( ) function will display a message box where the user can enter a value or a message in the form of text in a textbox. The format is

myMessage=InputBox(Prompt, Title, default_text, x-position, y-position)

myMessage is a variant data type(variable) declared as string, which accept the message input by the users. The arguments are explained as follows:

  • Prompt - The message displayed normally as a question asked.
  • Title - The title of the Input Box.
  • default-text - The default text that appears in the input field where users can use it as his intended input or he may change to the message he wish to key in.
  • x-position and y-position - the position or the coordinate of the input box.

Example 10.3

i.Design Interface

Figure 10.4

The procedure for the OK button is here:

Private Sub OK_Click()

Dim userMsg As String
userMsg = InputBox("What is your message?", "Message Entry Form", "Enter your messge here", 500, 700)
If userMsg > "" Then
message.Caption = userMsg
Else
message.Caption = "No Message"
End If

End Sub

Here message.caption is a label name in form1.

When a user click the OK button, the input box as shown in Figure 10.5 will appear. After user entering the message and click OK, the message will be displayed on the (label)caption of form1, if he click Cancel, "No message" will be displayed.

String functions

Here is a list of the basic functions that work with strings:

  • Len(string): returns the length ofstring, the number of characters it contains.
  • Left(string, number): returns the number of characters specified bynumberfrom the left end ofstring.
  • Right(string, number): returns the number of characters specified bynumberfrom the right end ofstring.
  • Mid(string, position, number): returns the number of characters specified bynumberstarting at character numberpositionfrom the left end ofstring.
  • InStr(string1, string2): returns the position ofstring2instring1- returns 0 ifstring2is not found instring1.
  • LTrim(string), RTrim(string) and Trim(string): returnsstringwith non-significant spaces removed from the left, the right or both, respectively.
  • LCase(string), UCase(string): returnsstringconverted to lower-case or upper-case, respectively.

Date and time functions:

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 all business 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:59 hours inclusive.

The system's current date and time can be retrieved using the Now, Date and Time functions in Visual Basic. The Now function retrieves the date and time, while Date function retrieves only date and Time function retrieves only the time.

To display both the date and time together a message box is displayed use the statement given below.

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)
Interface style

One of the first decisions you have to make is whether to goSDI (Single Document Interface)orMDI (Multiple Document Interface).If you have worked with Windows for any length of time, you have probably seen both. Notepad is an SDI - you can only have one document open at any time. Word is an MDI - you can open a number of documents and switch between them at will. An MDI application imposes different constraints on the developer because of the need to juggle several different forms at the same time. It usually requires more experience in the development process. For the purposes of this tutorial, we will work only with SDI applications.

Creating Your Own Function

The general format of a function is as follows:

Public FunctionfunctionName(Arg As dataType,...... ) As dataType

or

Private FunctionfunctionName(Arg As dataType,...... ) As dataType

* Public indicates that the function is applicable to the whole project and
Private indicates that the function is only applicable to a certain module or procedure.

Example 14.2

The following program will automatically compute examination grades based on the marks that a student obtained. The code is shown on the right.

The Code

Public Function grade(mark As Variant) As String

Select Case mark
Case Is >= 80
grade = "A"
Case Is >= 70
grade = "B"
Case Is >= 60
grade = "C"
Case Is >= 50
grade = "D"
Case Is >= 40
grade = "E"
Case Else
grade = "F"
End Select