43
ICS 3M Computer & Information Science Visual Basic Additional Notes Page 1 of 43 Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an acronym for Beginner's All-purpose Symbolic Instruction Code. In the 1960s, some Dartmouth College professors designed BASIC for their students. The Dartmouth professors wanted their non-computer students to be able to write quick-and-simple programs without worrying too much about the details required from other languages that were being used at the time (like Cobol and FORTRAN). BASIC is a language that was created solely for text-mode environments. Visual Basic includes almost the full original BASIC language but goes far beyond BASIC by adding the ability to manipulate the visual components and events found in windowed environments (Windows 95/98/NT). Unlike most other Windows programming languages, such as Visual C++, Visual Basic retains BASIC's ease of use. Visual Basic's simplicity makes it one of the easiest tools to learn for the Windows programming environment. Visual Basic is simple because so much of your program development will consist of arranging graphical icons and controls on the screen while using a Paint-like program editor. In older languages, you'd have to write detailed commands in order to achieve the same results. Visual Basic: More than just a Programming Language Visual Basic isn't just a programming language, it's a complete development environment that includes The VB language A complete full-screen editor with which you can write your program and which works a lot like a word processor A project manager that lets you create multiple-file Visual Basic Windows applications A runtime environment that lets you see the results of your program with the click of a button An interactive testing platform that helps you locate and find program bugs VB graphical controls Visual tools that let you manage the controls and icons that make programs function properly under the visual Windows environments Online help When you learn Visual Basic, you must learn more than just a new set of commands. You must also master the Integrated Development Environment (IDE).

Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

Embed Size (px)

Citation preview

Page 1: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 1 of 43

Introduction to Visual Basic

Visual Basic's Origins:

The name BASIC is an acronym for Beginner's All-purpose Symbolic Instruction Code. In the 1960s, some Dartmouth College professors designed BASIC for their students. The Dartmouth professors wanted their non-computer students to be able to write quick-and-simple programs without worrying too much about the details required from other languages that were being used at the time (like Cobol and FORTRAN).

BASIC is a language that was created solely for text-mode environments. Visual Basic includes almost the full original BASIC language but goes far beyond BASIC by adding the ability to manipulate the visual components and events found in windowed environments (Windows 95/98/NT). Unlike most other Windows programming languages, such as Visual C++, Visual Basic retains BASIC's ease of use. Visual Basic's simplicity makes it one of the easiest tools to learn for the Windows programming environment. Visual Basic is simple because so much of your program development will consist of arranging graphical icons and controls on the screen while using a Paint-like program editor. In older languages, you'd have to write detailed commands in order to achieve the same results.

Visual Basic: More than just a Programming Language

Visual Basic isn't just a programming language, it's a complete development environment that includes

• The VB language • A complete full-screen editor with which you can write your program and which works a lot like a

word processor • A project manager that lets you create multiple-file Visual Basic Windows applications • A runtime environment that lets you see the results of your program with the click of a button • An interactive testing platform that helps you locate and find program bugs • VB graphical controls • Visual tools that let you manage the controls and icons that make programs function properly

under the visual Windows environments • Online help

When you learn Visual Basic, you must learn more than just a new set of commands. You must also master the Integrated Development Environment (IDE).

Page 2: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 2 of 43

Creating a program in Visual Basic

Before setting out to write a program in a Visual-Events Driven Environment, you should have the following program-development model in mind:

1. Determine all of the need of the end use that need to be satisfied 2. Plan the program requirements that will fulfill all of those needs 3. Designing the Visual Interface (creating objects)

Designing the Visual Interface is done interactively without the need to create any code.

Screen objects (or controls) are selected from the toolbox, placed on a form and sized using the mouse. When you launch VB, the environment is in design mode, presenting a blank form, labeled Form1. This is where the user-interface is constructed. To place a control on Form1, double click on a toolbox icon. That object appears in the center of the form. From here the object may be dragged into place using the mouse.

4. Setting the Initial Properties of the Objects of the User Interface

Setting the properties of the screen objects to change such things as colors and labels. Properties are set using the properties window. If this is not visible press F4 or use the Windows menu to show it. To set the properties of a screen object. click on the object. The object box (under the properties title bar) displays the name of the object. This is a list box that can be used to select any of the objects on the current form. The property value can be edited by typing, or by selecting from a pre-defined list of possible values (obtained by clicking on the down arrow to the right of the settings list if available).

5. Writing the program code

Writing program code to specify what will happen as users interact with the screen objects. This step is often described as providing the 'functionality'. The final step is writing the code that activates the application, or makes it run. Once the correct control object has been selected the next step is to choose which event the control is going to respond to. Since version 4 of VB the code window can display multiple procedures. The horizontal line drawn half way down the window signifies a division between two different subroutines.

6. Test-Run the program Run the Visual Basic application

To run a Visual Basic program, you only need to click a toolbar button. Visual Basic does the rest of the work. Visual Basic then interactively runs your program.

7. Correct the bugs and Release the final Product (convert to machine-readable form)

After you have tested the product, you may find mistakes which you can correct. When all of the mistakes or "bugs" are worked out of your program, it is time to release it. To release the application as a final product, you must compile it to an executable program (make an ".EXE" file). This executable file can then be run without the need for VB.

Page 3: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 3 of 43

Creating Your First Application

When you start Visual Basic, you are asked what kind of application you want to create.

