01 Overview

..Early computer languages were Command Line languages. A user
wrote a program, compiled it,And ran the EXE from the Command
Line (DOS prompt - C: \ ). If a visualInterface (suchAs a display graphOr locationTo Type
In information) was needed, the user hadTo Write the codeTo manipulate every
pixelOn the screen that was neededTo create the display.
Visual Basic greatly simplified this process by providing the capability
To create userInterface items (windows, buttons, textboxes, etc.) easily
using just a mouse. All of the codeFor the userInterface Object was pre - writtenAnd
storedIn "runtime" files, which handled the details of interfacingWith
the Windows OS. All a user hadTo Do was draw the buttonAnd
Write the codeTo respondTo events suchAs a mouse clickOr the
pressing of keysOn the keyboard.
VB3 was the first versionTo achieve popularity. VB6 has been the most popular
of allAnd Is still used by more programmers than the most recent edition- VB.net.
Another key feature of VBIs that it uses anEvent - driven model. When a VB program
starts it goes through some initializationAnd Then basically waitsFor anEvent To occur.
Events are such things are mouse clicksOr button presses by the user. A VB program
consists primarily of the code which respondsTo these events.

02 Sample code

Sub Command1_click
'create a new VB program with a single window and a single button
'put the line below in the button click event . The line is executed when the button is pressed
'MsgBox Is a built-In VB function which pops up a window with the specified text
MsgBox"Hello world!"
End Sub

03 IDE

..VB comesWith a graphical intefaceFor enteringAnd executing
code (some languages still use the command line). TheInterface
Is called the Integrated Developement Environment (IDE)
The IDEAnd compiler are integrated.
The basicFunction of the IDEIs To provide a text editorFor
writing your code.
The second basicFunction of the IDEIs To allow youTo run your
program immediately (simply press F5), without first havingTo
compile your program.
The third primaryFunction of the IDEIs To allow yourTo compile
your program.
VB 's IDE allows you to open one or more projects or to combine
projects into groups.
The IDE also manages the addition / deletion of forms, modules
And Class filesTo your projects.
The IDE provides some other very key features:
1. code editorWith syntax highlighting
2. Intellisense (displays possible optionsTo finishing a line of code)
3. programs can be executed immediately from the IDE
4. programs can be compiledTo create an EXEFor later execution
5. debug features, includingStep - by - Step execution of a program
6 expression watches, where you can pauseWhen specified conditions are met

04 Syntax

'VB code is written one line at a time, A line of code is called a statement. (Not all languages
'recognize the end of a line as the end of a statement).
MyString= "hello"
'There are two variations on the rule of one line per statement:
'1. The underline character can be used to allow a long line of code to span multiple physical lines (simply a visual aide)
MyString= "the boys are about" & _
"where we want them"
'2. A colon can be used to put two or more statements on a single line
MyString= "hello" : YourString= "goodbye"
'VB allows the placement of comments in a line - comments are descriptive text which
'will be ignored during execution of the program. Comments are usually shown in
'the IDE as green-colored text. There are two ways to comment code:
'1. start the line with 'REM'
Rem this is a comment line
'2. all code to the right of an apostrophe is treated as a comment
MyString = "hello" 'comments go here

05 Data types / variables

VB,Like most programming languages, stores informationIn multiple
formats. The basicData types supported by VB are:
'Integerwhole numbers -32,768 to +32,767 2 bytes
'Longwhole numbers -2,147,483,648 to +2,147,483,647 4 bytes
'Singlenumbers with decimal points -1.4E-45 to +3.4E384 bytes
'Doublenumbers with decimal points -4.9E-324 to 1.8E308 8 bytes
'Booleanvalue of True or False only
'Stringssequences of characters, such as "abc123"
'Bytesingle character 0 to 255
'Dateincludes date and time
'Variantany type from the list above
'Variables are names assigned to store values. Variable naming rules are:
'1. Start with a letter
'2. Consist of letter, numbers, or an underscore '_'
'3. Cannot exceed 255 characters
'To create a variable of a certain type, use the Dim function
Dim MyStringAs String
MySring= "abc"
Dim YAs Integer
Y= 2
'VB also supports a user-defined type (UDT), which is a combination
'of the other types
Type Address
AddressAs String
CityAs String
StateAs String
ZipAs String
EndType
Dim RAs Address
R.Address= "101 Clover Lange"
R.City= "Tulsa"
R.State= "OK"
R.Zip= "72310"
'These VB function are available to convert 1 data type into another
Cbool (expression)
CByte (expression)
CCur(expression)
CDate (expression)
CDbl (expression)
CDec (expression)
CInt (expression)
CLng (expression)
CSng (expression)
CStr (expression)
CVar(expression)

