Learn Visual Basic 6.0 1. Introduction to the Visual Basic Language and Environment Preview " In this first class, we will do a quick overview of how to build an application in Visual Basic. You 9ll learn a new vocabulary, a new approach to programming, and ways to move around in the Visual Basic environment.
You will leave having written your first Visual Basic program. Course Objectives Ò Understand the benefits of using Microsoft Visual Basic 6.0 for Windows as an application tool Ò Understand the Visual Basic event-driven programming concepts, terminology, and available tools Ò Learn the fundamentals of designing, implementing, and distributing a Visual Basic application Ò Learn to use the Visual Basic toolbox Ò Learn to modify object properties Ò Learn object methods Ò Use the menu design window Ò Understand proper debugging and error-handling procedures Ò Gain a basic understanding of database access and management using databound controls Ò Obtain an introduction to ActiveX controls and the Windows Application Programming Interface (API) What is Visual Basic? " Visual Basic is a tool that allows you to develop Windows (Graphic User Interface - GUI ) applications.
The applications have a familiar appearance to the user. " Visual Basic is ... more. less.
event-driven , meaning code remains idle until called upon to respond to some event (button pressing, menu selection, ...). Visual Basic is governed by an event processor.<br><br> Nothing happens until an event is detected. Once an event is detected, the code corresponding to that event (event procedure) is executed. Program control is then returned to the event processor.<br><br> Event Procedures " Some Features of Visual Basic Ò Full set of objects - you 'draw' the application Ò Lots of icons and pictures for your use Ò Response to mouse and keyboard actions Ò Clipboard and printer access Ò Full array of mathematical, string handling, and graphics functions Ò Can handle fixed and dynamic variable and control arrays Ò Sequential and random access file support Ò Useful debugger and error-handling facilities Ò Powerful database access tools Ò ActiveX support Ò Package & Deployment Wizard makes distributing your applications simple Visual Basic 6.0 versus Other Versions of Visual Basic " The original Visual Basic for DOS and Visual Basic For Windows were introduced in 1991. " Visual Basic 3.0 (a vast improvement over previous versions) was released in 1993. " Visual Basic 4.0 released in late 1995 (added 32 bit application support).<br><br> " " Visual Basic 5.0 released in late 1996. New environment, supported creation of ActiveX controls, deleted 16 bit application support. " And, now Visual Basic 6.0 - some identified new features of Visual Basic 6.0: Ò Faster compiler Ò New ActiveX data control object Ò Allows database integration with wide variety of applications Ò New data report designer Ò New Package & Deployment Wizard Ò Additional internet capabilites Event?<br><br> Event processor Basic Code Basic Code Basic Code Control 1 Control 3 Control 2 Form 2 (.FRM) Control 1 Control 3 Control 2 Form 3 (.FRM) Module 1 (.BAS) 16 Bits versus 32 Bits " Applications built using the Visual Basic 3.0 and the 16 bit version of Visual Basic 4.0 will run under Windows 3.1, Windows for Workgroups, Windows NT, or Windows 95 " Applications built using the 32 bit version of Visual Basic 4.0, Visual Basic 5.0 and Visual Basic 6.0 will only run with Windows 95 or Windows NT (Version 3.5.1 or higher). " In this class, we will use Visual Basic 6.0 under Windows 95, recognizing such applications will not operate in 16 bit environments. Structure of a Visual Basic Application Project (.VBP, .MAK) Application (Project) is made up of: Ò Forms - Windows that you create for user interface Ò Controls - Graphical features drawn on forms to allow user interaction (text boxes, labels, scroll bars, command buttons, etc.) (Forms and Controls are objects .) Ò Properties - Every characteristic of a form or control is specified by a property.<br><br> Example properties include names, captions, size, color, position, and contents. Visual Basic applies default properties. You can change properties at design time or run time.<br><br> Ò Methods - Built-in procedure that can be invoked to impart some action to a particular object. Ò Event Procedures - Code related to some object. This is the code that is executed when a certain event occurs.<br><br> Ò General Procedures - Code not related to objects. This code must be invoked by the application. Ò Modules - Collection of general procedures, variable declarations, and constant definitions used by application.<br><br> Control 1 Control 3 Control 2 Form 1 (.FRM) Steps in Developing Application " There are three primary steps involved in building a Visual Basic application: 1. Draw the user interface 2. Assign properties to controls 3.<br><br> Attach code to controls We 9ll look at each step. Drawing the User Interface and Setting Properties Visual Basic operates in three modes. Ò Design mode - used to build application Ò Run mode - used to run the application Ò Break mode - application halted and debugger is available We focus here on the design mode.<br><br> Six windows appear when you start Visual Basic. Ò The Main Window consists of the title bar, menu bar, and toolbar. The title bar indicates the project name, the current Visual Basic operating mode, and the current form.<br><br> The menu bar has drop-down menus from which you control the operation of the Visual Basic environment. The toolbar has buttons that provide shortcuts to some of the menu options. The main window also shows the location of the current form relative to the upper left corner of the screen (measured in twips) and the width and length of the current form.<br><br> New form Add project Open project Save project Menu editor Properties window Code Editor Tasks Form Layout Run Pause Stop Project Explorer Object Browser Toolbox Form position Form dimensions Ò The Form Window is central to developing Visual Basic applications. It is where you draw your application. Ò The Toolbox is the selection menu for controls used in your application.<br><br> Ò The Properties Window is used to establish initial property values for objects. The drop-down box at the top of the window lists all objects in the current form. Two views are available: Alphabetic and Categorized.<br><br> Under this box are the available properties for the currently selected object. Pointer Label Frame Check Box Combo Box Horizontal Scroll Bar Timer Directory List Box Shapes Image Box Object Linking Embedding Picture Box Text Box Command Button Option Button List Box Vertical Scroll Bar Drive List Box File List Box Lines Data Tool Ò The Form Layout Window shows where (upon program execution) your form will be displayed relative to your monitor 9s screen: Ò The Project Window displays a list of all forms and modules making up your application. You can also obtain a view of the Form or Code windows (window containing the actual Basic coding) from the Project window.<br><br> " As mentioned, the user interface is 8drawn 9 in the form window. There are two ways to place controls on a form: 1. Double-click the tool in the toolbox and it is created with a default size on the form.<br><br> You can then move it or resize it. 2. Click the tool in the toolbox, then move the mouse pointer to the form window.<br><br> The cursor changes to a crosshair. Place the crosshair at the upper left corner of where you want the control to be, press the left mouse button and hold it down while dragging the cursor toward the lower right corner. When you release the mouse button, the control is drawn.<br><br> " To move a control you have drawn, click the object in the form window and drag it to the new location. Release the mouse button. " To resize a control, click the object so that it is select and sizing handles appear.<br><br> Use these handles to resize the object. Example 1-1 Stopwatch Application - Drawing Controls 1. Start a new project.<br><br> The idea of this project is to start a timer, then stop the timer and compute the elapsed time (in seconds). 2. Place three command buttons and six labels on the form.<br><br> Move and size the controls and form so it looks something like this: Click here to move object Use sizing handles to resize object Setting Properties of Objects at Design Time Each form and control has properties assigned to it by default when you start up a new project. There are two ways to display the properties of an object. The first way is to click on the object (form or control) in the form window.<br><br> Then, click on the Properties Window or the Properties Window button in the tool bar. The second way is to first click on the Properties Window. Then, select the object from the Object box in the Properties Window.<br><br> Shown is the Properties Window for the stopwatch application: The drop-down box at the top of the Properties Window is the Object box. It displays the name of each object in the application as well as its type. This display shows the Form object.<br><br> The Properties list is directly below this box. In this list, you can scroll through the list of properties for the selected object. You may select a property by clicking on it.<br><br> Properties can be changed by typing a new value or choosing from a list of predefined settings (available as a drop down list). Properties can be viewed in two ways: Alphabetic and Categorized . A very important property for each object is its name .<br><br> The name is used by Visual Basic to refer to a particular object in code. A convention has been established for naming Visual Basic objects. This convention is to use a three letter prefix (depending on the object) followed by a name you assign.<br><br> A few of the prefixes are (we 9ll see more as we progress in the class): Object Prefix Example Form frm frmWatch Command Button cmd, btn cmdExit, btnStart Label lbl lblStart, lblEnd Text Box txt txtTime, txtName Menu mnu mnuExit, mnuSave Check box chk chkChoice Object names can be up to 40 characters long, must start with a letter, must contain only letters, numbers, and the underscore (_) character. Names are used in setting properties at run time and also in establishing procedure names for object events. Setting Properties at Run Time You can also set or modify properties while your application is running.<br><br> To do this, you must write some code. The code format is: ObjectName.Property = NewValue Such a format is referred to as dot notation. For example, to change the BackColor property of a form name frmStart , we'd type: frmStart.BackColor = BLUE How Names are Used in Object Events The names you assign to objects are used by Visual Basic to set up a framework of event-driven procedures for you to add code to.<br><br> The format for each of these subroutines (all object procedures in Visual Basic are subroutines) is: Sub ObjectName_Event (Optional Arguments) . . End Sub Visual Basic provides the Sub line with its arguments (if any) and the End Sub statement.<br><br> You provide any needed code. Example 1-2 Stopwatch Application - Setting Properties 1. Set properties of the form, three buttons, and six labels: Form1 : BorderStyle 1-Fixed Single Caption Stopwatch Application Name frmStopWatch Command1 : Caption &Start Timing Name cmdStart Command2 : Caption &End Timing Name cmdEnd Command3 : Caption E&xit Name cmdExit Label1 : Caption Start Time Label2 : Caption End Time Label3 : Caption Elapsed Time Label4 : BorderStyle 1-Fixed Single Caption [Blank] Name lblStart Label5 : BorderStyle 1-Fixed Single Caption [Blank] Name lblEnd Label6 : BorderStyle 1-Fixed Single Caption [Blank] Name lblElapsed In the Caption properties of the three command buttons, notice the ampersand ( & ).<br><br> The ampersand precedes a button's access key . That is, in addition to clicking on a button to invoke its event, you can also press its access key (no need for a mouse). The access key is pressed in conjunction with the Alt key.<br><br> Hence, to invoke 'Begin Timing', you can either click the button or press Alt+B. Note in the button captions on the form, the access keys appear with an underscore (_). 2.<br><br> Your form should now look something like this: Variables " We 9re now ready to attach code to our application. As objects are added to the form, Visual Basic automatically builds a framework of all event procedures. We simply add code to the event procedures we want our application to respond to.<br><br> But before we do this, we need to discuss variables . " Variables are used by Visual Basic to hold information needed by your application. Rules used in naming variables: Ò No more than 40 characters Ò They may include letters, numbers, and underscore (_).<br><br> In specific, no spaces in variable names. Ò The first character must be a letter Ò You cannot use a reserved word (word needed by Visual Basic) Visual Basic Data Types Data Type Suffix Boolean None Integer % Long (Integer) & Single (Floating) ! Double (Floating) # Currency @ Date None Object None String $ Variant None Variable Declaration There are three ways for a variable to be typed (declared): 1.<br><br> Default 2. Implicit 3. Explicit If variables are not implicitly or explicitly typed, they are assigned the variant type by default .<br><br> The variant data type is a special type used by Visual Basic that can contain numeric, string, or date data. To implicitly type a variable, use the corresponding suffix shown above in the data type table. For example, TextValue$ = "This is a string" creates a string variable, while Amount% = 300 creates an integer variable.<br><br> There are many advantages to explicitly typing variables. Primarily, we insure all computations are properly done, mistyped variable names are easily spotted, and Visual Basic will take care of insuring consistency in upper and lower case letters used in variable names. Because of these advantages, and because it is good programming practice, we will explicitly type all variables.<br><br> To explicitly type a variable, you must first determine its scope . There are four levels of scope: Ò Procedure level Ò Procedure level, static Ò Form and module level Ò Global level Within a procedure, variables are declared using the Dim statement: Dim MyInt as Integer Dim MyDouble as Double Dim MyString, YourString as String Procedure level variables declared in this manner do not retain their value once a procedure terminates. To make a procedure level variable retain its value upon exiting the procedure, replace the Dim keyword with Static : Static MyInt as Integer Static MyDouble as Double Form (module) level variables retain their value and are available to all procedures within that form (module).<br><br> Form (module) level variables are declared in the declarations part of the general object in the form's (module's) code window. The Dim keyword is used: Dim MyInt as Integer Dim MyDate as Date Global level variables retain their value and are available to all procedures within an application. Module level variables are declared in the declarations part of the general object of a module's code window.<br><br> (It is advisable to keep all global variables in one module.) Use the Global keyword: Global MyInt as Integer Global MyDate as Date " What happens if you declare a variable with the same name in two or more places? More local variables shadow (are accessed in preference to) less local variables. For example, if a variable MyInt is defined as Global in a module and declared local in a routine MyRoutine, while in MyRoutine, the local value of MyInt is accessed.<br><br> Outside MyRoutine, the global value of MyInt is accessed. " Example of Variable Scope: Module1 Global X as Integer Form1 Form2 Dim Y as Integer Dim Z as Single Sub Routine1() Sub Routine3() Dim A as Double Dim C as String . .<br><br> . . End Sub End Sub Sub Routine2() Static B as Double .<br><br> . End Sub Procedure Routine1 has access to X, Y, and A (loses value upon termination) Procedure Routine2 has access to X, Y, and B (retains value) Procedure Routine3 has access to X, Z, and C (loses value) Example 1-3 Stopwatch Application - Attaching Code All that 9s left to do is attach code to the application. We write code for every event a response is needed for.<br><br> In this application, there are three such events: clicking on each of the command buttons. 1. Double-click anywhere on the form to open the code window.<br><br> Or, select 8View Code 9 from the project window. 2. Click the down arrow in the Object box and select the object named (general) .<br><br> The Procedure box will show (declarations) . Here, you declare three form level variables: Option Explicit Dim StartTime As Variant Dim EndTime As Variant Dim ElapsedTime As Variant The Option Explicit statement forces us to declare all variables. The other lines establish StartTime , EndTime , and ElapsedTime as variables global within the form.<br><br> 3. Select the cmdStart object in the Object box. If the procedure that appears is not the Click procedure, choose Click from the procedure box.<br><br> Type the following code which begins the timing procedure. Note the Sub and End Sub statements are provided for you: Sub cmdStart_Click () 8Establish and print starting time StartTime = Now lblStart.Caption = Format(StartTime, "hh:mm:ss") lblEnd.Caption = "" lblElapsed.Caption = "" End Sub In this procedure, once the Start Timing button is clicked, we read the current time and print it in a label box. We also blank out the other label boxes.<br><br> In the code above (and in all code in these notes), any line beginning with a single quote ( 8 ) is a comment. You decide whether you want to type these lines or not. They are not needed for proper application operation.<br><br> 4. Now, code the cmdEnd button. Sub cmdEnd_Click () 8Find the ending time, compute the elapsed time 8Put both values in label boxes EndTime = Now ElapsedTime = EndTime - StartTime lblEnd.Caption = Format(EndTime, "hh:mm:ss") lblElapsed.Caption = Format(ElapsedTime, "hh:mm:ss") End Sub Here, when the End Timing button is clicked, we read the current time ( End Time ), compute the elapsed time, and put both values in their corresponding label boxes.<br><br> 5. And, finally the cmdExit button. Sub cmdExit_Click () End End Sub This routine simply ends the application once the Exit button is clicked.<br><br> 6. Did you notice that as you typed in the code, Visual Basic does automatic syntax checking on what you type (if you made any mistakes, that is)? 7.<br><br> Run your application by clicking the Run button on the toolbar, or by pressing <f5>. Pretty easy, wasn 9t it? 8.<br><br> Save your application - see the Primer on the next page. Use the Save Project As option under the File menu. Make sure you save both the form and the project files.<br><br> 9. If you have the time, some other things you may try with the Stopwatch Application: A. Try changing the form color and the fonts used in the label boxes and command buttons.<br><br> B. Notice you can press the 8End Timing 9 button before the 8Start Timing 9 button. This shouldn 9t be so.<br><br> Change the application so you can 9t do this. And make it such that you can 9t press the 8Start Timing 9 until 8End Timing 9 has been pressed. Hint: Look at the command button Enabled property.<br><br> C. Can you think of how you can continuously display the 8End Time 9 and 8Elapsed Time 9? This is a little tricky because of the event-driven nature of Visual Basic.<br><br> Look at the Timer tool. Ask me for help on this one. Quick Primer on Saving Visual Basic Applications: When saving Visual Basic applications, you need to be concerned with saving both the forms (.FRM) and modules (.BAS) and the project file (.VBP).<br><br> In either case, make sure you are saving in the desired directory. The current directory is always displayed in the Save window. Use standard Windows techniques to change the current directory.<br><br> There are four Save commands available under the File menu in Visual Basic: Save [Form Name] Save the currently selected form or module with the current name. The selected file is identified in the Project window. Save [Form Name] As Like Save File, however you have the option to change the file name Save Project Saves all forms and modules in the current project using their current names and also saves the project file.<br><br> Save Project As Like Save Project, however you have the option to change file names. When you choose this option, if you have not saved your forms or modules, you will also be prompted to save those files. I always use this for new projects.<br><br> Exercise 1 Calendar/Time Display Design a window that displays the current month, day, and year. Also, display the current time, updating it every second (look into the Timer control). Make the window look something like a calendar page.<br><br> Play with object properties to make it pretty. My Solution: Form: Properties: lblDay lblTime timDisplay lblMonth lblNumber lblYear Form frmCalendar : Caption = My Calendar BorderStyle = 1 - Fixed Single Timer timDisplay : Interval = 1000 Label lblDay : Caption = Sunday FontName = Times New Roman FontBold = True FontSize = 24 Label lblTime : Caption = 00:00:00 PM FontName = Times New Roman FontBold = True FontSize = 24 Label lblYear : Alignment = 2 - Center Caption = 1998 FontName = Times New Roman FontBold = True FontSize = 24 Label lblNumber : Alignment = 2 - Center Caption = 31 FontName = Arial FontBold = True FontSize = 72 Label lblMonth : Alignment = 2 - Center Caption = March FontName = Times New Roman FontBold = True FontSize = 24 Code: General Declarations: Option Explicit timDisplay Timer Event: Private Sub timDisplay_Timer() Dim Today As Variant Today = Now lblDay.Caption = Format(Today, "dddd") lblMonth.Caption = Format(Today, "mmmm") lblYear.Caption = Format(Today, "yyyy") lblnumber.Caption = Format(Today, "d") lblTime.Caption = Format(Today, "h:mm:ss ampm") End Sub Making Decisions Y ou have seen that it is sometimes necessary to make a decision based on particular criteria. In the building exercise in Lesson 1, you had to decide if there was a door in front of you before you could tell what to do next.<br><br> In programming we call this kind of operation a branching structure. There are two kinds of main branching structures in most programming languages, If statements and Case statements. If Statements If statements allow you to take different courses of action depending on the results of a test or tests.<br><br> They generally follow the form below: If <test> then <result> else <other result> If there is more than one test to make, or if there are several things to do as the first or second result, it is better to use a block form of the If statement: If <test1> then result step 1 result step 2 Elseif <test2> Result Else Another result End If Test If Yes Instructions No Test 2 Instructions Yes No Instructions End Else If Else End If Figure 1 - If Then Flow Chart While the syntax may change a little depending on the language, nearly all languages have a block form of the If statement, and they are all very similar. As the code executes, each statement is evaluated. If a test is False, the execution skips to the next Else statement.<br><br> If the test is True, it executes the Result statements, and then goes to End If. Case Statements Case statements are used when there is only one testing criteria, but there may be many answers to the test. For instance, if you were testing for the color of a person 9s car, there may be several answers: red, blue, white, or any other color.<br><br> In a case statement, this would read something like this: Select Case CarColor 8check for the car color Case cred d 8if it is red do one thing 8follow this action Case cblue d 8if it is blue do another thing 8do this Case cwhite d 8if it is white do something else 8do this Case Else 8if it is any other color do yet another 8do this End Select Case 1 Yes Instructions No Case 2 Instructions Yes No End Test Expression Instructions Case Else Figure 2 - Case Flow Chart This handy structure is available in many languages, but not all of them. Because it is not as widely available, many programmers overlook it, even when it would really fit the bill. GoTo and GoSub Most languages also have some sort of statement that sends the course of execution to a line number or a line label.<br><br> GoSub sends the execution to a different procedure, and when that procedure is finished, execution resumes at the line after GoSub. In some languages, you simply enter the name of the other procedure without explicitly saying GoSub, or even Run. Generally, using a GoTo statement sends the program on a one-way trip to a different line in the same procedure or to a different procedure, and it never comes back.<br><br> (The one exception to that is in error handling, but that is beyond the scope of these exercises.) Of course, if you send the execution of a program to a line above the GoTo statement, it simply follows the sequence of the program, and then comes back to that line naturally. Some programming languages allow you to use a line number to send the program to, in others, you create a line label. These are simply names you give a line, like this: StartHere: If the program encounters a line that says: If <test> GoTo StartHere The test is evaluated, and if it is True, the execution skips to the line StartHere: and executes sequentially from that line.<br><br> Instructions End Start Here: If Condition is True Goto No Yes Instructions If Condition is True Goto No Start Here: If Condition is True Goto Yes No Instructions Yes If Condition is True Goto Yes Instructions No If Condition is True Goto No Yes End Pro er If Goto Loo S a hetti Code created with If Goto Instructions Figure 3 - GoTo Flow Charts Variables Variables are simply placeholders for information that your program uses temporarily. You give them a name, and assign a value to them. They may hold numbers, or strings (text), dates, currency, or Boolean values (True or False).<br><br> The type of information held in a variable is known as the data type. Variables can be declared explicitly, like this: Dim MyVariable as string MyVariable = cApril d Or they may be declared con the fly, d or implicitly: MyVariable = cApril d Implicitly declared variables can hold any data type, and the data type can change during code execution, but they take more memory and are not as efficient to use. Looping Loops come in two main varieties.<br><br> Do loops and For loops. Think of a loop as Do this and keep looping. A tongue-in-cheek dictionary definition is: Loop (n.) See Loop Do Loops The common syntax for a Do loop is: Do [While] [Until] <test> 8Use either While or Until instructions 8may be several lines Loop First you instruct the program to test for something, and either keep performing the same instructions while the test evaluates to True or until it is True.<br><br> The Loop statement after the instructions sends execution back to the test again. In this kind of looping structure, if the test is not True, no instructions are carried out at all. Sometimes you may want your instructions carried out once, whether or not the test is true.<br><br> In these cases you would want the instructions to precede the test like this: Do instructions Loop [While] [Until] <test> In either case, once the test proves False, execution falls out of the loop, and continues with the first statement after the loop. Instructions End Begin Do Loop Condition is True? No Yes Instructions End Condition is True?<br><br> Yes Loop No Begin Do Condition at Bottom of Loo Condition at To of Loo Figure 4 - Do Loop Flow Charts For Loops For loops allow you to execute a series of instructions a certain number of times. The general syntax is: For <variable> = <start number> to <end number> step <number> instructions Next <variable> Instructions End Yes For Initialize Counter to Start Is Counter > Sto Value No Increment Counter b Ste Value Figure 5 - For Next Flow Chart For loops work by counting the number of times to go through the loop. Each time through the loop, the variable takes on the value of the count.<br><br> There must be a start number and an end number; there may be a step number. If there is no step number, 1 is assumed. For example: For x = 2 to 10 step 2 print x Next x This would go through the loop five times.<br><br> The first time the value of x would be 2, then 4, then 6, then 8, and finally 10. It starts with 2, ends with 10 and, because we specified step 2, it skips every other number. Your start number can be greater than your end number, as long as the step is a negative.<br><br> Then the program counts down. In some languages, there are also For Each loops, in which you specify a collection of items, and execute instructions one time for each of the items in the collection. We will not go into the particulars about those here, but you should be aware that they exist Exit The Exit statement was designed for times when you need to break out of something without letting it complete a sequence of actions.<br><br> The syntax is like this: Exit <whatever> If you are in a subroutine, it is Exit Sub. If you are in a Do loop, it is Exit Do. In a For loop, it is Exit For.<br><br> Points to Remember " There is more than one way to program anything. Some may be more efficient than others, but if it works, it is right. " Most languages have the same control structures we have discussed here.<br><br> Once you know the logic behind programming, learning any new language is just a matter of learning a different syntax.