We will start be choosing a "Standard EXE" file. This is the most simple type of project you can make using VB but keep in mind that VB is full blown industrial strength developer's tool with many options (like building interactive components for web pages)

You will then see the first form, the toolbox and the properties window appear in the development environment.

Page 4: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 4 of 43

The Form is the canvas on which the objects are placed. The form is actually a special case of "window" in the windows environment. It is different from a "DOS window" (a console window) because it works with objects and events in a multitasking environment.

The Toolbox contains the objects that are to be added to the form (objects like buttons and text boxes). Simply click on the toolbox to select the desired object and then draw the object on the the form using your mouse. Once the object is on the form it can be customized. One way to customize the object is to change the object's properties. This can be done using the Properties Window.

The Properties Window is a developer tool that allows the programmer to set the initial properties of a selected object. Many of these properties can (and will) be changed during the execution of this program. To change the property of an object simply select the object (single-click on it), then in the properties window select the property name you wish to set, and finally change the property value. Shown above in the properties window for the selected object (the form) is the Caption property which has its value set to "Form1". The Caption property sets the title of the form.

Once you have added the desired objects to the form and set their initial properties, it is necessary link some code the objects in order to have a useful Program.

Page 5: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 5 of 43

Forms (Loading, Unloading, hiding and Showing)

To Bring up another form use the following code in a function....

Load Form_name

Form_name.Show

To Hide a form use the following code in a function ....

Form_name.Hide

To Show a hidden form use the following code in a function ....

Form_name.Show

To Eliminate a form (destroy it) use the following code in a function ....

UnLoad Form_name

Modules in VB

Modules

Modules are sections of code that contain variables and function/procedure declarations which can be shared among all forms and functions within the project.

To create a module, select Add Module, from the Project menu bar, then click open, and finally a code window will appear.

Page 6: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 6 of 43

This is where you will place any Global Variable declarations as well as define your own Global procedures and functions.

Page 7: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 7 of 43

Visual Basic Objects and Events

Visual Basic is an event driven - object based programming language (not quite object oriented). Visual Basic doesn't contain a few of the advanced but needed requirements for a truly technically pure OOP language, but Visual Basic is about as object-oriented as a language can get in many ways.

Visual Basic instantly offers you a set of predefined objects that you'll recognize right away, such as command buttons that you can add to your program just by clicking on the toolbox to select the desired object and then drawing the object on the the form using your mouse.

Shown here are some (but certainly not all) of the Visual Basic Objects you can use in your program.

Hooking these objects into your Visual Basic code is much simpler than doing the same from within a true OOP language such as C++. Visual Basic allows you to use more than the standard Windows controls such (like command buttons). Third-party developers make new controls for you to plug into your own Visual Basic programs all the time. If you need to insert a spreadsheet or calendar in your Visual Basic program, you don't have to write the code to implement it. You can add a calendar feature to your Visual Basic program by dragging a calendar tool that's available as a Visual Basic control, or a VBX for older versions of VB and OLE Control Extensions (OCXs) and ActiveX controls (controls that work in web browsers on the Internet) in newer versions of VB. You can download these controls from the Internet or you can purchase them.

Page 8: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 8 of 43

Objects and events are closely related in that an action upon an object produces an event.

Objects and Events in Visual Basic Objects: Anything that can be manipulated. For the most part, objects are any graphical entity

which can be placed on a form. Objects have preset properties and behaviours which react to user interaction, such as clicking the mouse or selecting the object using a mouse.

Events: Events happen to Objects.

Events or actions occur as a result of user action with objects. Since many events are common throughout windows programs, most events are predictable and reliable.

Properties: The Properties of an object define the characteristics of that object. Properties can be set at Design Time or at Run Time (while the program is running).

While in the VB design mode, hit the F4 key to display the current properties of each object.

Setting Properties at Design Time

The syntax for setting an objects properties is:

object.property = _________________

for example: frmmain.backcolor = blue 'set new background color for form

Setting Properties at Run Time

The syntax for setting properties is:

controlname.property = value

for example: lblname.caption = "Name" txtamount.text = val(txtamount.text) * 1.1

Methods: Methods are functions that act on an object and they can only be executed at Run Time. When executing, a methods may require additional information.

The syntax for executing a method of an objects is:

object.method arg1, arg2

for example: picFace.move 0,0 'moves to upper left of window

Page 9: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 9 of 43

Text Boxes in VB

Textboxes are interactive windows that you can use to input or output text.

To use a textbox, draw out the textbox on the form and manipulate its properties.

Here are the most useful properties of a text box (but there are many more):

Property Description Example (for a textbox called text1)

Text This is the contents of the text box (you can set it or retrieve from it)

text1.Text = "Hello" name = text1.Text

Visible When set to "True" the text box is shown When set to "False" the text box is NOT shown

Text1.Visible = False Text1.Visible = True

Enabled When set to "True" allows the use to enter text When set to "False" does not allow the use to enter text

Text1.Enabled = False Text1.Enabled = True

MultiLine

When set to "True" the text box can take multiple lines of Input. When set to "False" the text box can take only one line of Input.

Text1.MultiLine = False

Text1.MultiLine = True

Page 10: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 10 of 43

ForeColor Sets the color of the font in the textbox (this is a number value) Text1.ForeColor = 250