06 Operators

'VB supports the following operators
'Arithmetic
+ additionFor numbers
- substraction
/ division
\ Integer division, discards theDecimal part of the answer
* multiply
^ exponentiation
Mod division, returning only the remainder
'Comparison
= equal
less than
greater than
Not equal
>= greater thanOr equalTo
<= less thanOr equalTo
Is two variables / objects are the same
Like variable matches a pattern
'Concatenation
combines two strings into one
+ combines two strings into one ( Is addition for numbers)
'Logical
And logical conjunction (both valuesTrue )
Or logical disjunction (either valueTrue )
Not logical negation (reversesTrue / False value)
Xor logical exclusion ( True If one,And only one,Is True )
Imp logical implication (e9e9
Eqv logical equivalence ( True If both have same logical value)

07 Boolean logic

'Boolean refers to logical relationships - True or False, and is named
'after mathematician George Boole.
'VB supports the following Boolean opertors
Or
And
Not
Xor
'The following operators are also supported but see very little use by VB programmers
Eqv
Imp
Is
'To create a Boolean variable, use this:
Dim XAs Boolean
'Mathematical values used in Boolean expresssion are converted to Boolean values as follows:
0 becomesFalse
all other values becomeTrue .
'Boolean values used in mathematical expressions are converted to mathematical values as follows:
False becomes 0 i.e. False * 2= 0
True becomes- 1 i.e. True * 5= - 5
'results of applying Val to Boolean
Val( True )= 0
Val( False )= 0
Abs( True )= 1
Abs( False )= 0
CInt ( True )= - 1
CInt ( False )= 0
Print True ---> True
Print False ---> False
If AThen
'0 value is treated as False
'non-zero value is treated as True
End If

08 Strings

' "abc" is a String consisting of the three letters a, b, and c
'a string variable is assigned content as follows:
mystring= "abc"
'two strings can be merged with the & operator
mystring= "abc" "def" = "abcdef"
'VB has really wide range of functions that perform string operations
Left'returns # of characters at left of string
Right'returns # of characters at right of string
Trim'removes spaces from both ends of a string
LTrim'removes spaces from left side of a string
RTrim'removes spaced from right side of a string
Ucase 'make entire string upper case
Lcase 'makes entire string lower case
Mid 'returns any or all of a string (substring)
Chr 'returns string character associated with an integer (see Ascii values)
Asc 'returns Ascii integer value of a single character
Len'retruns the length of a string (number of characters in the string)
Lset 'left justifies a string in a string of specified width, padding with spaces as needed
Rset 'right justifies a string in a string of specified width, padding with spaces as needed
String 'retuns a string consisting of a character, repeated a specified number of times
Space'returns a specified number of spaces
InStr'finds position of one string inside a larger string (position defined as starting from the left of the string)
InStrRev'finds position of one string inside a larger string (position defined as starting from the right of the string)
Like 'compares two string and returns a Boolean result
Replace'replaces a part of a string with a specified replacement string
Join'joins the elements of an array into a single string, separated by a specified delimeter
Split'separates a string into an array. separation is made at a specified delimeter
StrComp'compares two strings for equality - with various options
StrReverse'reverse the order of characters in a string
StrConv'converts a string to various formats (upper, lower, proper, ...)
Format 'formats an expression to a user-define format. format is defined by a string
FormatCurrency'formats a number as currency
FormatDateTime'formats an expression as date and time
FormatNumber'formats a number with various options
FormatPerCent'formats a number as a percent

09 Arrays

'Arrays are variables which hold multiple values. Each of the values is indexed.
'Declare an array with Dim
'Arrays default to a lower bound of zero but the user must specify the upper bound
Dim MyArray(5)As Long '6 elements, 0-6
'Users can define the upper/lower bounds
Dim MyArray(1To 15)
Dim MyArray( - 10To 10)
'Arrays can have multiple dimensions
Dim MyArray(5,5)
Dim MyArray(1To 10, 1To 50)
'Arrays whose dimensions are set with Dim are fixed-size arrays. The dimensions
'cannot be changed.
'Arrays whose dimensions can be changed are called dynamic arrays.
'They are declared with ReDim and later dimensioned again, as often as needed
Redim MyArray()'dynamic array
'then later in code:
Redim MyArray(15)'the dimensions can be changed at any time to any value
'ReDim loses values in the array unless Preserve is used
Redim Preserve MyArray(15)
'Control arrays
Variables can contain objects, suchAs textboxesOr pictureboxes,And VB supports
arrays of objectsAs well.

10 Conditional flow

'VB offers 6 basic methods of flow control
1.For ...Next
2.If ...Then
3.Select Case ... EndSelect
4.While ...Wend
5.Do ...Loop
6.Goto
'For ... Next ======
For i= 1To jStep k
...
Next i
'Example
For i= 1To 10
Print i
Next i
'If ... Then ======
If (expression)Then
...
ElseIf (expression)
...
Else
...
End If
'Example
If j6Then
Print "big"
ElseIf i32
Print "hello"
Else
Print "none of the above
End If
'Select Case ... End Select ======
Select Case (expression)
Case (variable list)
Case (variable list)
Case Else
EndSelect
'While ... Wend ======
While (expression)
...
Wend
'Do ... Loop ======
Do While |Until (expression)
...
LoopWhile |Until (expression)
For Each (variable)In (Collection)
Next
'Example
Do While j10
j= j+ 1
Print J
Loop
'Example
Do
j= j+ 1
Print J
Loop Until j= 25
'GoTo ======
Goto Line
'Example
Goto Start 'skips the next two lines
j= j+ 1
Print j
Start:
Print j

11 Scope

'Scope ------
'The scope of a variable defines which parts of your program are aware of
'the variable. When you declare a variable within a procedure (sub/function)
'only code within that procedure can access or change the value of that variable.
'The variable's scope is local to the procedure.
'Scope of a variable can be controlled by the programmer. Variables are
'declared in one of two locations - procedures or modules. In each case,
'VB allows the declaration to define the procedure as Private or Public:
'Procedure-level variables
Private 'variables are private to the procedure
Public 'n/a. procedure variables cannot be Public
'Module-level variables
Private 'variables are private to the module
'they can be accessed from within any procedure in the module
Public 'variables are available to all modules
'Example: to make a public variable, put this in the declaration section of a module
'Note: Public replaces Dim in the declaration
Public MyVarAs Long
'Example: to make the same variable private to the module, use this:
Private MyVarAs Long
'Lifetime ------
'Normally, when a variable is declared in a procedure (sub/function) it exists only as long
'as the procedure is executing. For example:
Sub MySub ()
Dim jAs Long
j= 5
End Sub
'When the program call MySub, the variable j is created. When the program exits
'MySub the variable i no longer exists.
'The exception is that if the declaration uses the keyword Static, the variable continues
'to exist between calls of the procedure:
Sub MySub()
Static Dim jAs Long
i= j+ 5
End Sub
'In this example, the value of j is kept. Each time the procedure is called, j is incremented
'by an additional 5.
'These comments apply to module variables also

12 Functions / subroutines

'VB supports two kinds of functions - Subroutines and Functions
'Both allow passing variables to the Sub/Function for use
'Subroutines execute code and return control of program to calling point
Sub MySub ()
Print "Hello"
End Sub
'Functions execute code, return a value to the program and return control of program to calling point
Function MyFunction ()As String
MyFunction= Date
End Function
'usage
MyString= MyFunction'Date is placed in MyString
'Passing variables - Sub declaration defines data type of passed variable
Sub MySub (iAs Long , sAs String , a()As Variant )
Print i
Print s
Print a(5)
End Sub
'Passing variables - Sub declaration defines how passed variables are treated
'ByValcannot alter the passed variable
'ByRefcan alter the passed variable
Sub MySub ( ByVal iAs Long ,ByRef sAs String )
i= 5'the original variable passed has not changed - ByVal
s= 10'the original variable passed is now changed - ByRef
End Sub

13 Files / Folders

'Files ======
'VB can access files as text or as binary data
' generally text files are separated into lines - string data followed by a pair of LF+CR characters
' binary files have no such LF+CR separator
'basic functions
Namerename a file
Killdelete a file
FileCopycopy a fileTo aNew location
FileLenGet length of a fileIn bytes
FileDateTimeGet Date / Time file was last modified
GetAttrGet Readonly / system / hidden / directory / archiveAttribute of a fileOr folder
SetAttrSetsReadonly / system / hidden / archiveAttribute of a fileOr folder
'Open - most important VB function for reading and writing files
' files can be opened in 4 modes - append, binary, input, output, random
'Input - error if file does not exist
Open "myfile.txt" For Input As #1
LineInput #1, temp'read a line of text at a time
Input #1, a,b,c'reads list of variables
Close #1
'Example of reading text file from start to end
Open "myfile.txt" For InpuAs #1
While Not EOF(1)
LineInput #1, temp
Wend
'output - creates file if it does not exist. erases the file before creating it.
Open "myfile.txt" For OutputAs #1
Print #1,"information" 'prints data into file. auto-inserts LF+CR
Write #1,"dog" ,"cat" 'prints data into file. quotes around strings, commas between items. auto-inserts LF+CR
Close #1
'binary -
Open "myfile.txt" For BinaryAs #1
Get #1, 32, i
Close #1
'append - text mode. write only. writing starts at end of file
Open "myfile.txt" For AppendAs #1
Put #1, 128, j
Close #1
'random - reads fixed lenght data, but may be text or binary
Open "myfile.txt" For AppendAs #1
Get #1, 32, MyUDT'reads the 32nd fixed-length record
Close #1
'Folders======
'basic functions
ChDirChange directory
MkDirMake directory
RmDirRemove directory
ChDriveChange drive
CurDirReturn current directory

14 System functions

'This tutorial covers the Windows Registry and Environment variables
'Registry -VB can access registry information at:
'HKEY_CURRENT_USER\Software\VB and VBA Program Settings\appname\section\key\value
'A registry entry includes a reference to the program, a section, a key, and a value. Windows supports
values ofString , Binary,Or DWORDType , but VB only supportsString key values. VB Registry functions are:
GetSetting'gets a value from a section\key
SaveSetting'saves a value in the registry for a section\key
DeleteSetting'deletes a section or key
GetAllSettings'returns all key/values pairs from an application\setting of the Registry
'The Registry is a database of most Windows settings, as well as those for your installed applications.
'In Windows 95, 98, and Me, the Registry is contained in two hidden files in your
'Windows directory, called USER.DAT and SYSTEM.DAT.
'In Windows 2000 and Windows XP, the Registry is stored in several Hives (special files), located
'in the \windows\system32\config and \Documents and Settings\{username} folders.
'Windows 2000 and WIndows XP have five main branches:
'- HKEY_CLASSES_ROOT - contains all of file types as well as OLE information for OLE-aware applications.
'- HKEY_CURRENT_USER - points to the part of HKEY_USERS appropriate for the current user.
'- HKEY_LOCAL_MACHINE - information about all of the hardware and software installed on your
'- HKEY_USERS - preferences (such as colors and control panel settings) for each of the users of the computer.
'- HKEY_CURRENT_CONFIG - the part of HKEY_LOCAL_MACHINE appropriate for the current hardware configuration.
'Registry Editor
'Windows includes a program called the Registry Editor (regedit.exe) which allows
'you to view and edit the contents of the Registry.
'Registry Patch
'A Registry patch is a simple text file with the .REG extension that contains one or more keys
'or values. If you double-click on a .REG file, the patch is applied to the registry. You can
'create a Registry patch by opening the Registry Editor, selecting a branch, and choosing
'Export from the File menu.
======
'Environment variables
MyString= Environ( "PATH" )'returns the Windows Path spec
'Environment variables are strings that contain information such as
'drive, path, or file name. They control the behavior of various programs.
'For example, the TEMP environment variable specifies the location in
'which programs place temporary files. The PATH environment variable
'determines the path(s) where Windows will look for executable files.

15 Graphics

'VB has limited graphics capabilities. Most serious graphics work is done using Windows API
'Coordinate system
'Graphical controls (cannot appear on top of other controls, cannot receive focus, cannot
'serve as containers and do no have an hWnd property):
'Image
'Line
'Shape
'Pictures can be displayed on:
'form
'picturebox
'image control
'Graphics methods
.Cls'clear a drawing area
.PSet'sets color of a pixel at a specified point
.Point'returns color value at a specified point
.Line'draws line between two coordinates (also draws box)
.Circle'draw circle of radius about a specified point (can also draw arcs or ellipses)
.PaintPicture'draws a picture on a form, picturebox, or printer
'These properties affect the way graphics methods appear:
.FillStyle
.FillColor
.DrawWidth'width of lines
.BorderWidth'width of outline on line and shape controls
.DrawStyle'set solid or broken pattern for lines
.DrawMode'defines what happend when one pattern is drawn on top of another
'Colors
'color is a Long integer from 0 to 16,777,215 (&HFFFFFF&)
'color is represented by red, green and blue content - each with a value of 0 to 255
'RGB function is used to set colors using RGB content
iColor= RGB (R, G, B)'R,G,B have values 0 to 255. (0,0,0) is black. (255,255,255) is white.
iColor= QBColor (i)'i = 0 to 15, corresponding to VB color constants
'represent color by this syntax (Note: this is reversed from standard Internet color syntax):
iColor= &HBBGGRR&'where BB is blue, GG is green, and RR is red content
'Non-displayed pictures
'VB offers a Picture object for loading pictures which do not need to be displayed
'The Picture object is convenient for creating animation sequences by using an array of Picture objects
Dim MyPictureAs Picture
Set MyPicture= LoadPicture( "mypicture.bmp" )