This tutorial is divided into sections. If you want to jump to one of these sections, just click on the link below.
Overview
Declaration of variables
Selection Structure
Repetition Structure
String Manipulation
Sequential Files
Data Project
SQL Server Project
Overview of Visual Basic:
Visual Basic is an object-oriented/event-driven programming language. Unlike BASIC, it consists of objects like buttons, list boxes, text boxes etc. These objects in turn have properties and methods associated with them. The user interacts with these objects by events like clicking and the program responds with instructions written by the programmer. The code looks very much like the BASIC with a little new flavor. Lets study the following picture which resembles like a Visual Basic Form.
Here we have four objects:
1. LABEL:
The label is used by the programmer to tell the user what action to take. Here the user is being asked to enter his name. The contents of the label box can only be changed by the application developer. The properties of a label would be things like height, width, color, font, caption etc. The default name of the label is "Label1"
2. TEXTBOX:
The text box is where the end user is able to enter information required by the application. In this program the user can enter his/her name in the text box. Unlike the label, the contents of a text box can be changed by the user. The text box has similar properties as the label. If this was a real application you could enter your name in the text box. The default name of the textbox is "Text1"
3. PICTURE BOX:
The picture box is used to display images and also information about the execution of the program. In this program all we are going to is when the user enters their name and click PRINT, the name will be printed to the picture box. The default name of the picture box is "Picture1"
4. COMMAND BUTTONS:
Command buttons are most vital parts of any Visual Basic application. This is where the programmer would write the code for the application. In our sample program, all we want to do is read the information and print is to the picture box when the user clicks PRINT. If the user wants to end the application, they can just click the END button.
Code for "Command1" which says PRINT
Private Sub Command1_Click()
Picture1.Print Text1.Text
End Sub
Lets study the code in detail. The first letter for the sub (subroutine) is private. This tells VB that this sub is available to this form and application only. Command1 is the name of the command button followed by the Click method (command button). () means that we are not passing any arguments in this sub. The second line starts with picture1 which is the name of the picture box. It is followed by the print method (picture box) which means we will be printing to the picture box. Text1 is whatever the user enters in the text box followed by the text method (text box). The last line of the sub is end sub. This sub will take the name from the text box and print it to the picture box. Code for "Command2" which says END
Private Sub Command2_Click()
End
End Sub
This subroutine will end the application when the user clicks on it.
Declaration of variables and constants:
In Visual Basic, you use variables to temporarily store values during the execution of an application. Variables have a name (the word you use to refer to the value the variable contains) and a data type (which determines the kind of data the variable can store).
To declare a variable is to tell the program about it in advance. You declare a variable with the Dim statement, supplying a name for the variable. The syntax for declaring a variable is
Dim variable name [As type]
where
variable name: A combination of letters and numbers chosen by the programmer
type: One of the data types e.g. integer, string, data, variant (default) etc.
Examples:
Dim st_gender, st_dob As String
Dim x, y, z As Integer
Dim st_MD1, st_MDname As String
In order to assign a value to these variables, we use the following format
st_gender = "F"; st_MD1 = "M.D."; x = 1014
Sometimes in a program, a particular value is repeated in different places. In that case it is easy to declare it as
a constant instead of a variable. Here is the syntax
[Public|Private] Const constantname[As type] = expression
where
public/private is the scope of the constant.
constantname is the name used to define the constant
type is one of the data types
expression is the actual value of the constant
Examples:
public Const conMaxPlanets As Integer = 9
Const conReleaseDate = #1/1/95#
Selection Structure:
In any computer program, many decisions are made by the computer. A reliable selection structure is at the heart of any good program. Here we will discuss two types of selection structures; the if..then structure and the
select case structure. Lets us look at the first one
If..then structure:
This is the most common way to make decisions in a program. There are many different ways of using the if..then structure but the common syntax is as follows:
Syntax
If condition Then
[statements]
[Else
[elsestatements]]
End If
In order to understand the above syntax lets look at the following picture
During the execution of the program, the if..then causes the program to make a decision. If the first condition is true, the first set of statements will be executed. If the first condition is false, the program checks for the second condition. The next set of statements are executed if the second condition is true. The end if marks the end of this clause.
Examples:
If (Mid(st_linestring, 2, 1) = " ") And (Left(st_linestring, 1) = "F" Or Left(st_linestring, 1) = "M") Then
st_gender = Left(st_linestring, 1)
st_dob = Right(st_linestring, 10)
st_dob = Trim(st_dob)
Print #2, st_gender; "~";
Print #4, st_gender; "~";
pic_1.Print st_gender; "~";
Print #2, st_dob; "~";
Print #4, st_dob; "~";
pic_1.Print st_dob; "~";
Else
Print #2, "~";
Print #4, "~";
pic_1.Print "~";
Print #2, "~";
Print #4, "~";
pic_1.Print "~";
End If
If you don't know the string function, please visit this section for further information. This part of the program looks for the gender of a person. When it finds either "F" or "M", it prints the gender and date of birth to the
output file and also to the picture box. However if there is no information on the gender, it just prints tildas "~" to the file and the picture box.
Select Case structure:
When the selection structure has several paths to choose from, it is easier to use the Select Case structure. The syntax is like this
Syntax
Select Case testexpression
[Case expressionlist-n
[statements-n]] ...
[Case Else
[elsestatements]]
End Select
where
textexpression is any string or numeric expression
expressionlist-n is either an expression or comparative expressions
statements-n is the actual code that is executed if the textexpression matches the expressionlist-n
Examples:
This example uses a list box with months of the year. When the user clicks on a specific month, that specific month is assigned to string variable st_month. Notice how the first month has an index value of 0.
Select Case cbo_month.ListIndex
Case 0
st_month = "Jan"
Case 1
st_month = "Feb"
Case 2
st_month = "Mar"
Case 3
st_month = "Apr"
Case 4
st_month = "May"
Case 5
st_month = "Jun"
Case 6
st_month = "Jul"
Case 7
st_ month = "Aug"
Case 8
st_month = "Sep"
Case 9
st_month = "Oct"
Case 10
st_month = "Nov"
Case Else
st_month = "Dec"
End Select
Repetition Structure:
If a program is required to repeat any statement many times, it is convenient to use "loops". There are many
different kinds of loops, for..next, do..loop, while..wend etc. Lets take a closer look at each one of them.
FOR..NEXT:
The for next repeats a group of statements a specified number of times. The syntax is
Syntax
For counter = start To end [Step step]
[statements]
[Exit For]
[statements]
Next [counter]
where
counter: variable (usually integer ) used to control the flow of the loop.
start: initial value of the counter
end: final value of the counter
step: amount the counter changes by every time the loop is executed
exit for: optional statement to break out of the loop.
Examples:
If Len(st_mrn) <> 7 Then 'start of 6th if-then
For d = 1 To (7 - Len(st_mrn))
st_mrn = "0" + st_mrn
Next
Else
End If
We start with an if-then clause to check the length of the string "st_mrn". If the length of the string is less than
seven, the for next loop is used to add zeros to a string. Lets say the value of st_mrn is "1234" which means
Len(st_mrn) = 4. The expression (7-Len(st_mrn)) results in a value of 3. This means that the for next with
execute three times for d = 1, 2, 3. Every time it loops through, it will add a zero to the string.
DO..LOOP:
The do loop repeats a block of statements while a condition is True or until a condition becomes True.
Syntax
Do [{While | Until} condition]
[statements]
[Exit Do]
[statements]
Loop
Or, you can use this syntax:
Do
[statements]
[Exit Do]
[statements]
Loop [{While | Until} condition]
The difference is that the first one checks for the condition before executing any of the statements. The second
one loops through at least once and then checks for the condition. Its more of a personal choice to which one
should be used. Personally I like to use the second one. The Exit Do is again optional statement and breaks the
natural flow of the loop.
Examples:
Do While not EOF(1) AND Len(st_linestring) < 2
Line Input #1, st_linestring
st_linestring = Trim(st_linestring)
Picture2.Print st_linestring
print #2, st_linestring
Loop
In this example, the do-loop first checks for the end of file and then checks for the length of the string
"st_linestring". If the string is less than 2 characters long, then the following statements are executed. These
statements take the next string, trim it and then print it to the output file.
WHILE..WEND:
While-wend loop is exactly like the first do loop where the condition is checked in the beginning. It executes
a series of statements as long as a given condition is True.
Syntax
While condition
[statements]
Wend
Examples:
While counter < 20
counter=counter+1
Wend
The above loop increments the counter by 1 as long as it is below 20.
String Manipulation:
String is a fundamental data type that holds character information. A String variable can contain approximately 65,535 bytes (64K), is either fixed-length or variable-length, and contains one character per byte. Fixed-length
strings are declared to be a specific length. Variable-length strings can be any length up to 64K, less a small amount of storage overhead.
Visual Basic has many different functions for manipulation of strings. Lets look at some of these:
Len function:
Returns number of characters in a string or the number of bytes required to store a variable
The syntax is
Len(string | varname)
where
string is any valid string expression
varname is any valid variable name
Examples:
Dim MyString as string
Dim MyLen as long
MyString = "Hello World" ' Initialize variable.
MyLen = Len(MyString) ' Returns 11.
Left Function:
Returns a Variant (String) containing a specified number of characters from the left side of a string.
Left(string, length)
where string is the string expression and length is the number of characters from the left e.g.
Dim AnyString, MyStr
AnyString = "Hello World"
MyStr = Left(AnyString, 7) Returns "Hello W".
Right Function:
Returns a Variant (String) containing a specified number of characters from the right side of a string.
Right(string, length)
where string is the string expression and length is the number of characters from the right e.g.
Dim AnyString, MyStr
AnyString = "Hello World"
MyStr = Right(AnyString, 5) Returns "World".
Mid Function:
Returns a Variant (String) containing a specified number of characters from a string.
The syntax is
Mid(string, start[, length])
where
string is the string expression from which characters are returned
start is the position in the string at which the part is taken out
length is optional and is the number of characters returned.
Dim MyString, FirstWord, LastWord, MidWords
MyString = "Mid Function Demo" ' Create text string.
FirstWord = Mid(MyString, 1, 3) ' Returns "Mid".
LastWord = Mid(MyString, 14, 4) ' Returns "Demo".
MidWords = Mid(MyString, 5) ' Returns "Function Demo".
Instr Function:
Returns a Variant (Long) specifying the position of the first occurrence of one string within another.
The syntax is
InStr([start, ]string1, string2[, compare])
where
start is optional and sets the starting position for the search
string1 is the string being searched
string2 is the complete expression
compare is optional and defaults to the option compare settings (binary or text)
Examples:
This example deals with the string containing M.D. When the string is found, the program takes out the physician's name and prints it to the output file and to the picture box. If the string is not found, the program continues with next command.
x = InStr(st_linestring, st_MD1)
j = InStr(st_linestring, "M. D.")
k = InStr(st_linestring, "MD")
l = InStr(st_linestring, "M.D")
m = InStr(st_linestring, "MD.")
If x <> 0 Or j <> 0 Or k <> 0 Or l <> 0 Or m <> 0 Then
y = InStr(st_linestring, ",")
st_MDname = Left(st_linestring, y - 1)
pic_1.Print st_MDname; "~"
Print #2, st_MDname; "~"
Print #4, st_MDname; "~"
else
endif
Please note that we did not explicitly define the compare condition. Instead in the general declaration, we used
the following command: Option Compare Binary
Trim Functions:
Returns a Variant (String) containing a copy of a specified string without leading spaces (LTrim), trailing spaces
(RTrim), or both leading and trailing spaces (Trim).
The syntax for these commands are
LTrim(string)
RTrim(string)
Trim(string)
The required string is any valid string expression. If string contains a null, null is returned.
Examples:
Dim MyString, TrimString
MyString = " <-Trim-> " ' Initialize string.
TrimString = LTrim(MyString) ' TrimString = "<-Trim-> ".
TrimString = RTrim(MyString) ' TrimString = " <-Trim->".
TrimString = LTrim(RTrim(MyString)) ' TrimString = "<-Trim->".
' Using the Trim function alone achieves the same result.
TrimString = Trim(MyString) ' TrimString = "<-Trim->".
If Left(st_linestring, 7) = "TxtLine" Then
st_temp5 = Mid(st_linestring, 23, 10)
st_temp5 = Trim(st_temp5)
Print #3, st_temp5; "~"
GoTo break
Else
End If
In this example, if the string st_linestring contains "TxtLine", then we use the Mid function to get the error number and then use the Trim function to delete the spaces. We assign it to a new string st_temp5 and print it to the output file. We then use goto break to make an exit from the loop.
Sequential Files:
Sequential access files are similar to cassette tapes in that each record is stored and retrieved in consecutive order. Sequential files are easy to create but are slow for data retrieval. Lets look at the following picture
In Visual Basic, you can open a file using the Open statement. The syntax is
Open filename for mode as # filenumber
where
filename is the name of the file you want to open
mode is either input (read data), output (write data) or append (add data)
filenumber is an integer between 1 and 511 for reference
Before we get into an example, there are a few things to remember when working with sequential files. The command for reading is input # filenumber or line input # filenumber. The command for writing to a file is write # filenumber. In order to check the end of file use EOF function. Also remember to close the file using this command Close # filenumber. In order to loop through the data, you will need some kind of repletion structure. I like to use the Do..loop but it is your call. Lets look at the following example.
Examples:
Open "c:\kashef\patho_bcp.txt" For Input As #1
Open "c:\kashef\tilda.txt" For Output As #2
Do While Not EOF(1)
y = y + 1
Line Input #1, st_line
For x = 1 To Len(st_line)
st_comp = Mid(st_line, x, 1)
If st_comp = st_tilda Then
count = count + 1
End If
Next
Loop
Close #1
Close #2
In this example, first we open a file for input ( read from ) and then we open a different file for output ( write to ). Then we use a do-loop to make sure it is not the end of file 1. Using the command Line input #, we read one string. After the program reads the string, we then use an for-next loop to read every character in that string. We count the number of tildas in this string and continue with the next string. This part of the program was used to find records with incorrect number of tildas. The programmer has the option of writing the records
to the output file ( tilda.text ) which can be corrected at a later time. |