BackColor Sets the color of the textbox background (this is a number value) Text1.ForeColor = 128

Font Sets the font typeface in the textbox (this is a string stating the name of the font) Text1.Font="Arial"

PasswordChar This hides the characters as they are being typed in and displays the character that you specify.

Text1.PasswordChar = "*"

Height Changes the height of the textbox Text1.Height = 500 Width Changes the width of the textbox Text1.Width = 2500

Top Changes the vertical position of the textbox on the form Text1.Top = 0

Left Changes the horizontal position of the textbox on the form Text1.Left = 0

MousePointer You can change the mouse pointer when it enters the textbox (this is a number value) Text1.MousePointer = 1

Note:

Any data taken from a text box is a STRING (not a number, even if you type in digits).

Therefore, if you want numeric data out of a textbox, you will have to convert it to a number using the Val( ) function.

For example:

x = Val( text1.text )

... this take the contents of the text box called text1 , converts it to a number and stores the number in a variable named x.

Page 11: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 11 of 43

Labels in VB

Labels are non-interactive windows that you can use to display text.

To use a label, draw out the label on the form and manipulate its properties.

Here are the most useful properties of a label (but there are more):

Property Description Example (for a textbox called Label4)

Caption This is the contents of the Label (you can set it or retrieve from it)

Label4.Caption = "Hello"L4 = Label4.Caption

Visible When set to "True" the Label is shown (visible) When set to "False" the Label is NOT shown (not visible)

Label4.Visible = False Label4.Visible = True

Alignment Sets the alignment of text to left , right or centered (left = 0, right = 1 and center = 2) Label4.Alignment = 0

ForeColor Sets the color of the font in the textbox (this is a number value) Label4.ForeColor = 250

BackColor Sets the color of the Label background (this is a number value) Label4.ForeColor = 128

Page 12: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 12 of 43

Font Sets the font typeface in the Label (this is a string stating the name of the font) Label4.Font="Arial"

Height Changes the height of the Label Label4.Height = 500 Width Changes the width of the Label Label4.Width = 2500

Top Changes the vertical position of the Label on the form Label4.Top = 0

Left Changes the horizontal position of the Label on the form Label4.Left = 0

MousePointer You can change the mouse pointer when it enters the textbox (this is a number value) Label4.MousePointer = 1

Scroll Bar Controls

Scroll bars provide easy navigation through a long list of items or a large amount of information. You may use a scroll bar as an input device or indicator of some quantity (ie: to control the volume of a computer game).

There are two types of scroll bar controls:

1. The Horizontal Scroll Bar 2. The Vertical Scroll Bar

Page 13: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 13 of 43

Important Scroll Bar Properties

The "Value" property of the scroll bar is used to get or to change the position of the bar. The value will always be between the values contained in the Max and Min properties.

objectName.Value = value

Hscrol1.Value = 50

Here are the most useful properties of a Scroll Bar (but there are many more):

Property Description Example

(for a ScrollBar named ScrollB1)

Value

This sets the value (and the position) of the Scroll Bar (you can use this property to set the value or retrieve the value)

ScrollB1.Value = 5 X = ScrollB1.Value

Min

This sets the Minimum possible value a scroll bar can have (you can use this property to set the Min value or retrieve it)

ScrollB1.Min = 10 theMin = ScrollB1.Min

Max

This sets the Maximum possible value a scroll bar can have (you can use this property to set the Max value or retrieve it)

ScrollB1.Max = 100 theMax = ScrollB1.Max

SmallChange This sets the value for a small movement on the scroll bar (for clicking the arrows at the ends of the scroll bar)

ScrollB1.SmallChange = 1

LargeChange This sets the value for a large movement on the scroll bar (for clicking in the scroll bar)

ScrollB1.LargeChange = 10

Enabled

When set to "True" allows the user to move the Scroll Bar When set to "False" does not allow the user move the Scroll Bar

ScrollB1.Enabled = TrueScrollB1.Enabled = False

Visible When set to "True" the Scroll Bar is shown When set to "False" the Scroll Bar is NOT shown

ScrollB1.Visible= True ScrollB1.Visible= False

Height Changes the height of the Scroll Bar ScrollB1.Height = 500 Width Changes the width of the Scroll Bar ScrollB1.Width = 2500

Top Changes the vertical position of the Scroll Bar on the form ScrollB1.Top = 0

Left Changes the horizontal position of the Scroll Baron the form ScrollB1.Left = 0

MousePointer You can change the mouse pointer when it enters the Scroll Bar (this is a number value)

ScrollB1.MousePointer = 1

Page 14: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 14 of 43

Important Scroll Bar Events

• The "Scroll" Event • The "Change" Event

Working With Shapes

The SHAPE control is used to create certain shapes (rectangle, square, oval, circle, rounded rectangle, or rounded square) on forms, frames, or picture boxes: .

The shape control is represented on the toolbar by ...

Each Shape object has properties that you can manipulate such as ...

• The shape style(square, oval, ...) • The shape colour • The shape fill style • The shape border colour • The shape border style

Page 15: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 15 of 43

The Shape property of the shape control has six predefined shapes.

The Shape Number Constant Rectangle 0 vbShapeRectangle Square 1 vbShapeSquare Oval 2 vbShapeOval Circle 3 vbShapeCircle Rounded Rectangle 4 vbShapeRoundedRectangle Rounded Square 5 vbShapeRoundedSquare

Fill and Line Styles You can use the FillStyle and BorderStyle properties to set the fill style and border style of any of the SHAPE you draw on a form.

The FillStyle property, like the Style property, provides you with a number of predefined fill style patterns. These include: Solid, Transparent, Horizontal Line, Vertical Line, Upward Diagonal, Downward Diagonal, Cross, and Diagonal Cross.

The BorderStyle property provides you with a number of predefined border styles. These include: Transparent, Solid, Dash, Dot, Dash-Dot, Dash-Dot-Dot, and Inside Solid.

Setting Color Attributes The BackColor and FillColor properties allow you to add colour to the SHAPE and its border.

To set colors at run time, use the Visual Basic colour constants (vbGreen, for example) or the system color constants (vbWindowBackground, for example) or the RGB function to specify fill colors.

Note: When the FillStyle or BackStyle properties are set to 1 (Transparent), the FillColor and BackColor properties are ignored.

The Dimensions of a Shape (Height & Width Properties) The Height and Width properties of a shape control return or set the dimensions of a shape object.

How to Use these Properties

ShapeObject.Height [= number]

ShapeObject.Width [= number]

Note: these are measured from the center of the shape's border so that shapes with different border widths align correctly.

Page 16: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 16 of 43

Positioning a Shape Object

Positioning a Shape Object involves changing two properties:

• Left - returns or sets the distance between the internal left edge of an object and the left edge of its Form (or container).

• Top - returns or sets the distance between the internal top edge of an object and the top edge of its Form (or container).

How to Use these Properties

object.Left [= value]

object.Top [= value]

Visible Property The Visible property is used to return or set a value indicating whether an object is visible or hidden.

How to Use this Property

object.Visible [= Boolean]

Setting Description True Object is visible. False Object is hidden.

Other Useful Information

Forms have a Left and a Top property which are expressed in twips by default. You can (and should) change the units of measure to something familiar (like pixels, or mm or inches). The shape controls are measured in the same units as the coordinate system of the form (or container) it is attached to. The values for these properties change as the object is moved by the user or by code.

For operations based on an object's external dimensions use properties:

• Left • Top • Height • Width

These properties are used for moving or resizing. For operations based on an object's internal dimensions use properties:

• ScaleLeft • ScaleTop • ScaleHeight • ScaleWidth

The scale-related properties apply only to PictureBox controls and Form

Page 17: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 17 of 43

Working With Images

The IMAGE control is used to display a graphic. An Image control can display a graphic from a bitmap, icon, or metafile, as well as enhanced metafile, JPEG, or GIF files.

The Image control uses fewer system resources and repaints faster than a PictureBox control, but it supports only a subset of the PictureBox properties, events, and methods.

Stretch Property The Stretch property returns or sets a value indicating whether a graphic resizes to fit the size of an Image control. Use the Stretch property to determine whether the graphic is scaled to fit the control or vice versa. Although you can place an Image control within a container, an Image control can't act as a container.

How to Use these Properties

object.Stretch [= Boolean]

Setting Description True The graphic resizes to fit the control.False The control resizes to fit the graphic.

Page 18: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 18 of 43

File Controls (Selecting a file name)

There are three different controls (objects) that can be use together to select a file name.

• FileListBox (changes the file drive letter) • DirListBox (changes the file path) • FileListBox (changes which file is selected in the current path)

It is important to remember that all three of these components are independent of each other. You must link the three together in order to properly select a file name.

Using the Properties of each object toy can build a file name that you can then use VB code to open up and work on.

• For the FileListBox Object we will use the "Filename" property. • For the DirectoryListBox Object we will use the "Path" property. • For the DriveListBox Object we will use the "Drive" property.

Page 19: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 19 of 43

Here is some code to link all three objects together to get a file name in a textbox:

Private Sub Drive1_Change() Dir1.Path = Drive1.Drive End Sub Private Sub Dir1_Change() File1.Path = Dir1.Path End Sub Private Sub File1_Click() If Len(File1.Path) > 3 Then Text2.Text = Dir1.Path + "\" + File1.filename Else Text2.Text = Dir1.Path + File1.filename Endif End Sub

Page 20: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 20 of 43

Variables

Creating Variables = Setting Aside Memory

Variable:

A variable is a temporary storage location in memory. Variables can be modified during program execution and can be read to see what they contain. To use a variable in a program, it must be defined by giving its type and identifier. A Variable Identifier is how the variable is referred to within a program (the variable name).

Variable Types in VB:

In VB there are different types of variables available to be used. The type that you use depends on what you want to accomplish with your program. A variable type will indicates the kind of value (data) that the variable will store.

There is a trade-off in many cases between on how much space is used to store data in a variable vs how much precision you want to keep when storing numbers and you may choose the appropriate variable type according to your needs.

Each spot in memory is one byte in size. If the type of variable you create is two bytes in size, it needs two bytes of memory to store the value for that variable. The type of the variable (ie: a character) tells the compiler how much memory (bytes) to set aside to store the value for that particular variable.

The following variable types are available in VB ...

Data Type Suffix Storage Size Range Boolean none 2 bytes True or False Integer % 2 bytes -32,768 to 32,768

Long (integer) & 4 bytes -2,147,483,648 to 2,147,483,647

Single (precision) ! 4 bytes -3.40E38 to 3.40E38 Double (precision) # 8 bytes -1.80E308 to 1.80E308

Currency @ 8 bytes -9.22E14 to 9.22E14 String $ 1 byte/character max of 65,532

Variant none as appropriate determined by type

Page 21: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 21 of 43

Naming Variables in Visual Basic

You are free, in any program, to give variable's a meaningful, descriptive name. When you start to write a program, think about what each and every variable name should be. In any program try to make variable name's apply to whatever the variable is storing. For example the variable name telephone will obviously store a telephone number of some sort. So if it is a telephone number you want to store, it's best not to call it something like pn. This practice will make life a lot easier later on when you come to write long programs.

There are some restrictions on how variables are named in Visual Basic:

• Names must begin with an alpha character (A-Z or a-z) • Names cannot contain a period ( . ) because this is used for properties • Names have a maximum length of 255 characters • Names can not be reserved words (like the words if, begin, end, for ....)

It is a good habit to use VB standard naming conventions for all objects. This is done to avoid confusion when combining of forms. Also, because this is a standard practice for the visual basic programmers around the world, it makes it easier to share and understand other people's code.

The following is some of VB's standard naming conventions for a few objects:

VB Object Prefix VB Object Prefix Form frm Option Button opt

Command Button cmd Check Box chk Label lbl List Box lst

Text Box txt Combo Box cbo Menu mnu Picture Box pic

Variable Declarations in VB:

Implicit

If when using the variable you apply the appropriate suffix, the compiler will automatically assign the value as the given type.

For example to implicitly declare AGE as an integer:

AGE% = 40 ‘implicit variable declaration

Page 22: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 22 of 43

Explicit

The proper way to declare variables in VB is to use the DIM statement to declare them at the beginning of the procedure.

For example:

DIM AGE as INTEGER DIM WEIGHT as DOUBLE

Variable Scope in VB:

Variables have a specific lifetime and can only be accessed at certain times by a restricted list of objects. Depending where a variable is declared, it may be accessible only to specific objects, forms or may be global to the entire project.

Here are the different variable scopes allowed by VB:

Local Scope:

Variables can be declared within each object. For example during the execution of a command button you may need a temporary storage area. It is not available beyond that procedure.

Use Dim

Form Level Scope:

Variables declared in the general declarations of a given form are available in every object within that form.

Use Private

Global Scope:

Variables declared in the general declarations of a module, are available throughout the project, in every form, object.

Use Public

Page 23: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 23 of 43

Global Variables in VB

Just to review, variables have different scopes:

1. Global Scope - available to any form or module contained in the project. 2. Module Scope- available to any procedure on the form on which it is placed. 3. Local Scope (Procedure Scope) - available only within the procedure in which it is declared.

Use Global inside a Module

Global variables are defined in a module ( a file (ie: Module1.bas) that is used to store variables and functions that are shared among forms)

A global variable can be accessed (read or written to) anywhere in the entire project.

Side-effects can occur if one part of a program accesses a variable when it shouldn't.

Page 24: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 24 of 43

Arrays in VB

An array is a storage structure (an array is a special variable) that stores a group data of the same type (like a string, integer ...).

The notation used to refer to an element of an array consists of the variable name followed by parentheses containing an index number indicating the desired element.

The Simple form of the Array:

Dim ArrayName ( size ) as type

where:

• ArrayName is the name of the variable • size is the number of elements in the array • type is the data type (string, integer, ...)

For example: Dim DayArray(30) as String

The Two-Dimensional Array:

Dim ArrayName ( size1, size2 ) as type

where:

• ArrayName is the name of the variable • size1 is the number of elements in the first dimension of the array • size2 is the number of elements in the second dimension of the array • type is the data type (string, integer, ...)

For example: Dim DayArray(12, 31) as String

The Complex form of the Array:

Dim ArrayName ( beginning To end ) as type

where:

• ArrayName is the name of the variable • size is the number of elements in the array • type is the data type (string, integer, ...)

Page 25: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 25 of 43

For example: Dim MyMatrix(1 To 5, 4 To 9, 3 To 5) As Double

Let's look at the differences between a Regular variable and an Array variable:

Shown below are two variables, X and Y, both of which hold String data.

Dim X as String

Dim Y(10) as String

The variable "X" takes up one block of memory space and the variable "Y" takes up ten blocks of memory space.

To access the value stored in X you can do something like ...

• somevariable = X • msgbox (X)

To access a value stored in Y you must specify which position in Y you want to retrieve. You can do this like ...

• somevariable = Y(3) • i = 5

msgbox ( Y( i ) )

To change a value stored in X you can do something like ...

• X = somevariable • X = InputBox ("name")

Page 26: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 26 of 43

To change a value stored in Y you must specify which position in Y you want to retrieve. You can do this like ...

• Y(3) = somevariable • Y(4) = "Bart" • i = 5

Y( i ) = InputBox ("name5")

Sample use of an array:

This sample uses an array to enter 100 marks from the user and calculates the average of those marks:

Dim marks(100) as Integer avg = 0 For i = 1 To 100 marks(i) = Val(InputBox("Enter Mark #" & Str(i) & "please")) avg = avg + marks(i) Next i avg = avg / 100 MsgBox("the Average is " & Str(avg) )

Page 27: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 27 of 43

Functions and Procedures in VB

In programming, it is good practice to group code into modules by the type of functionality they perform. These modules are known as FUNCTIONs and Procedures. These functions / procedures perform well defined tasks.

In Visual Basic (and other programming languages) functions and procedures are a lot like "mini-programs" that can execute simultaneously (the can run at the same time) . Because they are like mini versions of programs, any variable that is declared in a function will only be available while that functions is executing (when the function is done, the variable is gone).

There are two varieties of functions:

• user-defined functions you create these functions • built-in functions these are already define (programmed) and are a part of VB

For user-defined functions there is a 2-step process:

1. There must be a function definition - the actual code of a function is written. This is declaring the function.

2. There must be a function call (the function is invoked). This is using the function.

Functions may require parameters. Parameters are declared in the header of the function with the parameter type being specified. See the note on parameter passing

Functions

A Function is a series of statements that perform a specific task and returns a value. The value returned is dependent on the type of function. It could be Boolean, integer, double or string.

When "calling" a function, you can assign its value to a variable or output the results directly.

Visual Basic has many built-in functions but you can create your own.

The basic syntax is :

ReturnValue = Function_Name (argument list )

for example:

Cost = PMT(rate, nper, pv, fv, due)

Page 28: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 28 of 43

Procedures

A procedure is a named sequence of statements executed as a unit. There are a number of built-in procedures that Visual Basic offers.

In order to use these procedures you simply need to "call" them with the proper number of arguments.

The basic syntax is:

Procedure_name (argument list)

for example: (see below)

Built-in VB Procedures Procedures Description Example

Filecopy Copies a disk file Filecopy "Oldfile" "Newfile" Name Renames a file Name "Oldfile" as "NewFile" Kill Deletes a file Kill "Deadfile" Beep Sounds a beep Beep

Page 29: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 29 of 43

String Functions in VB

There are built-in function in Visual Basic that deal with string manipulation.

These function come in especially handy when you are dealing with:

• TEXTBOXES (remember that textboxes ONLY deal with strings - not numbers - so you must convert data types)

• the MsgBox( ) function • the InputBox( ) function

Here are some of the string manipulations functions that are built into the Visual Basic Language:

Function Description Example Return Value Len( ) Returns the length of the string strlength=Len("Hello") strlength = 5 Val( ) Converts a string to a numeric value Value = Val("78") Answer = 78 Str( ) Converts a numeric value into a string Answer = Str(78) Answer = "78" Chr( ) Returns character equivalent Letter =Chr(65) Letter = "A" Asc( ) Returns ASCII equivalent Value = Asc("A") Value = 65 Ucase( ) Converts to uppercase Answer = Ucase("Hello") Answer = HELLO Lcase( ) Converts to lowercase Answer = Lcase("Hello") Answer = helllo Isnumeric( ) Verifies if a value is numeric Testit = Isnumeric(Answer) Testit = false Format( ) Formats the given text with predefined

formats txtanswer.text = Format(1000.5,"standard")

txtanswer.text= 1,000.50

Strcmp( ) Compares two strings (true or false) Answer = StrComp("A","a",1) Answer = true Trim( ) Removes all leading and trailing spaces Answer = Trim(" Hello ") Answer = "Hello"

Page 30: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 30 of 43

Math Operations in VB

In Visual Basic, there are certain math functions available for you to use:

see Visual Basic help for the built-in function available ...

Note: When doing math equations in your programs, remember the order of operations (remember math class ?).

Mathematical Operation Boolean Logic Brackets ( ) NOT

Exponents ^

Multiplication * AND

Division /

Addition + OR

Subtraction -

Page 31: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 31 of 43

The MsgBox( ) function (the Message Box)

MsgBox( ) is a function which displays a dialog box to the user that contains a short message that you specify. MsgBox can be used as a procedure or a function.

As a procedure,

The syntax is:

MsgBox msg, type, title

For example:

MsgBox "Hello there world", , "Greetings"

As a function

The syntax is:

Answer = MsgBox(msg, type, title)

If you need to know whether the user has clicked on the OK button or the Cancel button then you should use Msg as a function.

Sample:

Returnvalue = MsgBox ("Name entered is" & Name, vbYesNoCancel, "Name check") if returnvalue = 2 then exit

The MsgBox( ) "type" parameter Value Meaning Symbolic Constant

0 Display OK button vbOKOnly 1 Displays OK and Cancel buttons vbOKCancel 2 Displays Abort, Retry, and Ignore buttons vbAbortRetryCancel 3 Displays Yes, No and Cancel buttons vbYesNoCancel 4 Displays Yes and No vbYesNo 5 Displays Retry and Cancel vbRetryCancel

16 Display Critical Icon vbCritical 32 Displays Question Mark vbQuestion 48 Displays Exclamation Point vbExclamation 64 Displays Information Icon vbInformation

Page 32: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 32 of 43

MsgBox( ) function Return Values Value Meaning

1 Ok button selected 2 Cancel button selected 3 Abort button selected 4 Retry button selected 5 Ignore button selected 6 Yes button selected 7 No button selected

Page 33: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 33 of 43

The InputBox( ) function (the Input Box)

InputBox( ) is a function which displays a dialog box with a prompt and then waits for the user to enter text or choose the OK or Cancel buttons and finally it return the contents of the textbox.

The syntax for using an input box is:

returnvalue = InputBox(prompt, title)

where:

• prompt is the question the the user is asked • title is the title on the top of the input box • returnvalue is some variable that you choose to store the STRING that was entered by the

user.

Remember, the input box returns a string, not a number. If you want a number, you must convert the returnvalue variable to a number using the Val( ) function.

ie: number = Val(returnvalue)

This is how an InputBox( ) function works:

Page 34: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 34 of 43

here is an example of the use of an InputBox( ) function ...

name$ = InputBox("Please enter a name", "Friendly Farmacy")

If name$ = "Bart" Then MessageBox("Go away Bart")

Page 35: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 35 of 43

The For ... Next Loop

Normally programs flow along line by line (linear execution) in the order in which the line appears in your source code. The For .. Next statements enable you to repeat a block of code a set number of times (if you know exactly how many times you need to go through the loop). If you are uncertain how many time you want to go through the loop the use a While loop or a Do loop.

Simple For Loop:

"General Case" For Loop Sample For loop_counter = StartValue to EndValue statement; statement; Next loop_counter

WHERE:

• The For statement is the beginning of the loop • StartValue = the initial value of the loop counter • EndValue = the value that the loop counter must pass

to exit the loop • The Next statement is the end of the loop

example 1: For x = 1 to 10 y = x * 2 text1.text = y; Next x example 2: z = 12 For x = z to z+10 y = x * 2 text1.text = y; Next x

Complex For Loop:

"More Advanced" For Loop Sample For loop_counter = StartValue to EndValue Step stepValue statement; statement; Next loop_counter

WHERE:

• The For statement is the beginning of the loop • StartValue = the initial value of the loop counter • EndValue = the value that the loop counter must pass

to exit the loop • The stepValue (Optional) is the amount counter is

changed each time through the loop. If not specified, step defaults to one.

• The step argument (stepValue) can be either o positive (counter increases) o negative (counter decreases) o Loop executes if

example 1: For x = 10 to 100 Step 10 y = x * 2 text1.text = y; Next x example 2: For x = 1000 to 100 Step -100 y = x * 2 text1.text = y; Next x example 3: a = 3 b = 11 c = 2 For x = a to b Step c y = x * 2 text1.text = y; Next x

Page 36: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 36 of 43

Positive: counter <= end Negative: counter >= end

• The Next statement is the end of the loop

After all statements in the loop have executed, step is added to counter. At this point, either the statements in the loop execute again (based on the same test that caused the loop to execute initially), or the loop is exited and execution continues with the statement following the Next statement.

* If a Next statement is encountered before its corresponding For statement, an error occurs.

Nested loops:

You can put a loop inside of another loop in a structure called nested loops. This is done by placing one For...Next loop within another. Each loop MUST have a unique variable name as its loop counter.

Nested loop example:

For I = 1 To 10 For J = 1 To 10 For K = 1 To 10 statements ... Next K Next J Next I

* remember that nested loops must be bracketed in LIFO order. That means that the inner-most loop ends first and the outermost loop ends last.

Exiting loops Early (be careful how you use this):

If for some reason you need to exit a loop before it is finished, you may use the Exit For command.

example:

For i = 1 To 10 If Val(Text1.text) = 0 Then Exit For Text2.text = i * Val(text1.text) Next i

Page 37: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 37 of 43

The While ... Wend Loop

Normally programs flow along line by line (linear execution) in the order in which the line appears in your source code. The While .. Wend statements enable you to repeat a block of code an undetermined number of times (if you do not know exactly how many times you need to go through the loop).

The While Loop:

"General Case" While loop Sample While SomeConditionIsTrue statement; statement; Wend

WHERE:

• The While statement is the beginning of the loop • SomeConditionIsTrue = a logic comparison

that MUST be true in order to continue in the loop • The Wend statement is the end of the loop

example 1: x = 0 While x < 100 x = x + 2 text1.text = x; Wend example 2: x = 0 While x < 100 x = x + Val(text2.text) text1.text = x; Wend

* If a Wend statement is encountered before its corresponding While statement, an error occurs.

Nested loops:

You can put a loop inside of another loop in a structure called nested loops. This is done by placing one While...Wend loop within another.

Nested loop example:

I = 1 While I < 100 I=I+1 J=100 While J > 10 J = J - 1 K = I * J Text1.text=K Wend Wend

* remember that nested loops must be bracketed in LIFO order. That means that the inner-most loop ends first and the outermost loop ends last.

Page 38: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 38 of 43

The if Statement

Normally programs flow along line by line (linear execution) in the order in which it appears in your source code. The if statement enables you to compare two particular variables (objects) and jump (branch) to different parts of your code depending on the result of that comparison.

The simplest form of an if statement is this:

If expression Then statement; End if

The comparison expression found in the parentheses can be any expression at all, but it usually contains one of the relational expressions. If the expression has the value 0, it is considered false, and the statement is skipped.

Relational Expresion Meaning = equal to < less than

< = less than or equal > greater than

> = greater than or equal < > not equal to

Single Line Case:

General Case Sample If condition Then statement If mark >= 80 Then Label1.Caption = "Honour Roll"

Multiple Line Case:

General Case Sample If condition Then statement statement End If

If mark >= 80 Then Label1.Caption = "Honour Roll" Label2.Caption = "Good Work" End If

Page 39: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 39 of 43

If-Else Case:

General Case Sample If condition Then statement statement Else statement End If

If mark >= 80 Then Label1.Caption = "Honour Roll" Label2.Caption = "Good Work" Else Label1.Caption = "Not Honour Roll" Label2.Caption = "Try Harder" End If

If - Else If Case:

General Case Sample If condition Then statement statement ElseIf condition Then statement Else statement End If

If mark >= 80 Then Label1.Caption = "Honour Roll" Label2.Caption = "Good Work" ElseIf mark >= 70 Label1.Caption = "Not Honour Roll" Label2.Caption = "Nice Try" Else Label1.Caption = "Not Honour Roll" Label2.Caption = "Try Harder" End If

Compound Checking Conditions & Logic Operators:

Use The LOGIC involved Example of Use

And Both Conditions must be TRUE If (age >= 18) And (age <=65) Then Label1.Caption = "You are Hired"

Or Either Condition may be true If (age < 18) Or (age >65) Then Label1.Caption = "You NOT are Hired"

Not The result of the condition is reversed

If Not (name = "Bart") Then Label1.Caption = "You may go on the trip"

Xor Only one of Condition is true

** The AND operator binds more strongly than the OR operator just like the multiplication (*) operator takes precedence over the addition (+) operator. If you keep this in mind, it will help you to debug logic errors in your code.

Page 40: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 40 of 43

Files in Visual Basic

As a programmer (and as a user) you may be used to using the keyboard and the monitor for the input and output of information, but those devices are not the only way to input/output data. Most programming languages allow you to work with files. Files are an alternative way to do input and output using a faster and more permanent form of data storage, your floppy disk or hard drive.

It is important to realize that you are most often opening a file for one of either ...

• input (using the Input# statement) or • output (using the Print# statement)

Here is the general syntax for using files:

Open pathname For mode [Access access] [lock] As [#]filenumber [Len=reclength] (in here you need to use either an Input# statement or a Print# statement) ... Close [#]filenumber

where:

• pathname is a required string expression that specifies a file name - it may include directory or folder, and drive.

• mode is a required keyword specifying the file mode: Append, Binary, Input, Output, or Random.

• Access (Optional Keyword specifying the operations permitted on the open file: Read, Write, or Read Write)

• lock is an optional. keyword that specifies the operations permitted on the open file by other processes: Shared, Lock Read, Lock Write, and Lock Read Write.

• filenumber is a required parameter and must be a valid file number in the range 1 to 511. You may use the FreeFile function to obtain the next available file number.

• reclength is an optional parameter. It is a umber less than or equal to 32,767 (bytes). For files opened for random access, this value is the record length. For sequential files, this value is the number of characters buffered.

If the file is already opened by another process (like another program or another function) and the specified type of access is not allowed, the Open operation fails and an error occurs (you crash !).

Page 41: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 41 of 43

Opening a file for Input (Reading from a File)

Open "TESTFILE" For Input As #1 Input #1, somedata$ Close #1

... the Input#1 statement allows you to get data from an open file called "TESTFILE" (file #1) and put the data (from the file) into a variable called "somedata$".

Opening a NEW file for Output (Writing to a File)

Open "TESTFILE" For Output As #1 Print#1, somedata$ Close #1

... the Print#1 statement allows you to put data in to a file called "TESTFILE" (file #1). You get the data from a variable called "somedata$" and you write it to the file.

Opening an EXISTING file for Output (Writing to a File)

Open "TESTFILE" For Append As #1 Print#1, somedata$ Close #1

... the Print#1 statement allows you to put data in to a file called "TESTFILE" (file #1). You get the data from a variable called "somedata$". Here you are adding to the end of an existing file.

Samples that we tried in class Write to a file (output) Read from a file (input)

Dim X as String Open "h:TEST.TXT" For Output As #1 For i = 1 to 5 X = InputBox("Enter a word") Print#1, X Next i Close #1

Dim X as String Open "h:TEST.TXT" For Input As #1 For i = 1 to 5 Input#1, X MsgBox("The word is" & X) Next i Close #1

Page 42: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 42 of 43

File Controls (Selecting a file name)

There are three different controls (objects) that can be use together to select a file name.

• FileListBox (changes the file drive letter) • DirListBox (changes the file path) • FileListBox (changes which file is selected in the current path)

It is important to remember that all three of these components are independent of each other. You must link the three together in order to properly select a file name.

Using the Properties of each object toy can build a file name that you can then use VB code to open up and work on.

• For the FileListBox Object we will use the "Filename" property. • For the DirectoryListBox Object we will use the "Path" property. • For the DriveListBox Object we will use the "Drive" property.

Page 43: Introduction to Visual Basic - University of Windsorweb2.uwindsor.ca/courses/cs/dmayo/sss/ICS3U/IVB.pdf · Introduction to Visual Basic Visual Basic's Origins: The name BASIC is an

ICS 3M Computer & Information Science Visual Basic Additional Notes

Page 43 of 43

Here is some code to link all three objects together to get a file name in a textbox:

Private Sub Drive1_Change() Dir1.Path = Drive1.Drive End Sub Private Sub Dir1_Change() File1.Path = Dir1.Path End Sub Private Sub File1_Click() If Len(File1.Path) > 3 Then Text2.Text = Dir1.Path + "\" + File1.filename Else Text2.Text = Dir1.Path + File1.filename Endif End Sub