Visual Basic Concepts

Visual Studio 6.0 In order to understand the application development process, it is helpful to understand some of the key concepts upon which Visual Basic is built. Because Visual Basic is a Windows development language, some familiarity with the Windows environment is necessary. If you are new to Windows programming, you need to be aware of some fundamental differences between programming for Windows versus other environments.

How Windows Works: Windows, Events and Messages
A complete discussion of the inner workings of Windows would require an entire book. A deep understanding of all of the technical details isn't necessary. A simplified version of the workings of Windows involves three key concepts: windows, events and messages. Think of a window as simply a rectangular region with its own boundaries. You are probably already aware of several different types of windows: an Explorer window in Windows, a document window within your word processing program, or a dialog box that pops up to remind you of an appointment. While these are the most common examples, there are actually many other types of windows. A command button is a window. Icons, text boxes, option buttons and menu bars are all windows. The Microsoft Windows operating system manages all of these many windows by assigning each one a unique id number (window handle or hWnd). The system continually monitors each of these windows for signs of activity or events. Events can occur through user actions such as a mouse click or a key press, through programmatic control, or even as a result of another window's actions. Each time an event occurs, it causes a message to be sent to the operating system. The system processes the message and broadcasts it to the other windows. Each window can then take the appropriate action based on its own instructions for dealing with that particular message (for example, repainting itself when it has been uncovered by another window). As you might imagine, dealing with all of the possible combinations of windows, events and messages could be mind-boggling. Fortunately, Visual Basic insulates you from having to deal with all of the low-level message handling. Many of the messages are handled automatically by Visual Basic; others are exposed as Event procedures for your convenience. This allows you to quickly create powerful applications without having to deal with unnecessary details.

Understanding the Event-Driven Model
In traditional or "procedural" applications, the application itself controls which portions of code execute and in what sequence. Execution starts with the first line of code and follows a predefined path through the application, calling procedures as needed. In an event-driven application, the code doesn't follow a predetermined path ³ it executes different code sections in response to events. Events can be triggered by the user's actions, by messages from the system or other applications, or even from the application itself. The sequence of these events determines the sequence in which the code executes, thus the path through the application's code differs each time the program runs.

Because you can't predict the sequence of events, your code must make certain assumptions about the "state of the world" when it executes. When you make assumptions (for example, that an entry field must contain a value before running a procedure to process that value), you should structure your application in such a way as to make sure that the assumption will always be valid (for example, disabling the command button that starts the procedure until the entry field contains a value). Your code can also trigger events during execution. For example, programmatically changing the text in a text box cause the text box's Change event to occur. This would cause the code (if any) contained in the Change event to execute. If you assumed that this event would only be triggered by user interaction, you might see unexpected results. It is for this reason that it is important to understand the event-driven model and keep it in mind when designing your application.

Interactive Development
The traditional application development process can be broken into three distinct steps: writing, compiling, and testing code. Unlike traditional languages, Visual Basic uses an interactive approach to development, blurring the distinction between the three steps. With most languages, if you make a mistake in writing your code, the error is caught by the compiler when you start to compile your application. You must then find and fix the error and begin the compile cycle again, repeating the process for each error found. Visual Basic interprets your code as you enter it, catching and highlighting most syntax or spelling errors on the fly. It's almost like having an expert watching over your shoulder as you enter your code. In addition to catching errors on the fly, Visual Basic also partially compiles the code as it is entered. When you are ready to run and test your application, there is only a brief delay to finish compiling. If the compiler finds an error, it is highlighted in your code. You can fix the error and continue compiling without having to start over. Because of the interactive nature of Visual Basic, you'll find yourself running your application frequently as you develop it. This way you can test the effects of your code as you work rather than waiting to compile later.

Integrated Development Environment Elements
The Visual Basic integrated development environment (IDE) consists of the following elements.

Menu Bar
Displays the commands you use to work with Visual Basic. Besides the standard File, Edit, View, Window, and Help menus, menus are provided to access functions specific to programming such as Project, Format, or Debug.

Context Menus
Contain shortcuts to frequently performed actions. To open a context menu, click the right mouse button on the object you're using. The specific list of shortcuts available from context menus depends on the part of the

environment where you click the right mouse button. For example, the context menu displayed when you right click on the Toolbox lets you display the Components dialog box, hide the Toolbox, dock or undock the Toolbox, or add a custom tab to the Toolbox.

Toolbars
Provide quick access to commonly used commands in the programming environment. You click a button on the toolbar once to carry out the action represented by that button. By default, the Standard toolbar is displayed when you start Visual Basic. Additional toolbars for editing, form design, and debugging can be toggled on or off from the Toolbars command on the View menu. Toolbars can be docked beneath the menu bar or can "float" if you select the vertical bar on the left edge and drag it away from the menu bar.

Toolbox
Provides a set of tools that you use at design time to place controls on a form. In addition to the default toolbox layout, you can create your own custom layouts by selecting Add Tab from the context menu and adding controls to the resulting tab. For More Information To learn more about specific controls, see "Forms, Controls, and Menus" and "Using Visual Basic's Standard Controls." For information on how to add controls to the Toolbox, see "Adding Controls to a Project" in "Managing Projects."

Project Explorer Window
Lists the forms and modules in your current project. A project is the collection of files you use to build an application. For More Information For information on projects, see "Managing Projects."

Properties Window
Lists the property settings for the selected form or control. A property is a characteristic of an object, such as size, caption, or color. For More Information For information on properties, see "Understanding Properties, Methods, and Events" in "Forms, Controls, and Menus."

Object Browser
Lists objects available for use in your project and gives you a quick way to navigate through your code. You can use the Object Browser to explore objects in Visual Basic and other applications, see what methods and properties are available for those objects, and paste code procedures into your application.

Figure 2. Each form in your application has its own form designer window. can provide features like source code control. You add controls. graphics. see "Your First Visual Basic Application" later in this chapter. Locals. and pictures to a form to create the look you want. Add-ins.2 The Form Layout window Immediate. see "Using Wizards and Add-ins" in "Managing Projects. which allows you to support group development projects. which are available from Microsoft and third-party developers." Note You can also add features to the Visual Basic interface by using a program called an add-in. see "Debugging Your Code and Handling Errors." Code Editor Window Serves as an editor for entering application code. A separate code editor window is created for each form or code module in your application." Form Designer Serves as a window that you customize to design the interface of your application. see "Finding Out About Objects" in "Programming with Objects. They are only available when you are running your application within the IDE." For details on using add-ins to extend the Visual Basic programming environment.2) allows you to position the forms in your application using a small graphical representation of the screen. For More Information To learn more about entering code and using the code editor. For More Information To learn more about debugging and using the debug windows.For More Information For more information on using the Object Browser to view procedures. To learn more about designing an interface. see "Programming Fundamentals. ." Form Layout Window The Form Layout window (Figure 2. and Watch Windows These additional windows are provided for use in debugging your application. For More Information To learn how to add controls to an application. see "Creating a User Interface.

0 Environment Options Visual Basic provides a great deal of flexibility. allowing you to configure the working environment to best suit your individual style. Check or uncheck the SDI Development Environment check box. These include the Toolbox. Docking capabilities can be toggled on or off for a given window by selecting the appropriate check box on the Docking tab of the Options dialog box. windows can be docked to any side of the parent window. ²or² Run Visual Basic from the command line with a /sdi or /mdi parameter. they will remain on top of any other applications. as long as Visual Basic is the current application. and Immediate. to each other or to the edge of the screen. The Options dialog box is displayed. all of the IDE windows are contained within a single resizable parent window. Properties window. . Project Explorer. With the MDI option. 2. Docking Windows Many of the windows in the IDE can be docked.Visual Basic Concepts Visual Studio 6. You can choose between a single or multiple document interface. Locals. Your layout will persist between sessions of Visual Basic. or connected. With the MDI option. with SDI they can only be docked beneath the menu bar. 3. Select Options from the Tools menu. With the SDI option. available from the Options command on the Tools menu. Form Layout Window. Color Palette. Select the Advanced tab. To switch between SDI and MDI modes 1. all of the IDE windows are free to be moved anywhere on screen. The IDE will start in the selected mode the next time you start Visual Basic. and Watch windows. SDI or MDI Interface Two different styles are available for the Visual Basic IDE: single document interface (SDI) or multiple document interface (MDI). and you can adjust the size and positioning of the various Integrated Development Environment (IDE) elements.

Set properties. 3. Visual Basic Concepts Visual Studio 6. When you click the command button. 2. 2. You can use forms to add windows and dialog boxes to your application. the message "Hello. Select the window you wish to dock or undock. world!" appears in the text box. You can also use them as containers for items that are not a visible part of the application's interface.0 Hello. 4. To see how this is done. use the steps in the following procedures to create a simple application that consists of a text box and a command button. The first step in building a Visual Basic application is to create the forms that will be the basis for your application's interface. Button Control . you'll use two controls from the Toolbox. For this first application. Creating the Interface Forms are the foundation for creating the interface of an application. Write code.To dock or undock a window 1. For example. you might have a form in your application that serves as a container for graphics that you plan to display in other forms. 3. Release the mouse button. Then you draw the objects that make up the interface on the forms you create. Create the interface. Drag the window to the desired location by holding down the left mouse button. The outline of the window will be displayed as you drag. Visual Basic There are three main steps to creating an application in Visual Basic: 1.

Move the pointer onto your form. 2.3. Figure 2. .Text box Command button To draw a control using the Toolbox 1. The control appears on the form. Place the cross hair where you want the upper-left corner of the control. as shown in Figure 2.) Release the mouse button. (Dragging means holding the left mouse button down while you move an object with the mouse. Click the tool for the control you choose to draw ³ in this case. the text box. The pointer becomes a cross hair. 5. then you can move the control to another location on the form. Drag the cross hair until the control is the size you want. 4. Another simple way to add a control to a form is to double-click the button for that control in the Toolbox. This creates a default-size control located in the center of the form.3 Drawing a text box with the Toolbox 3.

²or² Use the Properties window to change the Top and Left properties. To adjust the position of locked controls . When a control is selected. you can use CTRL with the arrow keys to move the control one grid unit at a time. This will lock controls only on the selected form. ²or² Use SHIFT with the arrow keys to resize the selected control. You can also use the mouse. This is a toggle command. 3. The corner handles resize controls horizontally and vertically. while the side handles resize in only one direction. To resize a control 1. Position the mouse pointer on a sizing handle.Resizing. 2. keyboard. and menu commands to move controls. To move a control y Use the mouse to drag the control to a new location on the form. and adjust their positions. Sizing handles appear on the control. and Locking Controls Notice that small rectangular boxes called sizing handles appear at the corners of the control. Select the control you intend to resize by clicking it with the mouse. This will lock all controls on the form in their current positions so that you don't inadvertently move them once you have them in the desired location. and drag it until the control is the size you choose. If the grid is turned off. Moving. you'll use these sizing handles in the next step as you resize the control. Release the mouse button. lock and unlock control positions. the control moves one pixel at a time. To lock all control positions y From the Format menu. so you can also use it to unlock control positions. choose Lock Controls. ²or² Click the Lock Controls Toggle button on the Form Editor toolbar. controls on other forms are untouched.

click the Properties Window button on the toolbar. or position. fonts.5 The Properties window The Properties window consists of the following elements: y Object box ³ Displays the name of the object for which you can set properties. Sort tabs ³ Choose between an alphabetic listing of properties or a hierarchical view divided by logical categories. To open the Properties window. You can edit and view settings in the right column. y y To set properties from the Properties window . You now have the interface for the "Hello.5) provides an easy way to set properties for all objects on a form. world!" application. world!" application Setting Properties The next step is to set properties for the objects you've created. Figure 2.y You can "nudge" the control that has the focus by holding CTRL down and pressing the appropriate arrow key. The Properties window (Figure 2. or use the context menu for the control. ²or² You can change the control's Top and Left properties in the Property window.4 The interface for the "Hello. Click the arrow to the right of the object box to display the list of objects for the current form. Properties list ³ The left column displays all of the properties for the selected object. Figure 2. choose the Properties Window command from the View menu.4. such as those dealing with appearance. as shown in Figure 2.

In the right column. or click the Properties button on the toolbar. world!" example. set the Icon property for that form. default icon that appears when you minimize that form. select the name of a form or module. Enumerated properties have a predefined list of settings. you will probably change this icon to one that illustrates the use of the form or your application. From the View menu. Use the default settings for all other properties. To open the Code window y Double-click the form or control for which you choose to write code. You can use 32 x 32 pixel icons that were standard in 16-bit versions of Microsoft Windows and are also used in Windows 95/98 and Windows NT. you'll need to change three property settings. From the Properties list. To assign an icon to a form. world! (Empty) OK Setting the Icon Property All forms in Visual Basic have a generic. constants. You can display the list by clicking the down arrow at the right of the Settings box. . ²or² From the Project Explorer window. and choose the View Code button. Using the Code Editor window. choose Properties. The Properties window displays the settings for the selected form or control. For the "Hello. Writing Code The Code Editor window is where you write Visual Basic code for your application. as well as the 16 x 16 pixel icons used in Windows 95/98. and declarations. you can quickly view and edit any of the code in your application. Code consists of language statements. or you can cycle through the list by double-clicking a list item. However. Object Form Text box Command button Property Caption Text Caption Setting Hello. select the name of a property.1. 3. 2. type or select the new property setting.

²or² Click the Procedure View button in the lower left corner of the Code Editor window. From the Tools menu. 2. Click.6 The Code Editor window You can choose to display all procedures in the same Code window.Figure 2. select the Options dialog box. select the Options dialog box. 2. Click the arrow to the right of the list box to display a list of all objects associated with the form. The check box to the left of Procedure Separator adds or removes a separator line between procedures. On the Editor tab in the Options dialog box. Figure 2. or display a single procedure at a time. To display all procedures in the same Code window 1. clear the check box to the left of Default to Full Module View.6 shows the Code Editor window that appears when you double-click the Command button control. The box displays the name of the selected procedure ³ in this case. y . From the Tools menu. and the events for that command. ²or² Click the Full Module View button in the lower left corner of the Code Editor window. Procedure list box ³ Lists the procedures. for an object. To display one procedure at a time in the Code window 1. Choose the arrow to the right of the box to display all the procedures for the object. or events. On the Editor tab in the Options dialog box. select the check box to the left of Default to Full Module View. The Code window includes the following elements: y Object list box ³ Displays the name of the selected object.

use the procedure Command1_Click. where Text1 is the object and Text is the property. select the name of an event for the selected object.Text = "Hello. For More Information For information on creating other types of procedures.) For this example. or click the Start button on the toolbar. such as those you'll create here. world!" displayed in the text box. an underscore (_). Click the command button you've created on the form. world!" The event procedure should look like this: Private Sub Command1_Click () Text1. (The active form is the form that currently has the focus. see "Introduction to Procedures" in "Programming Fundamentals. select the name of an object in the active form. Here.property. because it's the default procedure for a command button. To create an event procedure 1. Note that a template for the event procedure is now displayed in the Code window. Command1. contains code that is executed when an event occurs (such as when a user clicks a button). if you want a command button named Command1 to invoke an event procedure when it is clicked. 2. In the Object list box. the Click procedure is already selected.Creating Event Procedures Code in a Visual Basic application is divided into smaller blocks called procedures. You can use this syntax to change property settings for any form or control in response to events that occur while your application is running. and the event name. . Text1. An event procedure for a control combines the control's actual name (specified in the Name property). choose Start from the Run menu.Text = "Hello. and you'll see "Hello. world!" End Sub You'll note here that the code is simply changing the Text property of the control named Text1 to read "Hello. 3. world!" The syntax for this example takes the form of object. For example. Type the following code between the Sub and End Sub statements: 4. An event procedure. or press F5. choose the command button. In the Procedure list box." Running the Application To run the application.

The following example illustrates how easy it can be to create a useful application in Visual Basic. in this case a ListBox object. you use a data control. To add items to the list box. so you'll need to add it: To add a control to the toolbox 1. The MSFlexGrid control isn't in the default toolbox. . a list box control. The AddItem method allows you to dynamically add items to the list box while the application is running." Creating a Project You begin creating this application by choosing New Project from the File menu. Controls. and Menus. and two command buttons. The grid displays a table of information about products retrieved from the Northwind database. Methods. 2. a list box control. Conversely. As the user selects an item by using the navigation buttons on the data control. a MSFlexGrid control. so you'll soon use many other features to manage and customize your applications. To draw the interface.property). then selecting Standard EXE in the New Project dialog box (when you first start Visual Basic. The data control provides the ability to navigate through the database recordset. Select Components from the context menu for the toolbox. the New Project dialog box is presented). synchronizing the display of records in the grid control with the position in the recordset. For More Information To learn more about methods.0) in the Controls list box and select the check box to its left. (A method is a Visual Basic function that acts on a particular object. the Clear method is used to remove all items from the list box.0 The Firstapp Sample Application Visual Basic provides you with a wealth of tools beyond the ones used in this first application. see "Understanding Properties. the name of the selected product is displayed in the data control. The Firstapp application demonstrates how a data control and a grid control can be used to display a table of information from a database. The user can also add items to a "shopping list" in the list box control by doubleclicking the current selection in the grid. Find the MSFlexGrid (Microsoft Flex Grid 6. and Events" in "Forms.method) is similar to the syntax for setting a property (object. Reviewing sample applications can be an excellent way to learn more about Visual Basic. (You can right-click within the toolbox window to display the context menu. Visual Basic creates a new project and displays a new form.) The Components dialog box will be displayed. The application consists of a data control.Visual Basic Concepts Visual Studio 6. and two command buttons. you use the AddItem method. a MSFlexGrid control.) The syntax for specifying a method (object. Visual Basic makes it easy to access database information from within your application.

Clear ' Clears the list box. set properties for the objects according to the following table. If you don't remember how. Data1_Reposition. . Use the default settings for all other properties. you can click the button to the right of the property to display a standard File Open dialog box to browse for the file. Setting Properties In the Properties window. By default.3. The icon for the MSFlexGrid control will appear in the toolbox. Double-click the form or control to display the Code window.mdb database is installed in the same directory as Visual Basic. Writing Event Code All the code for the application is contained in the Command1_Click. Use the Toolbox to draw a data control.mdb Products Data1 Clear Exit The DatabaseName property of the data control must include the actual path to the database. a list box control. the RecordSource property in the Properties window will contain a list of tables or recordsets for the selected database. List1. check out "Creating the Interface" earlier in this chapter. the Nwind. an MSFlexGrid control. you are invoking the Clear method of the list box. and then type the code for each event procedure. Once the DatabaseName property has been set. Command2_Click. Add this code to the Command1_Click event procedure to clear the list box when the user clicks the button: Private Sub Command1_Click () List1. Click the OK button. Setting the DataSource property of the MSFlexGrid control to Data1 automatically links the grid to the data control. When you select the DatabaseName property in the Properties window. and MSFlexGrid1_DblClick event procedures. End Sub In the above statement. and two command buttons on the form. Object Form Data1 Property Caption DatabaseName RecordSource MSFlexGrid1 Command1 Command2 DataSource Caption Caption Setting Products path \Nwind. The Clear method deletes the contents of the list box.

the first statement invokes the Unload event for the form. One possible name for the project is "Northwind Shopping List. As you .AddItem MSFlexGrid1. Saving a Project You finish your work on the application by choosing Save Project from the File menu. the value of the title field in the recordset of the data control. You can use this application as a basis for adding similar functionality in your own applications. Add this code to the Data1_Reposition event procedure to update the caption each time a record is selected: Private Sub Data1_Reposition () Data1. The text to be added to the list box is contained in the argument of the method.Recordset("ProductName") End Sub In the above statement. Add this code to the MSFlexGrid_DblClick event procedure to add an item to the list box when the user doubleclicks a selected row: Private Sub MSFlexGrid1_DblClick () List1.mdb. Older versions of Microsoft Windows limited you to file names of eight characters. Of course.Text End Sub In the above statement.Caption = Data1. Enhancing Your Application You have just completed your first Visual Basic application: one that performs a simple but useful function. substituting your own data instead of Nwind. The second statement calls the End function." Windows 95.Add this code to the Command2_Click event procedure to unload the form from memory and end the application: Private Sub Command2_Click () Unload Form1 End ' Ends application. which ends the application. such as saving a file. Visual Basic will prompt you separately to save the form and then the project. End Sub In the above procedure. to add additional information such as price and availability. with a three-character extension. If you needed to perform a function at shutdown. you could place that code in the form's Unload event procedure. in this case. and even to gather credit card information and transmit an order across the Internet. to make this application truly useful. Passing a value to an argument is similar to assigning a value to a property. and file names can include spaces. you might want to add functionality to save or print the contents of the list box. you are assigning the value on the right (the contents of the Title field in the Recordset of the data control) to the property on the left (the Caption property of the data control object). the equal sign isn't required. and Windows NT allow you to use file names up to 255 characters in length. you are invoking the AddItem method of the list box (List1). Windows 98. unlike the assignment statement.

all balloons are capable of these methods. or to the event of being released by rising into the air. methods. methods and events. you will find examples of doing all that and a lot more. Other controls let you access other applications and process data as if the remote application was part of your code. and events which define their interaction with the user. you customize the object to meet the requirements of your application. A balloon's properties include visible attributes such as its height. and events as its responses. they are the objects that you will work with to build your application. the visual part of the application with which the user will interact. Properties can be thought of as an object's attributes. An everyday object like a child's helium balloon also has properties. a balloon would respond to the event of being punctured by deflating itself. as well as form-specific items such as menus and dialog boxes. For instance. methods and events. and Menus The first step to creating an application with Visual Basic is to create the interface. By setting the properties of the form and writing Visual Basic code to respond to its events. and events. methods as its actions. Other properties describe its state (inflated or not inflated). This chapter introduces the basic concepts of working with forms and controls and their associated properties. Again. the settings of these properties may differ from one balloon to another. diameter and color. . Controls. Controls are objects that are contained within form objects. Visual Studio 6. Many of the standard controls are discussed. Forms and controls are the basic building blocks used to create the interface. all balloons have these properties. or attributes that aren't visible such as its age. Forms are objects that expose properties which define their appearance. methods which define their behavior. Understanding Properties. By definition. Each type of control has its own set of properties. It has an inflate method (the action of filling it with helium). Methods and Events Visual Basic forms and controls are objects which expose their own properties.continue on through the rest of the Programmer's Guide. Some of the controls you can use in your applications are best suited for entering or displaying text.0 Forms. Balloons also have predefined responses to certain external events. methods and events that make it suitable for a particular purpose. a deflate method (expelling its contents) and a rise method (if you were to let go of it). A balloon also has inherent methods or actions that it might perform.

1 Objects have properties.Color) followed by the assignment of the value (Red). While you can't actually program a balloon. and perform methods If you were able to program a balloon. you can program a Visual Basic form or control. you are in control. which denotes the distance to rise.Figure 3. then invoke the MakeNoise method with an argument of "Bang" (the type of noise to make). the code describes the balloon's behavior when a puncture event occurs: invoke the Deflate method. Properties can also be set in the Properties window while you are designing your application. respond to events.Rise 5 The syntax is similar to the property ³ the object (a noun) followed by the method (a verb). You decide which properties should be changed. The balloon might respond to an event as follows: Sub Balloon_Puncture() Balloon.Diameter = 1 End Sub In this case.Inflated = False Balloon. To set the balloon's properties: Balloon. called an argument. A balloon's methods are invoked like this: Balloon.MakeNoise "Bang" Balloon. You could change the color of the balloon from code by repeating this statement and substituting a different value.Inflated = True Note the syntax of the code ³ the object (Balloon) followed by the property (.Diameter = 10 Balloon. the Inflated property is set to False and the Diameter property is set to a new value. there is an additional item. Since the balloon is no longer inflated.Color = Red Balloon.Inflate Balloon. As the programmer. Some methods will have one or more arguments to further describe the action to be performed. the Visual Basic code might look like the following. methods invoked or events responded to in order to achieve the desired appearance and behavior. In the third example.Deflate Balloon. .Deflate Balloon.

Run time is any time you are actually running the application and interacting with the application as the user would. Left and Top properties determine the form's location in relation to the upper left-hand corner of the screen. minimized. You can learn more about each property by selecting it and pressing F1 to view the context-sensitive Help.2 Forms and controls have their own properties. You can set a form's properties at design time in the Properties window. and methods with which you can control their appearance and behavior.0 Designing a Form Form objects are the basic building blocks of a Visual Basic application. Forms have their own properties. the Icon property sets the icon that is displayed when a form is minimized. The Name property sets the name by which you will refer to the form in code. events. or at run time by writing code. Form2. Height and Width properties determine the initial size of a form. its name is set to Form1. Change some of the properties of a form in the Properties window (Figure 3. Figure 3. The MaxButton and MinButton properties determine whether the form can be maximized or minimized. Figure 3. The Caption property determines the text that is shown in the form's title bar. and write code for their events at design time. or normal state. By default. Note You work with forms and controls. By changing the BorderStyle property. when a form is first added to a project. such as "frmEntry" for an order entry form. events. The best way to familiarize yourself with the many form properties is to experiment. which is any time you're building an application in the Visual Basic environment. The WindowState property can be set to start the form in a maximized.Visual Studio 6.3). you can control the resizing behavior of the form. and methods The first step in designing a form is to set its properties. the actual windows with which a user interacts when they run the application. It's a good idea to set the Name property to something more meaningful. and so forth. Setting Form Properties Many of a form's properties affect its physical appearance. set their properties. then run the application to see their effect.3 The Properties window .

Form Events and Methods As objects. forms can perform methods and respond to events. These methods and more are discussed in "Working with Text and Graphics. see "More About Forms" in "Creating a User Interface. For example. Many of a form's methods involve text or graphics. The Activate event occurs whenever a form becomes the active form." For More Information For additional information on forms. or you can create your own "button" using an image control containing a graphic. in the Deactivate event you might save changes to a file or database. such as an icon. Circle.0 Clicking Buttons to Perform Actions The easiest way to allow the user to interact with an application is to provide a button to click. To make a form visible. Using Command Buttons .Show Invoking the Show method has the same effect as setting a form's Visible property to True. you would invoke the Show method: Form2. The Print. Line. These events are convenient for initializing or finalizing the form's behavior. the Deactivate event occurs when another form or application becomes active. This allows you to perform actions such as moving or resizing controls on a form when its dimensions have changed. either by user interaction or through code. in the Activate event you might write code to highlight the text in a particular text box. and Refresh methods are useful for printing or drawing directly onto a form's surface. The Resize event of a form is triggered whenever a form is resized." Visual Basic Concepts Visual Studio 6. You can use the command button control provided by Visual Basic.

Most Visual Basic applications have command buttons that allow the user to simply click them to perform actions. even if you change the focus to a different control other than a command button. it not only carries out the appropriate action. Change &Signal).vbp sample application. it also looks as if it's being pushed in and released. pressing ENTER chooses the button. At design time. When the user chooses the button. you specify a default command button by setting that button's Default property to True. If the command button is the default Cancel button for the form. and then choose the button by pressing the SPACEBAR or ENTER. (See "Understanding Focus" later in this chapter. Whenever the user clicks a button. the Test Buttons example from the Controls sample application contains a command button with its Caption property set to "Change Signal. You place code in the Click event procedure to perform any action you choose. Figure 3. see Button. Set the command button's Value property to True in code: y y y y y y cmdClose.) Press an access key (ALT+ the underlined letter) for a command button. the Click event procedure is invoked. There are many ways to choose a command button at run time: y y Use a mouse to click the button. you specify a default Cancel button by setting that button's Cancel property to True. In Figure 3.) Notice that 'S' is the access key for this button. denoted by an underline. Inserting an ampersand (&) in the text of the Caption property makes the character following it the access key for that button (for example. y All these actions cause Visual Basic to invoke the Click event procedure.4 Command button with a caption ." (For a working version of this example.frm in the Controls. then pressing ESC chooses the button. even if you change the focus to another control.4. Move the focus to the button by pressing the TAB key. The Test Buttons Application You use the Caption property to display text on the button to tell the user what the button does.Value = True Invoke the command button's Click event in code: cmdClose_Click If the command button is the default command button for the form. At design time.

The actual text displayed in a label is controlled by the Caption property. if you set the BorderStyle property to 1 (which you can do at design time). the caption is the only visible part of the label control. Labels contain text that can only be read. To provide this feature Text that can be edited by the user. Sizing a Label to Fit Its Contents . You can use labels to identify controls. see "Using Visual Basic's Standard Controls. the label appears with a border ³ giving it a look similar to a text box. for example to identify a field on a form or display instructions to the user Label Use this control Text box Labels and text boxes are discussed in the following sections: Using Labels to Display Text A label control displays text that the user cannot directly change. which can be set at design time in the Properties window or at run time by assigning it in code. such as text boxes and scroll bars. Use labels when you want your application to display text on a form. and text boxes when you want to allow the user to enter text. For More Information For information on additional properties of the command button. that do not have their own Caption property." Controls for Displaying and Entering Text Label and text box controls are used to display or enter text. while text boxes contain text that can be edited. By default. for example an order entry field or a password box Text that is displayed only. BackStyle. a different traffic light icon is displayed each time the button is clicked. In the example. You can also change the appearance of the label by setting the BackColor. However. the code in the command button's Click event procedure is executed. and Font properties.When a user clicks the command button. ForeColor.

as shown in Figure 3. AutoSize must be set to True.6. Figure 3.frm in the Controls. as shown in Figure 3. while retaining the same width. you'll notice that for the WordWrap example to actually work. For More Information For additional information on the label control's properties. For a working version of this example. But what if you want to enter a longer caption. see Wordwrap. If set to True. The width of the label is increased only if the width of a single word exceeds the current width of the control.5. unless you've set the Locked property to True. Text boxes should not be used to display text that you don't want the user to change. for the label's WordWrap property to take effect. The AutoSize property determines if a control should be automatically resized to fit its contents. see "Using Visual Basic's Standard Controls. both check boxes must be selected. Figure 3.5 AutoSize example The WordWrap property causes the label to grow vertically to fit its contents.Single-line label captions can be specified at design time in the Properties window. the label grows horizontally to fit its contents. .vbp.6 WordWrap example Note If you run the AutoSize example from Controls. or a caption that will change at run time? Labels have two properties that help you size the controls to fit larger or smaller captions: AutoSize and WordWrap." Working with Text Boxes Text boxes are versatile controls that can be used to get input from the user or to display text.vbp sample application. This is because.

Note The ScrollBars property should not be confused with scroll bar controls. For example. MultiLine and ScrollBars. The SelStart and SelLength properties allow you to modify the behavior to suit your purpose. A multipleline text box automatically manages word wrap as long as there is no horizontal scroll bar.7 Insertion point example . In some cases.Text = "Here are two lines" _ & vbCrLf & "in a text box" End Sub Working with Text in a Text Box You can control the insertion point and selection behavior in a text box with the SelStart. a text box displays a single line of text and does not display scroll bars. In a word processing application. the default insertion point or cursor position within the text box is to the left of any existing text.The actual text displayed in a text box is controlled by the Text property.7. If the text box loses and then regains the focus. which are available only at design time. Multiple-Line Text Boxes and Word Wrap By default. When a line of text is longer than what can be displayed on a line. only part of the text will be visible. SelLength and SelText properties. Line breaks cannot be entered in the Properties window at design time. If the SelStart property is set to a value equal to or greater than the number of characters in the text box.frm in the Controls. If the text is longer than the available space. which are not attached to text boxes and have their own set of properties. When a text box first receives the focus. the following event procedure puts two lines of text into a multiple-line text box (Text1) when the form is loaded: Sub Form_Load () Text1. the user might expect new characters to appear after any existing text. with 0 being the left-most position. Setting MultiLine to True enables a text box to accept or display multiple lines of text at run time. at run time by setting it in code. the user might expect their typing to replace any existing entry. the text box wraps the text to the next line. Automatic word wrap saves the user the trouble of inserting line breaks at the end of lines. the insertion point will be placed after the last character. or by input from the user at run time. The look and behavior of a text box can be changed by setting two properties. The SelStart property is a number that indicates the insertion point within the string of text. as shown in Figure 3. These properties are only available at run time.vbp sample application. Figure 3. see Text. the insertion point will be wherever the user last placed it. It can be set in three different ways: at design time in the Property window. For a working version of this example. this behavior can be disconcerting to the user. You can also use the constant vbCrLf to insert a carriage return/linefeed combination. The ScrollBars property is set to 0-None by default. Within a procedure. The current contents of a text box can be retrieved at run time by reading the Text property. It can be moved by the user from the keyboard or with the mouse. you create a line break by inserting a carriage return followed by a linefeed (ANSI characters 13 and 10). In a data entry application.

the selected text will be replaced." Controls That Present Choices to Users Most applications need to present choices to their users. A small set of options from which a user can choose just one. In some cases.The SelLength property is a numeric value that sets the width of the insertion point. see "Using Visual Basic's Standard Controls. ranging from a simple yes/no option to selecting from a list containing hundreds of possibilities. To provide this feature A small set of choices from which a user can choose one or more options.8 Selection example If the user starts typing while a block of text is selected. Option buttons (use frames if additional groups are needed) Use this control Check boxes .8 shows the selection behavior. you might want to replace a text selection with new text by using a paste command. The following table summarizes these controls and their appropriate uses. The SelText property is a string of text that you can assign at run time to replace the current selection. SelText will insert its text at the current insertion point. Visual Basic includes several standard controls that are useful for presenting choices. starting from the current insertion point. For More Information For additional information on the text box control's properties. Figure 3. Setting the SelLength to a number greater than 0 causes that number of characters to be selected and highlighted. If no text is selected. Figure 3.

A scrollable list of choices from which the user can choose. a command button. You use check boxes in an application to give users true/false or yes/no options. For a working version of this example. Bold and Italic can both be checked. List box Combo box Selecting Individual Options with Check Boxes A check box indicates whether a particular condition is on or off. a user can select any number of check boxes at the same time. The application has a text box.frm in the Controls. Figure 3. For example in Figure 3.10 Check box example The following table lists the property settings for the objects in the application. Because check boxes work independently of each other. Figure 3.9 Check boxes The Check Box Application The Check Box example uses a check box to determine whether the text is displayed in regular or italic font. The user can either choose from the list or type a choice in the edit field. and two check boxes. as shown in Figure 3.10. Object Property Setting .vbp sample application. see Check. a label. A scrollable list of choices along with a text edit field.9.

Italic = False End If End Sub Grouping Options with Option Buttons Option buttons present a set of two or more choices to the user. its Value property is set to 0.Value = vbChecked Then ' If checked.Italic = True Else ' If not checked. txtDisplay.Bold = True Else ' If not checked.Form Name Caption frmCheck Check Box Example txtDisplay Some sample text chkBold &Bold chkItalic &Italic cmdClose &Close Text box Name Text First Check box Name Caption Second Check box Name Caption Command button Name Caption When you check Bold or Italic.Font.Font. Private Sub chkBold_Click () If ChkBold. txtDisplay. Events in the Check Box Application The Click event for the check box occurs as soon as you click the box. the text is converted to bold or italic by setting the Bold or Italic properties of the Font object returned by the Font property of the text box.Font. the check box's Value property is set to 1. txtDisplay. If so. txtDisplay. the check box will be unchecked when it is first displayed. This event procedure tests to see whether the check box has been selected (that is. so unless you change Value. The default Value is 0. selecting one option button immediately clears all the other buttons in . Unlike check boxes. when unchecked. if its Value = vbChecked).Font. option buttons should always work as part of a group.Bold = False End If End Sub Private Sub chkItalic_Click () If ChkItalic. however.Value = vbChecked Then ' If checked. You can use the constants vbChecked and vbUnchecked to represent the values 1 and 0.

the group. Repeat step 2 for each additional option button you wish to add to the frame. you must place some of them inside frames or picture boxes. always draw the frame or picture box first. Select the option button control from the toolbox and draw the control within the frame.12 Option button groups A user can select only one option button in the group when you draw option buttons in a frame.12 shows a form with two option button groups. Figure 3. not in a frame or picture box) constitute one group. Defining an option button group tells the user. If you want to create additional option button groups. Figure 3. in the option button group shown in Figure 3. If you try to move existing controls onto a frame. and then draw the option buttons on top of it. When you create a separate group this way. Drawing the frame first and then drawing each control on the frame allows you to move the frame and controls together. as do all the option buttons inside a picture box.11. the user can select one of three option buttons. 3.11 Selecting an option button Creating Option Button Groups All of the option buttons placed directly on a form (that is. 2." For example. All the option buttons inside any given frame constitute a separate group. . Select the frame control from the toolbox and draw the frame on the form. Figure 3. "Here is a set of choices from which you can choose one and only one. the controls will not move with the frame. To group controls in a frame 1.

vbp sample application. y y y To make a button the default in an option button group. It remains selected until a user selects a different option button or code changes it. The Options Application The form shown in Figure 3. you need to understand that all controls are children of the form on which they are drawn. The Left and Top properties of a control are relative to the parent form. Assigning its Value property to True in code: optChoice. meaning that it is unavailable.Value = True Using a shortcut key specified in the caption of a label. Selecting or Disabling Option Buttons An option button can be selected by: y y Clicking it at run time with the mouse. most controls support the read-only Parent property. set its Value property to True at design time.12 demonstrates how option buttons can be contained within a form or within a frame control. and the control's position relative to the container's Left and Top properties does not change because the control moves with the container. In fact. To understand the concept of containers.13 uses option buttons to determine the processor type and operating system for a fictional computer. Containers for Controls While controls are independent objects. When the user selects a option button in either group. For a working version of this example. To disable an option button. set its Enabled property to False. and controls cannot be moved outside the boundaries of the parent. Tabbing to the option button group and then using the arrow keys to select an option button within the group. When the program is run it will appear dimmed. the caption of the label is changed to reflect the current choices. Moving a container moves the controls as well. which returns the form on which a control is located. Figure 3. see Options. a certain parent and child relationship exists between forms and controls. Being a child affects the placement of a control on the parent form.Note If you have existing controls that you want to group in a frame. Figure 3.frm in the Controls. you can select all the controls and cut and paste them into a frame or picture control.13 Option button example .

Object Label Property Name Caption Command button Name Caption First option button Name Caption Second option button Name Caption Value Third option button Name Caption Frame Name Caption Fourth option button Name Caption Fifth option button Name Caption Value Setting lblDisplay (Empty) cmdClose &Close opt486 &486 opt586 &Pentium True opt686 P&entium Pro fraSystem &Operating System optWin95 Windows 95 optWinNT Windows NT True .The following table lists the property settings for the objects in the application.

14 Single-column list box . The user can then scroll up and down or left to right through the list. strComputer. that concatenates the two variables and updates the label's Caption property: Sub DisplayCaption() lblDisplay. Each time a new option button is selected. scroll bars automatically appear on the control. y The key to this approach is the use of these two form-level variables. although you can set up multiple columns as well. Figure 3. strSystem. only the value of the variables change from one instance to the next. called DisplayCaption. the code in its Click event updates the appropriate variable: Private Sub opt586_Click() strComputer = "Pentium" Call DisplayCaption End Sub It then calls a sub procedure." Using List Boxes and Combo Boxes List boxes and combo boxes present a list of choices to the user.Caption = "You selected a " & _ strComputer & " running " & strSystem End Sub A sub procedure is used because the procedure of updating the Caption property is essentially the same for all five option buttons. For More Information Variables and sub procedures are discussed in detail in "Programming Fundamentals.14 shows a single-column list box. This saves you from having to repeat the same code in each of the Click events. These variables contain different string values. depending on which option buttons were last selected. strComputer and strSystem. If the number of items exceeds what can be displayed in the combo box or list box. the choices are displayed vertically in a single column.Events in the Options Application The Options application responds to events as follows: y The Click events for the first three option buttons assign a corresponding description to a form-level string variable. Figure 3. By default. The Click events for the last two option buttons assign a corresponding description to a second formlevel variable.

A combo box control combines the features of a text box and a list box. Figure 3. or MDI forms (text boxes and MDI forms have a ScrollBars property to add or remove scroll bars that are attached to the control). the code would look like this: List1. The HScrollBar (horizontal) and VScrollBar (vertical) controls operate independently from other controls and have their own set of events.15 Combo box In contrast to some other controls that contain a single value. Scroll bar controls are not the same as the built-in scroll bars that are attached to text boxes.AddItem "San Francisco" List boxes and combo boxes are an effective way to present a large number of choices to the user in a limited amount of space.AddItem "New York" List1. list boxes. removing and retrieving values from their collections at run time. Examples of slider controls can be seen in the Windows 95/98 control panel. Because these controls can indicate the current position on a scale. see "Using Visual Basic's Standard Controls.AddItem "Paris" List1. and methods. to control the sound volume or to adjust the colors in a picture. To add several items to a list box named List1. This control allows the user to select either by typing text into the combo box or by selecting an item from its list. scroll bar controls can be used individually to control program input ³ for example. properties." Using Scroll Bars as Input Devices Although scroll bars are often tied to text boxes or windows. list boxes and combo boxes contain multiple values or a collection of values. for example the label's Caption property or the text box's Text property. combo boxes. They have built-in methods for adding. . Windows interface guidelines now suggest using slider controls as input devices instead of scroll bars. A slider control of this type is included in the Professional and Enterprise editions of Visual Basic.15 shows a combo box. you'll sometimes see them used as input devices. For More Information For additional information on the list box and combo box controls. Figure 3.

To provide this feature A container for other controls. The actual picture that is displayed is determined by the Picture property. the shape control.Picture = LoadPicture("VANGOGH. image controls.gif") The picture box control has an AutoSize property that. They require less system resources and consequently display somewhat faster than the picture box control. shape and line controls are sometimes referred to as "lightweight" graphical controls. and line controls are discussed in the following sections: Working With the Picture Box Control The primary use for the picture box control is to display a picture to the user. the image control. you can use the LoadPicture function to set the Picture property. causes the picture box to resize automatically to match the dimensions of its contents. when set to True. Each is best suited for a particular purpose. Displaying a simple graphical element Use this control Picture box Picture box Image control or picture box Shape or line control Picture boxes.For More Information For additional information on scroll bar controls. shape controls. Displaying a picture. see "Using Visual Basic's Standard Controls. they contain a subset of the properties. To display or replace a picture at run time." Controls That Display Pictures and Graphics Because Windows is a graphical user interface. and the line control. Note Form objects also have a Picture property that can be set to display a picture directly on the form's background. Printing or graphics methods. methods and events available in the picture box. The image. Take extra care in designing your form if you plan on . it's important to have a way to display graphical images in your application's interface. The Picture property contains the file name (and optional path) for the picture file that you wish to display. Visual Basic includes four controls that make it easy to work with graphics: the picture box control. You supply the name (and optional path) for the picture and the LoadPicture function handles the details of loading and displaying it: picMain.

using a picture box with the AutoSize enabled. The picture will resize without regard to other controls on the form, possibly causing unexpected results, such as covering up other controls. It's a good idea to test this by loading each of the pictures at design time.

Using the Picture Box as a Container
The picture box control can also be used as a container for other controls. Like the frame control, you can draw other controls on top of the picture box. The contained controls move with the picture box and their Top and Left properties will be relative to the picture box rather than the form. A common use for the picture box container is as a toolbar or status bar. You can place image controls on it to act as buttons, or add labels to display status messages. By setting the Align property to Top, Bottom, Left, or Right, the picture box will "stick" to the edge of the form. Figure 3.16 shows a picture box with its Align property set to Bottom. It contains two label controls which could be used to display status messages. Figure 3.16 Picture box used as a status bar

Other Uses for the Picture Box
The picture box control has several methods that make it useful for other purposes. Think of the picture box as a blank canvas upon which you can paint, draw or print. A single control can be used to display text, graphics or even simple animation. The Print method allows you to output text to the picture box control just as you would to a printer. Several font properties are available to control the characteristics of text output by the Print method; the Cls method can be used to erase the output. Circle, Line, Point and Pset methods may be used to draw graphics on the picture box. Properties such as DrawWidth, FillColor, and FillStyle allow you to customize the appearance of the graphics. Animation can be created using the PaintPicture method by moving images within the picture control and rapidly changing between several different images. For More Information For additional information on the picture box control, see "Using Visual Basic's Standard Controls."

Lightweight Graphical Controls

The image, shape and line controls are considered to be lightweight controls; that is, they support only a subset of the properties, methods, and events found in the picture box. Because of this, they typically require less system resources and load faster than the picture box control.

Using Image Controls Instead of Picture Boxes
The image control is similar to the picture box control but is used only for displaying pictures. It doesn't have the ability to act as a container for other controls, and it doesn't support the advanced methods of the picture box. Pictures are loaded into the image control just as they are in the picture box: at design time, set the Picture property to a file name and path; at run time, use the LoadPicture function. The sizing behavior of the image control differs from that of the picture box. It has a Stretch property while the picture box has an AutoSize property. Setting the AutoSize property to True causes a picture box to resize to the dimensions of the picture; setting it to False causes the picture to be cropped (only a portion of the picture is visible). When set to False (the default), the Stretch property of the image control causes it to resize to the dimensions of the picture. Setting the Stretch property to True causes the picture to resize to the size of the image control, which may cause the picture to appear distorted. For More Information For additional information on the image control, see "Using Visual Basic's Standard Controls."

Using an Image Control to Create Your Own Buttons
An image control also recognizes the Click event, so you can use this control anywhere you'd use a command button. This is a convenient way to create a button with a picture instead of a caption. Grouping several image controls together horizontally across the top of the screen ³ usually within a picture box ³ allows you to create a toolbar in your application. For instance, the Test Buttons example shows an image control that users can choose like they choose a command button. When the form is first displayed, the control displays one of three traffic icons from the Icon Library included with Visual Basic. Each time the image control is clicked, a different icon is displayed. (For a working version of this example, see Button.frm in the Controls.vbp sample application.) If you inspect the form at design time, you will see that it actually contains all three icons "stacked" on top of each other. By changing the Visible property of the top image control to False, you allow the next image (with its Visible property set to True) to appear on top. Figure 3.17 shows the image control with one of the traffic icons (Trffc10a.ico). Figure 3.17 Image control with a traffic icon

To create a border around the image control, set the BorderStyle property to 1-Fixed Single. Note Unlike command buttons, image controls do not appear pushed in when clicked. This means that unless you change the bitmap in the MouseDown event, there is no visual cue to the user that the "button" is being pushed. For More Information For information on displaying a graphic image in an image control, see "Using Visual Basic's Standard Controls."

Using Shape and Line Controls
Shape and line controls are useful for drawing graphical elements on the surface of a form. These controls don't support any events; they are strictly for decorative purposes. Several properties are provided to control the appearance of the shape control. By setting the Shape property, it can be displayed as a rectangle, square, oval, circle, rounded rectangle, or rounded square. The BorderColor and FillColor properties can be set to change the color; the BorderStyle, BorderWidth, FillStyle, and DrawMode properties control how the shape is drawn. The line control is similar to the shape control but can only be used to draw straight lines. For More Information For additional information on the shape and line controls, see "Using Visual Basic's Standard Controls."

The Images Application
The form shown in Figure 3.18 uses four image controls, a shape control, a picture box, and a command button. When the user selects a playing card symbol, the shape control highlights the symbol and a description is displayed in the picture box. For a working version of this example, see Images.frm in the Controls.vbp sample application. Figure 3.18 Image and shape control example

The following table lists the property settings for the objects in the application. Object Picture box Property Name Align First image control Name Picture Second image control Name Picture Third image control Name Picture Fourth image control Name Caption Shape control Name Shape BorderWidth Height Width Command button Name Caption Setting picStatus Bottom imgClub Spade.ico imgDiamond Diamond.ico imgHeart Heart.ico imgSpade Spade.ico shpCard 4 - Rounded Rectangle 2 735 495 cmdClose &Close

Events in the Images Application
The Images application responds to events as follows:

y

The Click event in each of the image controls sets the Left property of the shape control equal to its own Left property, moving the shape on top of the image. The Cls method of the picture box is invoked, clearing the current caption from the status bar. The Print method of the picture box is invoked, printing the new caption on the status bar.

y y

The code in the image control Click event looks like this:

Private Sub imgHeart_Click() shpCard.Left = imgClub.Left picStatus.Cls picStatus.Print "Selected: Club" shpCard.Visible = True End Sub
Note that the first line in the Click event code assigns a value (the Left property of the image control) to the Left property of the shape control using the = operator. The next two lines invoke methods, so no operator is needed. In the third line, the value ("Selected: Club") is an argument to the Print method. There is one more line of code in the application that is of interest; it is in the Form Load event.

shpCard.Visible = False
By setting the Visible property of the shape control to False, the shape control is hidden until the first image is clicked. The Visible property is set to True as the last step in the image control Click event. For More Information For additional information on properties, methods, and events see "Programming Fundamentals."

Additional Controls
Several other standard controls are included in the Visual Basic toolbox. Some controls are useful for working with large amounts of data contained in an external database. Other controls can be used to access the Windows file system. Still other controls defy categorization, but are useful nonetheless. You can also use ActiveX controls, previously called custom or OLE controls, in a Visual Basic application in the same way that you use the standard controls. The Professional and Enterprise editions of Visual Basic include several ActiveX controls as well as the capability to build your own controls. Additional ActiveX controls for just about any purpose imaginable are available for purchase from numerous vendors. For More Information For additional information on using ActiveX controls, see "Managing Projects."

Its properties. For more information on common dialog control. most information is stored in one or more central databases. see the Visual Basic Data Access Guide. At run time.Data Access Controls In today's business. directories and files. Each serves a unique purpose. Miscellaneous Controls Several other standard controls are included in Visual Basic. the user can rearrange columns and rows to provide different views of the data. including Microsoft Access and SQL Server. . These controls are normally used together to provide a view of drives. y y y y For More Information For additional information on data access controls. with the changes appearing in the underlying database. The DataCombo control is like a combination of the DataList control and a text box. Think of it as a pipeline between the database and the other controls on your form. methods. but with the built-in capability of displaying a list of directories in the currently selected drive. The FileListBox control also looks like a list box with a list of file names in a selected directory." For more information on working with external data. y y Note These controls are provided primarily for backward compatibility with applications created in earlier versions of Visual Basic. Visual Basic includes several data access controls for accessing most popular databases. see "Using Visual Basic's Standard Controls. When used in conjunction with an ADO Data control. File System Controls Visual Basic includes three controls for adding file handling capabilities to your application. y The DriveListBox control looks like a combo box. When used in conjunction with an ADO Data control. It provides a drop-down list of drives from which the user can select. The common dialog control provides an easier method of working with file access. and events allow you to navigate and manipulate external data from within your own application. it can be automatically filled with a list of data from a field in an external database. they have special properties and events that tie them together. The Microsoft Hierarchical FlexGrid control is a unique control for presenting multiple views of data. y The ADO Data control is used to connect to a database. The DirListBox is similar to a list box control. Think of it as a combination of a grid and a tree or outline control. The selected text in the text box portion can be edited. The DataGrid control displays data in a grid or table. it presents fully editable data from multiple fields in an external database. see "Miscellaneous Controls" later in this chapter. The DataList control is similar to the list box control.

When an object has the focus. The common dialog control adds built-in dialog boxes to your application for the selection of files. when command buttons have the focus. Occurs when an object loses focus. only the text box with the focus will display text entered by means of the keyboard. For example. see "Using Visual Basic's Standard Controls.y The timer control can be used to create an event in your application at a recurring interval. several applications can be running at any time. Using the SetFocus method in code. and printing functions. You can see when some objects have the focus. Forms and most controls support these events. but only the application with the focus will have an active title bar and can receive user input. You can give focus to an object by: y y y Selecting the object at run time. Through the OLE container control. fonts.19). On a Visual Basic form with several text boxes. Event GotFocus LostFocus Description Occurs when an object receives focus." Understanding Focus Focus is the ability to receive user input through the mouse or keyboard. or for reversing or changing conditions you set up in the object's GotFocus procedure. The OLE container control is an easy way to add capabilities like linking and embedding to your application. it can receive input from a user. Figure 3. In the Microsoft Windows interface. they appear with a highlighted border around the caption (see Figure 3. This is useful for executing code without the need for user interaction. Word and many others. The GotFocus and LostFocus events occur when an object receives or loses focus. Using an access key to select the object at run time. A LostFocus event procedure is primarily used for verification and validation updates. you can provide access to the functionality of any OLEenabled application such as Microsoft Excel. colors.19 A command button showing focus . y y For More Information For additional information on any of the standard controls.

For more information. When the application starts. Text1 has the focus. Command1. which occurs before a control loses focus. In many cases. controls that are invisible at run time. Validate Event of Controls Controls also have a Validate event. For example. because the Validate event occurs before the focus is lost.20. The Enabled property allows the object to respond to user-generated events such as keyboard and mouse events. Note A form can receive focus only if it doesn't contain any controls that can receive the focus. cannot receive focus. such as the Timer control. such as the lightweight controls. this event occurs only when the CausesValidation property of the control that is about to receive the focus is set to True. Lightweight controls include the following: y y y y y Frame control Image control Label control Line control Shape control Additionally. Text1 and Text2. cannot receive focus. and then a command button. it is more appropriate than the LostFocus event for data validation. as shown in Figure 3. . assume you create two text boxes. the tab order is the same as the order in which you created the controls. Usually. see "Validating Control Data By Restricting Focus" in "Using Visual Basic's Standard Controls That Can't Receive Focus Some controls. The Visible property determines whether an object is visible on the screen. Setting the Tab Order The tab order is the order in which a user moves from one control to another by pressing the TAB key. Pressing TAB moves the focus between controls in the order they were created.An object can receive focus only if its Enabled and Visible properties are set to True. Each form has its own tab order. However.

the second has a TabIndex of 1. the button with its Value set to True) has its TabStop property automatically set to True. set the TabIndex property. don't have a TabIndex property and are not included in the tab order. even though the control is skipped when you cycle through the controls with the TAB key. You can remove a control from the tab order by setting its TabStop property to False (0). Visual Basic automatically renumbers the tab order positions of the other controls to reflect insertions and deletions. Note An option button group has a single tab stop. The selected button (that is. Removing a Control from the Tab Order Usually. As a user presses the TAB key.20 Tab example To change the tab order for a control.Figure 3. the first control drawn has a TabIndex value of 0. Even if you set the TabIndex property to a number higher than the number of controls. The TabIndex property of a control determines where it is positioned in the tab order. and so on. while the other buttons have their TabStop property set to False. When you change a control's tab order position. these controls are skipped. For example. Visual Basic converts the value back to the number of controls minus 1. as shown in the following table. . TabIndex before it is changed Control Text1 Text2 Command1 0 1 2 1 2 0 TabIndex after it is changed The highest TabIndex setting is always one less than the number of controls in the tab order (because numbering starts at 0). pressing TAB at run time selects each control in the tab order. the TabIndex values for the other controls are automatically adjusted upward. A control whose TabStop property has been set to False still maintains its position in the actual tab order. as well as disabled and invisible controls. Note Controls that cannot get the focus. if you make Command1 first in the tab order. By default.

A menu control is an object. for example.22. which is invoked when the menu control is selected with the mouse or using the keyboard. the Click event. When you click a menu title (such as File). and Save As¬ are all found on the File menu. and others at design time or at run time. (In Windows 95 or later. if you click a text box with the right mouse button. the Exit menu item on the File menu closes the application.21. Some menu items perform an action directly. and submenu titles. the Enabled and Visible properties. menus offer a convenient and consistent way to group commands and an easy way for users to access them. These menu items should be followed by an ellipsis (¬).Menu Basics If you want your application to provide a set of commands to users. the Checked property. Menu controls contain only one event. the file-related commands New. like other objects it has properties that can be used to define its appearance and behavior. you activate context menus by clicking the right mouse button. separator bars.22. independent of the menu bar. the Save File As dialog box appears. Figure 3. For example. Other menu items display a dialog box ³ a window that requires the user to supply information needed by the application to perform the action. In Figure 3. pop-up menus are also called context menus. Menu items can include commands (such as New and Exit).21 The elements of a menu interface on a Visual Basic form The menu bar appears immediately below the title bar on the form and contains one or more menu titles. Open. For example. you should group menu items according to their function. To make your application easier to use. Figure 3. when you choose Save As¬ from the File menu. You can set the Caption property.) You should use pop-up menus to provide an efficient method for accessing common. for example. see "Creating Menus with the Menu Editor" in "Creating a User Interface. Each menu item the user sees corresponds to a menu control you define in the Menu Editor (described later in this chapter). The items displayed on the pop-up menu depend on the location of the pointer when the right mouse button is pressed. For More Information For additional information on menu controls. contextual commands. therefore.22 A pop-up menu .21 Illustrates the elements of a menu interface on an untitled form." Pop-up Menus A pop-up menu is a floating menu that is displayed over a form. a menu containing a list of menu items drops down. as shown in Figure 3. a contextual menu would appear. Figure 3. as shown in Figure 3.

to quickly change a single property.23 Figure 3. see "Creating Menus" in "Creating a User Interface. You would normally create a menu in the Menu Editor. and change and delete existing menus and menu bars. shown in Figure 3.23 The Menu Editor While most menu control properties can be set using the Menu Editor. you can add new commands to existing menus. use the PopupMenu method. choose Menu Editor. To display a pop-up menu. all menu properties are also available in the Properties window. To display the Menu Editor y From the Tools menu.Any menu that has at least one menu item can be displayed at run time as a pop-up menu. You can customize menus in a completely interactive manner that involves very little programming. see "Creating Menus" in "Creating a User Interface. you could use the Properties window. create new menus and menu bars. This opens the Menu Editor. replace existing menu commands with your own commands." Using the Menu Editor With the Menu Editor. The main advantage of the Menu Editor is its ease of use. For More Information For additional information on creating pop-up menus." Prompting the User with Dialog Boxes . however. For More Information For additional information on creating menus and using the Menu Editor.

Modeless dialog boxes are rare. a dialog box is modal if it requires you to click OK or Cancel before you can switch to another form or dialog box. y Figure 3.24 looks like this: MsgBox "Error encountered while trying to open file. Dialog boxes are a specialized type of form object that can be created in one of three ways: y y Predefined dialog boxes can be created from code using the MsgBox or InputBox functions. Managing Projects To create an application with Visual Basic. This chapter describes how to build and manage projects. The code for displaying the dialog box shown in Figure 3. You can continue to work elsewhere in the current application while the dialog box is displayed. Customized dialog boxes can be created using a standard form or by customizing an existing dialog box. Figure 3. or arguments. "Text Editor" You supply three pieces of information. a constant (numeric value) to determine the style of the dialog box.In Windows-based applications. From the Edit menu.". vbExclamation. Styles are available with various combinations of buttons and icons to make creating dialog boxes easy.24 shows an example of a predefined dialog box created using the MsgBox function. such as Print and File Open. and a title. Modeless dialog boxes let you shift the focus between the dialog box and another form without having to close the dialog box. . Use modeless dialog boxes to display frequently used commands or information." & vbCrLf & "please retry. they are usually displayed as modal dialog boxes. A modal dialog box must be closed (hidden or unloaded) before you can continue working with the rest of the application. For example. the Find dialog box in Visual Basic is an example of a modeless dialog box. A project is the collection of files you use to build an application. Because most dialog boxes require user interaction. Standard dialog boxes. to the MsgBox function: the message text. you work with projects. dialog boxes are used to prompt the user for data needed by the application to continue or to display information to the user. can be created using the common dialog control. you will usually display a dialog because a response is needed before the application can continue.24 A predefined dialog box This dialog is displayed when you invoke the MsgBox function in code.

frx). add. and File Formats. Optionally. When you have completed all the files for a project. All of the files and objects can be shared by other projects as well. . you will usually create new forms.dll files. choose the Make project. one or more files containing ActiveX controls (. Optionally. This information is updated every time you save the project. or remove editable files from a project. One file for each form (. you can convert the project into an executable file (.ocx). Visual Basic reflects your changes in the Project Explorer window." The Project Explorer As you create. Optionally. you might also reuse or modify forms that were created for previous projects. which contains a current list of the files in the project. Limitations. y y y y The project file is simply a list of all the files and objects associated with the project. for additional information related to other project types see the Component Tools Guide.cls).ocx and .bas).exe command.res). A project consists of: y y y One project file that keeps track of all the components (.frm file that contains binary properties. one file for each class module (.vbp).1 shows some of the types of files you can include in a Visual Basic project.frm). you work with a project to manage all the different files that make up the application. For information about binary data files and project files." later in this chapter. For More Information For more details about creating executables. After all of the components in a project have been assembled and the code written. These files are not editable and are automatically generated for any . References in this chapter assume a standard . Note With the Professional and Enterprise editions of Visual Basic.When you create an application. see "Making and Running an Executable File. The same is true for other modules or files that you might include in your project.exe project. Working with Projects As you develop an application. ActiveX controls and objects from other applications can also be shared between projects. as well as information on the environment options you set. a single resource file (. see "Visual Basic Specifications. you compile your project to create an executable file. The Project Explorer window in Figure 4. Optionally. one file for each standard module (. One binary data file for each form containing data for properties of controls on the form (. you can also create other types of executable files such as .exe): From the File menu. such as Picture or Icon.

cls file name extension) are similar to form modules. as well as references to the ActiveX controls and insertable objects that are used in the project. see "Creating Your Own Classes" in "Programming with Objects. Form Modules Form modules (. A project file contains the same list of files that appears in the Project Explorer window. Limitations. and external procedures. including their property settings. For More Information For information about writing code in class modules. and File Formats. and File Formats. For More Information The specific format of information stored in the .vbp file is described in "Visual Basic Specifications. event procedures. You can use class modules to create your own objects. You can open an existing project file by double-clicking its icon. They can also contain form-level declarations of constants. Limitations. and general procedures." The Structure of a Visual Basic Project The following sections describe the different types of files and objects that you can include in a project.vbp). For More Information For more about creating forms. see "Visual Basic Specifications.frm file name extension) can contain textual descriptions of the form and its controls." Standard Modules ." For information about the format and content of form files.Figure 4. by choosing the Open Project command from the File menu." Class Modules Class modules (.1 The Project Explorer window The Project File Each time you save a project. or by dragging the file and dropping it on the Project Explorer window. including code for methods and properties. Visual Basic updates the project file (. except that they have no visible user interface. see "Developing an Application in Visual Basic" and "Creating a User Interface. variables.

see "Programming Fundamentals" and "Programming with Objects. see "Creating ActiveX Components" in the Component Tools Guide. For More Information For more information on using resource files. For More Information For more information on ActiveX documents. but are used to create ActiveX controls and their associated property pages for displaying design-time properties. The Professional and Enterprise editions of Visual Basic are capable of creating ActiveX controls. constants. Components In addition to files and modules. and "International Issues. text strings. which you can then localize instead of the entire application.dob) are similar to forms. the files containing the controls included with Visual Basic are copied to a common directory (the \Windows\System subdirectory under Windows 95 or later).res file name extension) contain bitmaps.bas file name extension) can contain public or module-level declarations of types. You can also create your own controls using the Professional or Enterprise editions of Visual Basic. A project can contain no more than one resource file. For More Information For more information on ActiveX control creation.ocx file name extension) are optional controls which can be added to the toolbox and used on forms. For More Information For information about using modules.Standard modules (. and public procedures. variables. ActiveX Controls ActiveX controls (. see "Using the ActiveX Controls" in the Component Tools Guide. For More Information For more information on using the included ActiveX controls. When you install Visual Basic. For example." ActiveX Documents ActiveX documents (." in the Component Tools Guide. The Professional and Enterprise editions of Visual Basic are capable of creating ActiveX documents. . external procedures. see "Creating an ActiveX Control" in "Creating ActiveX Components.pag) modules are also similar to forms." Resource Files Resource files (. see "Using a Resource File" later in this chapter. Additional ActiveX controls are available from a wide variety of sources. you can keep all of the user-interface text strings and bitmaps in a resource file. if you plan to localize your application in a foreign language.ctl) and Property Page (. but are displayable in an Internet browser such as Internet Explorer. several other types of components can be added to the project. User Control and Property Page Modules User Control (. and other data that you can change without having to re-edit your code.

and Saving Projects Four commands on the File menu allow you to create. For More Information For more information about ActiveX designers. modules. prompting you to save any files that have changed. For More Information For more information on references. and text. Creating. see "ActiveX Designers" in "Programming with Objects. Open Project Closes the current project. are components you can use as building blocks to build integrated solutions. open. including the forms. You can select a type of project from the New Project dialog." Standard Controls Standard controls are supplied by Visual Basic. prompting you to save any changes. see "Programming with Components. are always included in the toolbox. such as spreadsheets. unlike ActiveX controls and insertable objects. such as a Microsoft Excel Worksheet object. which can be removed from or added to the toolbox.Insertable Objects Insertable objects. accessed from the References menu item on the Project menu.vbp) file. see "Using Other Applications' Objects" later in this chapter. ActiveX Designers ActiveX designers are tools for designing classes from which objects can be created." References You can also add references to external ActiveX components that may be used by your application. Standard controls. and ActiveX controls listed in its project (. bitmaps. which were all created by different applications. An integrated solution can contain data in different formats. You assign references by using the References dialog. . Visual Basic then creates a new project with a single new file. Additional designers may be available from other sources. Opening. and save projects. Menu command New Project Description Closes the current project. For More Information For more information on using other applications' objects. such as the command button or frame control. The design interface for forms is the default designer. Visual Basic then opens an existing project.

such as a form. Visual Basic also prompts you to save any forms or modules that have changed. can be part of more than one project. 2. Removing. and choose Open. 2. This is useful for building and testing solutions involving user-created controls or other components. Select an existing project or a new project type. Select a project or a component of a project in the Project Explorer. Removing. When more than one project is loaded. see "Adding. A single file. Select Project. To remove a project from the current project group 1. Note that changes made to a form or module in one project will be propagated amongst all projects that share that module. choose Remove Project Adding. and Saving Files Working with files within a project is similar to working with the projects themselves. and class modules. standard. To add a file to a project 1. Save Project As Updates the project file of the current project. From the File menu. the caption of the Project Explorer window will change to Project Group and the components of all open projects will be displayed. From the File menu. For More Information For more information about sharing files. . Add filetype (where filetype is the type of file).2) is displayed. saving the project file under a file name that you specify. To add an additional project to the current project group 1. The Add Project dialog box is displayed. The Add filetype dialog box (Figure 4. It is also possible to share files between projects.Save Project Updates the project file of the current project and all of its form. choose Add Project. Working with Multiple Projects In the Professional and Enterprise editions of Visual Basic. it is possible to have more than one project open at a time. and Saving Files" later in this chapter.

You can also drag and drop . To change a file without affecting other projects. If you delete a file outside of Visual Basic. Note You can drag and drop files from the Windows Explorer. Visual Basic displays an error message warning you that a file is missing. To save an individual file without saving the project 1.2. To insert a text file into your code 1. Select an existing file or a new file type. select the form or module into which you want to insert code. select the file in the Project Explorer. if you make changes to a file and save it. choose Save filename As from the File menu. Visual Basic updates this information in the project file when you save it. Figure 4. . This is useful for adding a list of constants or for adding snippets of code that you might have saved in text files. Merging Text You can also insert existing text from other files into one of your code modules. From the Project window. you are not adding a copy of the file. choose Remove filename. The file will be removed from the project but not from the disk. when you open the project. Therefore. Visual Basic cannot update the project file. your changes will affect any project that includes the file. or Network Neighborhood into the Project window to add them to a project. and choose Open. 2. you are simply including a reference to the existing file in the project. From the Project menu. however. Select the file in the Project Explorer. 3.ocx files onto the toolbox to add new controls. To remove a file from a project 1. File Manager. From the File menu.2 The Add Form dialog box When you add a file to a project. choose Save filename . Select the file in the Project Explorer. and then save the file under a new file name. 2. If you remove a file from a project. therefore.

3. All of the ActiveX controls that you selected will now appear in the toolbox. 4. Adding Controls to a Project The set of controls available in the toolbox can be customized for each project. and move the cursor to the point in the Code Editor where you want to insert code. The basic set of standard controls that always appear in the toolbox is described in "Forms. From the Project menu. Choose OK to close the Components dialog box.3 The Components dialog box . as doing so may put the module into an internally inconsistent state. as shown in Figure 4. The items listed in this dialog box include all registered ActiveX controls. insertable objects. To add a control to a project's toolbox 1. select the Controls tab. such as a Microsoft Excel Chart. From the Edit menu. In particular. select the Insertable Objects tab. Any given control must be in the toolbox before you can add it to a form in the project. and ActiveX designers. and choose Open. To view insertable objects. To view controls with . choose Components. changing this attribute may cause serious problems with the GlobalMultiUse and GlobalSingleUse classes. Figure 4. To add a control (. 3. and Menus. you should not edit attributes manually. choose Insert File. The Components dialog box is displayed. Choose the View Code button. be careful not to change settings of the attribute VB_PredeclaredId. 2. select the check box to the left of the control name. Note If you edit Visual Basic source files using a text or code editor other than Visual Basic." Adding ActiveX Controls to a Project You can add ActiveX controls and insertable objects to your project by adding them to the toolbox.ocx file name extension) or an insertable object to the toolbox.3. In general. Select the name of the text file you want to insert. Controls.2.ocx file name extensions.

oca files are typically stored in the same directory as the ActiveX controls and are recreated as needed (file sizes and dates may change). The Components dialog box is displayed. choose the Browse button. 2. but not as controls. From the Project menu. choose References. Note You cannot remove any control from the toolbox if an instance of that control is used on any form in the project. To make another application's objects available in your code. To add objects to the toolbox. and search other directories for files with a . 2. set a reference to that application's object library. The References dialog box is displayed. When you add an ActiveX control to the list of available controls. This file stores cached type library information and other data specific to the control. Clear the check box next to each control you want to remove.oca extension. either as controls in the toolbox or as programmable objects in your code. such as those included in the Microsoft Excel object library. The control icons will be removed from the toolbox. see "Adding Controls to a Project" earlier in this chapter.To add ActiveX controls to the Components dialog box. Note Each ActiveX control is accompanied by a file with an . .4. Visual Basic automatically selects the check box. as shown in Figure 4. Removing Controls from a Project To remove a control from a project 1. choose Components.ocx file name extension. The . To add a reference to another application's object library 1. Select the check box next to each reference you want to add to your project. Using Other Applications' Objects You can also use objects from other applications. From the Project menu.

choose the Browse button. see "International Issues. Select an existing resource file (. For More Information " For information on the Object Browser. You can use any object listed in the Object Browser in your code. and other material that may change between localized versions or between revisions or specific configurations.res extension. thus reducing the time it takes your project to compile. see "Finding Out About Objects" in "Programming with Objects. 3.To add references to applications not listed in the References dialog box." ." Using a Resource File A resource file allows you to collect all of the version-specific text and bitmaps for an application in one place. screen text.4 The References dialog box If you are not using any objects in a referenced library. 2. From the Project menu. Figure 4. To add a file to a project 1. Choose OK to add the selected references to your project. and then select the application. icons. select Add File. Once you have set references to the object libraries you want. you should clear the check box for that reference to minimize the number of object references Visual Basic must resolve. A single project can have only one resource file. This can include constant declarations.res) and choose Open. if you add a second file with a . an error occurs. The Add File dialog box is displayed. For More Information For more information on the contents of a resource file. you can find a specific object and its methods and properties in the Object Browser by choosing Object Browser from the View menu.

Project Description A user-friendly name for the project. such as creating a form. you can find more information by searching Help. Use the Project Properties dialog box. Wizards are a type of add-in that can simplify certain tasks. Property settings are saved to the project (." Using Wizards and Add-Ins Visual Basic allows you to select and manage add-ins. for example. components. Identifies the project in code. the project name and class name cannot exceed a total of 37 characters. For More Information To learn about setting environment options that affect all projects. see "Developing An Application in Visual Basic. The context ID for the specific Help topic to be called when the user selects the "?" button while the application's object library is selected in the Object Browser. Several wizards are included in Visual Basic. Displayed in the References and Object Browser dialog boxes. or Sub Main ( ). and multithreading. spaces. including those for compiling. The following table describes some of the options you can set. special source code control capabilities. or start with a nonalphabetic character. These extensions add capabilities to the Visual Basic development environment.vbp) file. Help File Project Help Context ID The name of the Help file associated with the project. . which are extensions to Visual Basic. For a public class name. Microsoft and other developers have created add-ins you can use in your applications. Option Startup Object Project Name Description The first form that Visual Basic displays at run time.). accessible through the Project Properties command on the Project menu. It can't contain periods (. When you're ready to access some of the more advanced options. Many other options are also available.Setting Project Options Visual Basic allows you to customize each project by setting a number of properties.

choose Application Wizard. When you are finished making your selections. To unload an add-in or prevent it from loading. Once installed. Using the Add-In Manager You can add or remove an add-in to your project by using the Add-In Manager.To have an add-in appear on the Add-In Manager dialog box. Highlight an add-in from the list and click the desired behaviors in Load Behavior. choose Add-In Manager. Visual Basic saves your add-in selections between editing sessions. all you need to do is add code for your own specific functionality. they will appear as selections on the Add-Ins menu. 2. Select the Application Wizard icon. Some of the wizards also appear as icons in the related dialog boxes. choose New Project. which is accessible from the Add-Ins menu. Depending upon your Load Behavior selections. the developer of the add-in must ensure that it is installed properly. Wizards are installed or removed using the Add-in Manager. Using Wizards Wizards make working with Visual Basic even easier by providing task-specific assistance. It generates the forms and the code behind the forms based on your choices. the Application Wizard can also be accessed using its icon in the New Project dialog box. choose OK. From the File menu. ²or² 1. 2. . the Application Wizard included in Visual Basic helps you to create the framework for an application by presenting a series of questions or choices. The Professional and Enterprise editions of Visual Basic include other wizards. Note Selecting an add-in may add menu items to the Visual Basic Add-Ins menu. To install an add-in 1. including a Data Form Wizard for creating forms to be used with databases. and an ActiveX Document Wizard for converting forms for use in Internet applications. To start the Application Wizard y From the Add-Ins menu. for example. 3. For example. From the Add-Ins menu. clear all Load Behavior boxes. The Add-In Manager dialog box lists the available add-ins. Visual Basic connects the selected add-ins and disconnects the cleared add-ins.

Visual Basic is an object-based programming language. Once you understand a few basic concepts. Imagine the chaos that would result if your application's code was allowed to execute in random order. the event-driven nature of Visual Basic introduces some subtle differences. Visual Basic supports a number of common programming constructs and language elements. The form that you see on screen is a representation of the properties that define its appearance and intrinsic behavior. the structure of its code closely models its physical representation on screen. By definition. As with any modern programming language. much of the material covered in this chapter will seem familiar. the need for organization or structure becomes obvious.1 A form and its related form module . where the instructions are stored and the order in which instructions are executed. Try and approach this material with an open mind.3. you will need to write the code that defines the application's behavior. 5. The structure of an application is the way in which the instructions are organized. that is. As applications become more complex. After creating the interface for your application using forms and controls. 6. Simple applications such as the classic "hello world" example have a simple structure. the structure is important to the programmer: how easily can you find specific instructions within your application? Because a Visual Basic application is based on objects. Don't worry: whether you realize it or not. you will be able to create powerful applications using Visual Basic. objects contain data and code. If you're new to programming. In addition to controlling the execution of an application. you've been dealing with objects most of your life. objects actually help to make programming easier than ever before. 7. The mere mention of objects may cause undue anxiety in many programmers. This chapter introduces the essential components of the Visual Basic language. organization isn't very important with a single line of code. Programming Fundamentals 4.frm) that contains its code. Figure 5. If you've programmed in other languages. the material in this chapter will serve as an introduction to the basic building blocks for writing code. there is a related form module (with file name extension . While most of the constructs are similar to other languages. once you understand the differences you can use them to your advantage. Once you understand the basics. For each form in an application. The Structure of a Visual Basic Application An application is really nothing more than a set of instructions directing the computer to perform a task or tasks.

Whereas a standard module contains only code. your project contains a single form module. there is a corresponding set of event procedures in the form module. A procedure that might be used in response to events in several different objects should be placed in a standard module. Forms can contain controls. In addition to event procedures. form modules can contain general procedures that are executed in response to a call from any event procedure. You can add additional form.Each form module contains event procedures ³ sections of code where you place the instructions that will execute in response to specific events. A class module (. While "Managing Projects" describes which components you can add to an application. and standard modules. a class module contains both code and data ³ you can think of it as a control without a physical representation. Code that isn't related to a specific form or control can be placed in a different type of module. rather than duplicating the code in the event procedures for each object. as needed. a standard module (. Class modules are discussed in "Programming with Objects. class. this chapter explains how to write code in the various components that make up an application.BAS). ." y How an Event-Driven Application Works A discussion of the Event-driven model. For each control on a form.CLS) is used to create objects that can be called from procedures within your application. By default.

it helps to think of your application in terms of the objects that it represents. Determining which procedures belong in which module depends somewhat on the type of application that you are creating. Vcr. it may not be as obvious that you need to design the structure of the code. is based on the objects that comprise a video cassette recorder and a television. Figure 5. The VCR application consists of two form modules. Each module contains one or more procedures that contain the code: event procedures. and optional class modules. Sub or Function procedures. and two class modules.vbp.2 The structure of the VCR project is shown in the Object Browser . The design of the sample application for this chapter. The way you structure your application can make a difference in its performance as well as in the maintainability and usability of your code. optional standard modules for shared code. The code in a Visual Basic application is organized in a hierarchical fashion. and Property procedures.Before You Start Coding Perhaps the most important (and often overlooked) part of creating an application in Visual Basic is the design phase. A typical application consists of one or more modules: a form module for each form in the application. While it's obvious that you need to design a user interface for your application. a standard module. You can use the Object Browser to examine the structure of the project (Figure 5.2). Because Visual Basic is based on objects.

or Record buttons are "pushed. cmdRecord. The event procedures for all of these objects are contained in the Vcr." the Pause and Stop buttons need to be enabled. Because they are independent code modules. and so on).3 The main form for the VCR application In many cases there are repetitive procedures that are shared by more than one object. The software VCR also contains a clock (lblTime). A group of Command buttons (cmdPlay. Rather than repeat this code in each button's Click event procedure. The classes defined in these modules have no direct references to any of the objects in the forms. . such as the tape transport mechanism or the logic for recording a television program. some of the functions of the software VCR have no visual representation. all of the modifications can be done in one place. when the Play. This and other shared procedures are contained in the standard module. Some parts of a VCR aren't visible.The main form for the VCR application (frmVCR) is a visual representation of a combination VCR and television screen (Figure 5. Rewind. function indicators (shpPlay.3).frm form module. they could easily be reused to build an audio recorder without any modifications. it's better to create a shared Sub procedure that can be called by any button. Vcr. Figure 5. and so on) mimic the buttons used to operate a VCR. code to control the direction and speed of the "tape" is contained in the clsTape module. Code to initiate the "recording" process is contained in the clsRecorder module. shpRecord.bas.cls. Likewise. These are implemented as two class modules: Recorder. a channel indicator (lblChannel). It is composed of several objects that model those found in the real world version. If these procedures need to be modified in the future. For example. and a "picture tube" (picTV).cls and Tape.

class or standard modules. or Property procedure contains pieces of code that can be executed as a unit. variable. discuss the basics of using the Code Editor. A Sub. These are discussed in the section "Procedures" later in this chapter. general procedures. and so on. If you have several forms in an application. As your applications get larger and more sophisticated. The code that you write in a form module is specific to the particular application to which the form belongs. types. you would also see descriptions of the form and its controls. type. standard. including their property settings. and formatting code. Standard Modules . y Form Modules Form modules (. Visual Basic has its own rules for organizing. constants. Like any programming language." As you learn more about objects and writing code. If you were to look at a form module in a text editor. the second Form2. class. You can place constant. Simple applications can consist of just a single form. Code Modules Code in Visual Basic is stored in modules. The following topics introduce code modules and procedures. and form module can contain: y Declarations. Each standard. it's a good idea to give them meaningful names to avoid confusion when writing or editing your code. By default. Code Writing Mechanics Before you begin. and cover basic rules for writing code. Over time. Visual Basic names the first form in a project Form1. it might also reference other forms or objects within that application. it's important to establish naming conventions. and external procedures. They can contain procedures that handle events. Eventually you might find that there is common code you want to execute in several forms. and all of the code in the application resides in that form module. and form-level declarations of variables. you can refer to the VCR sample application for examples of various different coding techniques. so you create a separate module containing a procedure that implements the common code. Some suggested naming conventions are presented in "Visual Basic Coding Conventions. Function. you can build up a library of modules containing shared procedures. There are three kinds of modules: form. you add additional forms. This separate module should be a standard module. You don't want to duplicate the code in both forms. and dynamic-link library (DLL) procedure declarations at the module level of form. and class. it's important to understand the mechanics of writing code in Visual Basic. Procedures.In addition to designing the structure of your code.FRM file name extension) are the foundation of most Visual Basic applications. editing.

Class Modules Class modules (. You can write code in class modules to create new objects.4 The Code Editor window . For More Information For information about writing code in class modules. These new objects can include your own customized properties and methods. and User Controls. external procedures. types. forms are just class modules that can have controls placed on them and can display form windows. if you're careful not to reference forms or controls by name. From the standpoint of writing code." Note The Professional and Enterprise editions of Visual Basic also include ActiveX Documents. Using the Code Editor The Visual Basic Code Editor is a window where you write most of your code. The code that you write in a standard module isn't necessarily tied to a particular application. ActiveX Designers. They can contain global (available to the whole application) or module-level declarations of variables. Figure 5. constants.CLS file name extension) are the foundation of object-oriented programming in Visual Basic. see "Programming with Objects. Actually.BAS file name extension) are containers for procedures and declarations commonly accessed by other modules within the application. It is like a highly specialized word processor with a number of features that make writing Visual Basic code a lot easier. these modules should be considered the same as form modules.Standard modules (. These introduce new types of modules with different file name extensions. and global procedures. The Code Editor window is shown in Figure 5. a standard module can be reused in many different applications.4.

In a form module.Because you work with Visual Basic code in modules. among others. where you place module-level variable. use the View Selection buttons in the lower left-hand corner of the editor window. or to view all of the procedures in the module with each procedure separated from the next by a line (as shown in Figure 5. The procedure list for a general section of a module contains a single selection ³ the Declarations section. Switching between sections is accomplished using the Object Listbox. and DLL declarations. You can choose to view a single procedure at a time. the list includes a general section. Code within each module is subdivided into separate sections for each object contained in the module. constant. As you add Sub or Function procedures to a module. accessed using the Procedure Listbox.4). . Each section of code can contain several different procedures. for a standard module only a general section is shown. and DblClick events. For example. those procedures are added in the Procedure Listbox below the Declarations section. For a class module. a section for the form itself. a separate Code Editor window is opened for each module you select from the Project Explorer. Standard modules don't list any event procedures. To switch between the two views. Class modules list only the event procedures for the class itself ³ Initialize and Terminate. Two different views of your code are available in the Code Editor window. The procedure list for a form module contains a separate section for each event procedure for the form or control. the procedure list for a Label control includes sections for the Change. because a standard module doesn't support events. the list includes a general section and a class section. and a section for each control contained on the form. Click.

After you enter the first argument value.Automatic Code Completion Visual Basic makes writing code much easier with features that can automatically fill in statements. Auto Quick Info can also be accessed with the CTRL+I key combination. Type in the first few letters of the property name and the name will be selected from the list. accessed through the Options command on the Tools menu. statement or function prototypes. Even if you choose to disable the Auto List Members feature. Figure 5. When you enter the name of a control in your code. the editor displays lists of appropriate choices. Options for enabling or disabling these and other code settings are available on the Editor tab of the Options dialog.6). properties. or values. This option is also helpful when you aren't sure which properties are available for a given control. the Auto List Members feature presents a drop-down list of properties available for that control (Figure 5.5 The Auto List Members feature The Auto Quick Info feature displays the syntax for statements and functions (Figure 5. the second argument appears in bold. you can still access it with the CTRL+J key combination.5). with the first argument in bold. the TAB key will complete the typing for you. When you enter the name of a valid Visual Basic statement or function the syntax is shown immediately below the current line.6 Auto Quick Info . Figure 5. As you enter code. and arguments for you.

Bookmarks Bookmarks can be used to mark lines of code in the Code Editor so that you can easily return to them later. both online and when printed." Code Basics This section presents information on code writing mechanics. Bookmarks menu item. adding comments to your code. Commands to toggle bookmarks on or off as well as to navigate existing bookmarks are available from the Edit. Using this character can make your code easier to read. including breaking and combining lines of code. The following code is broken into three lines with line-continuation characters ( _): . Breaking a Single Statement Into Multiple Lines You can break a long statement into multiple lines in the Code window using the line-continuation character (a space followed by an underscore). and following naming conventions in Visual Basic. or from the Edit toolbar For More Information For more information on key combinations to access these and other functions in the Code Editor window. see "Code Window Keyboard Shortcuts. using numbers in code.

For example: ' This is a comment beginning at the left edge of the ' screen.Data1. it's better to place each statement on a separate line. Limitations. Both are illustrated in the preceding code. Publishers" _ & "WHERE Publishers. Visual Basic represents numbers in hexadecimal with the prefix &H and in octal with &O.BackColor = _ Red In order to make your code more readable.Text = "Hello" : Red = 255 : Text1. however. Such words are remarks placed in the code for the benefit of the developer. and other programmers who might examine the code later." Adding Comments to Your Code As you read through the examples in this guide. and there is no statement terminator. Combining Statements on One Line There is usually one Visual Basic statement to a line. and File Formats. Remember that comments can't follow a line-continuation character on the same line.Text = "Hi!" ' Place friendly greeting in text ' box. Understanding Numbering Systems Most numbers in this documentation are decimal (base 10). you'll often come across the comment symbol ('). There are also some limitations as to where the line-continuation character can be used.RecordSource = _ "SELECT * FROM Titles.State = 'CA'" You can't follow a line-continuation character with a comment on the same line.PubID" _ & "AND Publishers.PubId = Titles. For More Information For more information. But occasionally it's convenient to use hexadecimal numbers (base 16) or octal numbers (base 8). This symbol tells Visual Basic to ignore the words that follow it. Text1. you can place two or more statements on a line if you use a colon (:) to separate them: Text1. see "Visual Basic Specifications. octal. Comments can follow a statement on the same line or can occupy an entire line. The following table shows the same numbers in decimal. Decimal 9 Octal &O11 Hexadecimal &H9 . Note You can add or remove comment symbols for a block of code by selecting two or more lines of code and choosing the Comment Block or Uncomment Block buttons on the Edit toolbar. and hexadecimal. However.

variables. some number systems lend themselves to certain tasks. see the Language Reference. classes. because Visual Basic assumes you mean the Loop keyword.Loop. y y A restricted keyword is a word that Visual Basic uses as part of its language. For More Information For a complete list of keywords. The names of the procedures. For example. and modules must not exceed 40 characters. you can have a control named Loop. The names of controls. Your forms and controls can have the same name as a restricted keyword. To refer to a form or control that has the same name as a restricted keyword. such as using hexadecimals to set the screen and control colors. and constants that you declare in your Visual Basic code must follow these guidelines: y y They must begin with a letter. you declare and name many elements (Sub and Function procedures. functions (such as Len and Abs). They can't contain embedded periods or type-declaration characters (special characters that specify a data type.Visible = True ' Qualified with the form ' name. ' Square brackets also ' work. variables. They can't be the same as restricted keywords. . For example. this code does not cause an error: MyForm. However.Visible = True ' Causes an error. This includes predefined statements (such as If and Loop). and so on). however. constants. you must either qualify it or surround it with square brackets: [ ].15 16 20 255 &O17 &O20 &O24 &O377 &HF &H10 &H14 &HFF You generally don't have to learn the hexadecimal or octal number system yourself because the computer can work with numbers entered in any system. They can be no longer than 255 characters. In your code you cannot refer to that control in the usual way. For example. forms. this code causes an error: Loop.Visible = True [Loop]. and operators (such as Or and Mod). Naming Conventions in Visual Basic While you are writing Visual Basic code.

uses variables for storing values. Using constants can make your code more readable by providing meaningful names instead of numbers. However. depending on what values the user provides. You can use two variables to hold the unknown values ³ let's name them ApplePrice and ApplesSold. For example.You can use square brackets in this way when referring to forms and controls. but as the name implies. depending on the result of the comparison. You can think of a variable as a placeholder in memory for an unknown value. The variables allow you to make a calculation without having to know in advance what the actual inputs are. your code would look like this: txtSales. Constants also store values. Variables have a name (the word you use to refer to the value the variable contains) and a data type (which determines the kind of data the variable can store). and perform different operations on them. Note Because typing square brackets can get tedious. you might want to refrain from using restricted keywords as the name of forms and controls. For example. Visual Basic uses the Variant data type. you use variables to temporarily store values during the execution of an application. . You don't know the price of an apple or the quantity sold until the sale actually occurs. Arrays can be used to store indexed collections of related variables. compare them. but you don't need to store them in a property. but not when declaring a variable or defining a procedure with the same name as a restricted keyword. Data types control the internal storage of data in Visual Basic. Visual Basic. Constants and Data Types You often need to store values temporarily when performing calculations with Visual Basic. you might want to calculate several values. Variables have a name (the word you use to refer to the value the variable contains) and a data type (which determines the kind of data the variable can store). Introduction to Variables. For more detailed information. There are a number of other available data types that allow you to optimize your code for speed and size when you don't need the flexibility that Variant provides. but you can also create your own.txt = ApplePrice * ApplesSold The expression returns a different total each time. you can use this technique if a future version of Visual Basic defines a new keyword that conflicts with an existing form or control name when you update your code to work with the new version. those values remain constant throughout the execution of an application. Square brackets can also be used to force Visual Basic to accept names provided by other type libraries that conflict with restricted keywords. Each time the program is run. By default. To calculate the total sales and display it in a Textbox named txtSales. the user supplies the values for the two variables. see: Variables In Visual Basic. imagine you are creating a program for a fruit stand to track the sales of apples. There are a number of built-in constants in Visual Basic. like most programming languages. You need to retain the values if you want to compare them.

the data type of ApplePrice is Currency. For More Information For more information on objects. see "Programming with Objects" and "Programming with Components. Form1. and so on. the value of a variable in a procedure is local to that procedure ³ that is. a form. "Data Types. Must not exceed 255 characters. Note that the equal sign in this example is an assignment operator. Data types define the type of information the variable stores. These characteristics allow you to use the same variable names in different procedures without worrying about conflicts or accidental changes. and Currency. Declaring Variables To declare a variable is to tell the program about it in advance. Variables can represent many other values as well: text values." later in this chapter. Some examples of data types include String. In addition. Integer. When the procedure finishes." Data types are discussed in detail in the section. include Object. You declare a variable with the Dim statement. Must be unique within the same scope. supplying a name for the variable: Dim variablename [As type] Variables declared with the Dim statement within a procedure exist only as long as the procedure is executing. which is the range from which the variable can be referenced ³ a procedure. There are other ways to declare variables: . the data type of ApplesSold is an integer. Storing and Retrieving Data in Variables You use assignment statements to perform calculations and assign the result to a variable: ApplesSold = 10 ' The value 10 is passed to the ' variable. Examples of Visual Basic object types. even objects. not an equality operator. A variable name: y y y y Must begin with a letter. the value of the variable disappears.In this example. Variables can also contain objects from Visual Basic or other applications. the value (10) is being assigned to the variable (ApplesSold). Can't contain an embedded period or embedded type-declaration character. and TextBox. The optional As type clause in the Dim statement allows you to define the data type or object type of the variable you are declaring. you can't access a variable in one procedure from another procedure. ApplesSold = ApplesSold + 1 ' The variable is ' incremented. or classes. various numeric types. dates.

or class module. you could write a function where you don't need to declare TempVal before using it: Function SafeSqr(num) TempVal = Abs(num) SafeSqr = Sqr(TempVal) End Function Visual Basic automatically creates a variable with that name. click the Editor tab and check the Require Variable Declaration option. But because the TempVal variable was misspelled on the next-to-last line. which you can use as if you had explicitly declared it. or standard module: Option Explicit ²or² From the Tools menu. . you must manually add Option Explicit to any existing modules within a project. standard. therefore. this function will always return zero.y Declaring a variable in the Declarations section of a form. it can't determine whether you actually meant to implicitly declare a new variable or you just misspelled an existing variable name. it can lead to subtle errors in your code if you misspell a variable name. For example. suppose that this was the function you wrote: Function SafeSqr(num) TempVal = Abs(num) SafeSqr = Sqr(TemVal) End Function At first glance. For example. makes the variable available to all the procedures in the module. but not in modules already created. this looks the same. Declaring a local variable using the Static keyword preserves its value even when a procedure ends. Declaring a variable using the Public keyword makes it available throughout your application. Explicit Declaration To avoid the problem of misnaming variables. rather than within a procedure. y y Implicit Declaration You don't have to declare a variable before using it. form. To explicitly declare variables y Place this statement in the Declarations section of a class. you can stipulate that Visual Basic always warn you whenever it encounters a name not declared explicitly as a variable. While this is convenient. When Visual Basic encounters a new name. so it creates a new variable with that name. choose Options. This automatically inserts the Option Explicit statement in any new modules.

it's a good idea to use it with all your code. Module-level Variables are private to the module in which they appear. Scoping Variables Depending on how it is declared. however. You could then explicitly declare TempVal: Function SafeSqr(num) Dim TempVal TempVal = Abs(num) SafeSqr = Sqr(TemVal) End Function Now you'd understand the problem immediately because Visual Basic would display an error message for the incorrectly spelled TemVal. and class modules. Understanding the Scope of Variables The scope of a variable defines which parts of your code are aware of its existence. Because the Option Explicit statement helps you catch these kinds of errors. standard. and class module for which you want Visual Basic to enforce explicit variable declarations. you need to use a variable with a broader scope. such as one whose value is available to all the procedures within the same module. only code within that procedure can access or change the value of that variable. it must be placed in the Declarations section of every form. Note The Option Explicit statement operates on a per-module basis. . it has a scope that is local to that procedure. You must manually add Option Explicit to any existing modules within a project. Scope Procedure-level Private Variables are private to the procedure in which they appear. When you declare a variable within a procedure. Sometimes. or even to all the procedures in your entire application.Had this statement been in effect for the form or standard module containing the SafeSqr function. but does not add it to existing code. a variable is scoped as either a procedure-level (local) or module-level variable. Visual Basic inserts Option Explicit in all subsequent form. Visual Basic allows you to specify the scope of a variable when you declare it. Visual Basic would have recognized TempVal and TemVal as undeclared variables and generated errors for both of them. Variables are available to all modules. Public Not applicable. You cannot declare public variables within a procedure. standard. If you select Require Variable Declaration.

You create module-level variables by declaring them with the Private keyword in the Declarations section at the top of the module. but Private is preferred because it readily contrasts with Public and makes your code easier to understand. but not to code in other modules. Any one procedure can alter the value in its local intTemp without affecting intTemp variables in other procedures. You declare them with the Dim or Static keywords. For example. use the Public keyword to declare the variable. These are also known as local variables. For example. you can create a dozen different procedures containing a variable called intTemp. public variables are declared in the Declarations section at the top of the module. there is no difference between Private and Dim.intX to get the correct values. The values in public variables are available to all procedures in your application. Local variables are a good choice for any kind of temporary calculation. a module-level variable is available to all the procedures in that module. it's possible to differentiate between them in code by referring to both the module and variable names. For example: Public intTemp As Integer Advanced Variable Topics Using Multiple Variables with the Same Name If public variables in different modules share the same name.intX and Form1. As long as each intTemp is declared as a local variable.Variables Used Within a Procedure Procedure-level variables are recognized only in the procedure in which they're declared. For example: Dim intTemp As Integer ²or² Static intPermanent As Integer Values in local variables declared with Static exist the entire time your application is running while variables declared with Dim exist only as long as the procedure is executing. Like all module-level variables. if there is a public Integer variable intX declared in both Form1 and in Module1. you can refer to them as Module1. . Variables Used by All Modules To make a module-level variable available to other modules. For example: Private intTemp As Integer At the module level. Variables Used Within a Module By default. each procedure recognizes only its own version of intTemp.

or Form1. Module1.intX when calling the value of the form's Integer variable. Public intX As Integer ' Declare the form's intX ' variable. Sub Test() ' Set the value for the intX variable in Module2. Sub Test() ' Set the value for the intX variable in the form. ' Calls Test in Module2.Test MsgBox Module1. Module2. intX = 2 End Sub The third intX variable is declared in the form module. ' Displays Module2's intX. is declared in the first standard module. which has the same name. Again. If there are multiple procedures and variables with the same name. Notice in the third command button's Click event procedure.intX End Sub ' Calls Test in Module1. And again. ' Displays Module1's intX.Test MsgBox Module2. intX = 1 End Sub The second variable. a procedure named Test sets its value: Public intX As Integer ' Declare Module2's intX. is declared in the second standard module. Visual Basic takes the value of the more local variable. You'll see the separate references to the three public variables. Private Sub Command3_Click() Test ' Calls Test in Form1. Private Sub Command1_Click() Module1. The Test procedure sets its value: Public intX As Integer ' Declare Module1's intX.Test when calling the form's Test procedure. Sub Test() ' Set the value for the intX variable in Module1. End Sub Run the application and click each of the three command buttons. you don't need to specify Form1. intX = 3 End Sub Each of the three command buttons' Click event procedures calls the appropriate Test procedure and uses MsgBox to display the values of the three variables.To see how this works. intX. insert two standard modules in a new project and draw three command buttons on a form. a procedure named Test sets its value. which in this case. intX. is the Form1 variable. .intX End Sub Private Sub Command2_Click() Module2. One variable. MsgBox intX ' Displays Form1's intX.

and procedures are treated as modulelevel variables in the form module. End Sub . For example. you could have a public variable named Temp and then. BackColor ' Assume there is also a control on the form called ' Text1. Me. or procedure because both are in the same scope. Within the form module. Local Variables You can also have a variable with the same name at a different scope. It is not legal to have a form property or control with the same name as a module-level variable. The module-level variable can be accessed from within the procedure by qualifying the variable with the module name.Temp to 1. within a procedure. End Sub Private Sub Command1_Click() Test End Sub In general.Temp End Sub ' Temp has a value of 2. Text1. Me.Temp has a value of 1. You must qualify the control with a reference to the form or the Me keyword to set or get its value or any of its properties. Shadowing Form Properties and Controls Due to the effect of shadowing. Text1 = "Variable" ' Variable shadows control. it is accessed in preference to) less local variables.Top = 0 ' Must qualify with Me to get ' control. References to the name Temp within the procedure would access the local variable. user-defined type. constants.Text1 = "Control" ' Must qualify with Me to get ' control. ' Form1. when variables have the same name but different scope. the more local variable always shadows (that is. declare a local variable named Temp.BackColor = 0 ' Must qualify with Me to get ' form property. constant. Public Temp As Integer Sub Test() Dim Temp As Integer Temp = 2 MsgBox Form1. controls. BackColor = 0 ' Variable shadows property. references to Temp outside the procedure would access the public variable.Top = 0 ' This causes an error! Me. Private Sub Form_Load() Temp = 1 ' Set Form1. So if you also had a procedure-level variable named Temp. form properties. it would shadow the public variable Temp within that module.Text1. local variables with the same names as controls on the form shadow the controls.Public vs. For example: Private Sub Form_Click () Dim Text1.

However. In form modules. local variables declared with Dim exist only while the procedure in which they are declared is executing. It can. types. the following function calculates a running total by adding a new value to the total of previous values stored in the static variable Accumulate: Function RunningTotal(num) Static ApplesSold ApplesSold = ApplesSold + num RunningTotal = ApplesSold End Function If ApplesSold was declared with Dim instead of Static. it is good programming practice to keep the names of your variables distinct from each other. when a procedure is finished executing. and the function would simply return the same value with which it was called. However. the procedure no longer has exclusive access to it. the previous accumulated values would not be preserved across calls to the function.Using Variables and Procedures with the Same Name The names of your private module-level and public module-level variables can also conflict with the names of your procedures. In this case. have the same name as public procedures. Usually. For example: . it must be qualified with the module name. you can preserve the value of a local variable by making the variable static. You can produce the same result by declaring ApplesSold in the Declarations section of the module. Because other procedures can access and change the value of the variable. the period of time during which they retain their value. when the variable is accessed from another module. try to use variables names that are different from names of controls on those forms. The values in module-level and public variables are preserved for the lifetime of your application. all its local variables are reinitialized. variables have a lifetime. Static Variables In addition to scope. exactly as you would with the Dim statement: Static Depth For example. the running totals might be unreliable and the code would be more difficult to maintain. shadowing can be confusing and lead to subtle bugs in your code. however. Once you change the scope of a variable this way. A variable in the module cannot have the same name as any procedures or types defined in the module. While the shadowing rules described above are not complex. however. Use the Static keyword to declare one or more variables inside a procedure. Declaring All Local Variables as Static To make all local variables in a procedure static. or variables defined in other modules. the values of its local variables are not preserved and the memory used by the local variables is reclaimed. The next time the procedure is executed. making it a module-level variable. place the Static keyword at the beginning of a procedure heading.

also provide a list of constants you can use with their objects." Symbolic or user-defined constants are declared using the Const statement. have no obvious meaning. you can't modify a constant or assign a new value to it as you can to a variable. and can be viewed in the Object Browser. or declared implicitly. Each of these elements is defined in the object library. Although a constant somewhat resembles a variable. For information on changing the priority of object libraries. For details on using the Object Browser. vbTileHorizontal. Even with prefixes. Modulename is the name of the module that defines the constant. see the "References Dialog Box. you can qualify references to constants with the following syntax: [libname. Constants from the Visual Basic and Visual Basic for applications object libraries are prefaced with "vb" ³ for instance. "Creating Your Own Constants.]constname Libname is usually the class name of the control or library. In these cases. You can place Static in front of any Sub or Function procedure heading." y In Visual Basic. and properties. you can greatly improve the readability of your code ³ and make it easier to maintain ³ by using constants. see "Programming with Objects. Constants are also defined in the object library for each ActiveX control. with a prefix indicating the object library that defines the constant. it's still possible that two object libraries may contain identical constants representing different values. methods. such as Microsoft Excel and Microsoft Project. Which constant is referenced in this case depends on which object library has the higher priority. including event procedures and those declared as Private. Creating Your Own Constants . Constname is the name of the constant.Static Function RunningTotal(num) This makes all the local variables in the procedure static regardless of whether they are declared with Static." To be absolutely sure you avoid constant name collisions. A constant is a meaningful name that takes the place of a number or string that does not change. Private. Constants Often you'll find that your code contains constant values that reappear over and over. Or you may find that the code depends on certain numbers that are difficult to remember ³ numbers that. constant names are in a mixed-case format. Other applications that provide object libraries. User-defined constants are described in the next section. in and of themselves. Dim. Visual Basic constants are listed in the Visual Basic (VB) and Visual Basic for applications (VBA) object libraries in the Object Browser. There are two sources for constants: y Intrinsic or system-defined constants are provided by applications and controls. The prefixes are intended to prevent accidental collisions in cases where constants have identical names and represent different values.][modulename.

A Const statement can represent a mathematical or date/time quantity: Const conPi = 3. see "Understanding the Scope of Variables" earlier in this chapter. y For More Information For more information regarding scope. conMaxPlanets = 9. Public constants cannot be declared in a form or class module. but not to any code outside that module.10.A" Const conCodeName = "Enigma" You can place more than one constant declaration on a single line if you separate them with commas: Public Const conPi = 3. To create a constant available throughout the application. declare it in the Declarations section of the module. and the same rules apply: y y To create a constant that exists only within a procedure.14159265358979 Public Const conMaxPlanets As Integer = 9 Const conReleaseDate = #1/1/95# The Const statement can also be used to define string constants: Public Const conVersion = "07. however.The syntax for declaring a constant is: [Public|Private] Const constantname[As type] = expression The argument constantname is a valid symbolic name (the rules are the same as those for creating variable names). You can even define constants in terms of previously defined constants: Const conPi2 = conPi * 2 Once you define constants.14. and expression is composed of numeric or string constants and operators. _ conWorldPop = 6E+09 The expression on the right side of the equal sign ( = ) is often a number or literal string. To create a constant available to all procedures within a module. you can place them in your code to make it more readable. For example: Static SolarSystem(1 To conMaxPlanets) If numPeople > conWorldPop Then Exit Sub Scoping User-Defined Constants A Const statement has scope like a variable declaration. you can't use function calls in expression. . but it can also be an expression that results in a number or string (although that expression can't contain calls to functions). and place the Public keyword before Const. declare the constant in the Declarations section of a standard module. declare it within that procedure.

For example. just about anything in Visual Basic that involves data also involves data types. Data types apply to other things besides variables. because a name is always composed of characters. at most.Avoiding Circular References Because constants can be defined in terms of other constants. a variable to store a person's name is best represented as a string data type." Declaring Variables with Data Types Before using a non-Variant variable. see the section. Visual Basic can handle that data more efficiently if you declare a variable of that type. If a cycle occurs. Double. When you assign a value to a property. For example: ' In Module 1: Public Const conA = conB * 2 ' In Module 2: Public Const conB = conA / 2 ' Available throughout ' application. "Arrays. each of which is defined in terms of the other. You don't have to convert between these types of data when assigning them to a Variant variable: Visual Basic automatically performs any necessary conversion. that value has a data type. In fact. When you declare a variable. For More Information For more information. A cycle occurs when you have two or more public constants. the variable is given the Variant data type. For example. To avoid creating a cycle. Data Types Variables are placeholders used to store values. and Currency type. however. arguments to functions also have data types. or circular reference between two or more constants. You can also declare arrays of any of the fundamental types. You cannot run your code until you resolve the circular reference." later in this chapter. String. you can also supply a data type for it. they have names and data types. The data type of a variable determines how the bits representing those values are stored in the computer's memory. respectively: . you must be careful not to set up a cycle. All variables have a data type that determines what kind of data they can store. The Variant data type is like a chameleon ³ it can represent many different data types in different situations. the following statements declare an Integer. Selecting data types to improve your application's performance is discussed in "Designing for Performance and Compatibility. Visual Basic generates an error when you attempt to run your application. a small number of modules. if you don't supply a data type. Public. By default. Dim or Static statement to declare it As type. ' Available throughout ' application. restrict all your public constants to a single module or. If you know that a variable will always store data of a particular type. you must use the Private.

or 3. it is an accurate fixed-point data type suitable for monetary calculations. the highest positive value of a Double data type is 1. declare it as a Single. declare it as an Integer or Long type.Private I As Integer Dim Amt As Double Static YourName As String Public BillsPaid As Currency A Declaration statement can combine multiple declarations. in which mmm is the mantissa and eee is the exponent (a power of 10). the variable is given the default type. Operations are faster with integers. The Byte Data Type If the variable contains binary data. Double. declare it as an array of the Byte data type. or Currency variable..57). Visual Basic may automatically convert between ANSI and Unicode when: . BillsPaid As Currency Private Test. using E in the same fashion treats the value as a Single data type. see "Introduction to Control Structures" later in this chapter.8 times 10 to the 308th power. or about 1. This may surprise you if your experience with other programming languages leads you to expect all variables in the same declaration statement to have the same specified type (in this case. the variables Test and Amount are of the Variant data type. and these types consume less memory than other data types.402823E+38. They are especially useful as the counter variables in For.79769313486232D+308. (Arrays are discussed in "Arrays" later in this chapter). Double (double-precision floating point). any binary data in the variable is corrupted. Long (long integer). When String variables are converted between ANSI and Unicode formats. but can be subject to small rounding errors. Floating-point (Single and Double) numbers have much larger ranges than Currency.4 times 10 to the 38th power. Using Byte variables to store binary data preserves it during format conversions. Integer). For More Information To read more about control structures. Likewise. The highest positive value of a Single data type is 3. Using D to separate the mantissa and exponent in a numeric literal causes the value to be treated as a Double data type. If the variable contains a fraction.Next loops. as in these statements: Private I As Integer. Numeric Data Types Visual Basic supplies several numeric data types ³ Integer. and Currency.. Amt As Double Private YourName As String. In the preceding example. Note Floating-point values can be expressed as mmmEeee or mmmDeee. Using a numeric data type generally uses less storage space than a variant. J As Integer Note If you do not supply a data type. Single (single-precision floating point). Amount. If you know that a variable will always store whole numbers (such as 12) rather than numbers with a fractional amount (such as 3. The Currency data type supports up to four digits to the right of the decimal separator and fifteen digits to the left.

Visual Basic coerces the Byte to a signed integer first. to declare a string that is always 50 characters long. a string variable or argument is a variable-length string. Visual Basic rounds off rather than truncates the fractional part of a floating-point number before assigning it to an integer. see "International Issues. In forms and class modules. fixed-length strings must be declared Private. So for unary minus. 4) By default. Visual Basic simply truncates the characters. For More Information For details on Unicode and ANSI conversions. the string grows or shrinks as you assign new data to it. EmpName is padded with enough trailing spaces to total 50 characters. Fixed-length strings in standard modules can be declared as Public or Private. You can also declare strings that have a fixed length. Because fixed-length strings are padded with trailing spaces. you may find the Trim and RTrim functions. Since Byte is an unsigned type with the range 0-255. use code like this: Dim EmpName As String * 50 If you assign a string of fewer than 50 characters. If you assign a string that is too long for the fixed-length string. . useful when working with them.y y y y Reading from files Writing to files Calling DLLs Calling methods and properties on objects All operators that work on integers work with the Byte data type except unary minus. which remove the spaces. you can declare it to be of type String: Private S As String You can then assign strings to this variable and manipulate it using string functions: S = "Database" S = Left(S." The String Data Type If you have a variable that will always contain a string and never a numeric value. it cannot represent a negative number. All numeric variables can be assigned to each other and to variables of the Variant type. You specify a fixed-length string with this syntax: String * size For example.

Text1. In the following example. RTrim Function and Trim Functions" in the Language Reference. Midnight is 0.23" intX = strY ' Passes the string to a numeric ' variable. It's also possible to assign a numeric value to a string variable. Exchanging Strings and Numbers You can assign a string to a numeric variable if the string represents a numeric value. The same general characteristics apply to dates in both types. strY = Cos(strY) ' Passes cosine to the ' string variable. 1899. For example. while values to the right of the decimal represent time. passing a non-numeric value in the string will cause a run-time error to occur. End Sub Visual Basic will automatically coerce the variables to the appropriate data type. If Recorder. Negative whole numbers represent dates before December 30. The Boolean Data Type If you have a variable that will contain simple true/false. . List1. Run the application. you can declare it to be of type Boolean. Private Sub Command1_Click() Dim intX As Integer Dim strY As String strY = "100. yes/no. values to the left of the decimal represent date information. You should use caution when exchanging strings and numbers. and list box on a form." in "Advanced Variant Topics. and click the command button. text box.For More Information See "Ltrim. place a command button." When other numeric data types are converted to Date. or on/off information. Dim blnRunning As Boolean ' Check to see if the tape is running. "Date/Time Values Stored in Variants. Enter the following code in the command button's Click event. blnRunning is a Boolean variable which stores a simple yes/no setting.Text = strY ' String variable prints in ' the text box. and midday is 0.5.AddItem Cos(strY) ' Adds cosine of number in ' the string to the listbox.Direction = 1 Then blnRunning = True End if The Date Data Type Date and time values can be contained both in the specific Date data type and in Variant variables. For More Information See the section. The default value of Boolean is False.

Visual Basic can resolve references to the properties and methods of objects with specific types before you run an application. allowing the reference to be resolved at run time. A variable declared as Object is one that can subsequently be assigned (using the Set statement) to refer to any actual object recognized by the application. Dim objDb As Object Set objDb = OpenDatabase("c:\Vb5\Biblio. For More Information For more information on creating and assigning objects and object variables. declare objects as they are listed in the Classes list in the Object Browser. instead of using a Variant or the generic Object. When working with other applications' objects. for example. This ensures that Visual Basic recognizes the specific type of object you're referencing. try to use specific classes (such as TextBox instead of Control or. in the preceding case.The Object Data Type Object variables are stored as 32-bit (4-byte) addresses that refer to objects within an application or within some other application. see "Creating Objects" later in this chapter. To convert a value to Currency. you use the CCur function: PayPerWeek = CCur(hours * hourlyPay) Conversion function Cbool Cbyte Ccur Cdate CDbl Cint CLng CSng Boolean Byte Currency Date Double Integer Long Single Converts an expression to . Database instead of Object) rather than the generic Object. This allows the application to perform faster at run time.mdb") When declaring object variables. Specific classes are listed in the Object Browser. Converting Data Types Visual Basic provides several conversion functions you can use to convert values into a specific data type.

CStr Cvar CVErr String Variant Error Note Values passed to a conversion function must be valid for the destination data type or an error occurs. Visual Basic automatically performs any necessary conversion. The Empty value is a special value different from 0. For More Information See the Language Reference for a specific conversion function.character string). see the section. if you attempt to convert a Long to an Integer. Variants can also contain three special values: Empty. y If you perform arithmetic operations or functions on a Variant. SomeValue = SomeValue . ' SomeValue contains "17" (a two' character string). see the section. The Variant Data Type A Variant variable is capable of storing all system-defined types of data. the Long must be within the valid range for the Integer data type. A Variant variable has the Empty value before it is assigned a value. You can test for the Empty value with the IsEmpty function: If IsEmpty(Z) Then Z = 0 . "Numeric Values Stored in Variants." in "Advanced Variant Topics. "Strings Stored in Variants. there are some traps you must avoid. The Empty Value Sometimes you need to know if a value has ever been assigned to a created variable. For details. For example. While you can perform operations on Variant variables without much concern for the kind of data they contain. use the & operator instead of the + operator." If you are concatenating strings. a zero-length string ("").15 ' SomeValue now contains ' the numeric value 2. For details. or the Null value. You don't have to convert between these types of data if you assign them to a Variant variable. and Error." in "Advanced Variant Topics. Null. For example: Dim SomeValue SomeValue = "17" ' Variant by default." y In addition to being able to act like the other standard data types. the Variant must contain something that is a number. SomeValue = "U" & SomeValue ' SomeValue now contains ' "U2" (a two.

Passing Null. The Error Value In a Variant. You can set a Variant variable back to Empty by assigning the keyword Empty to the Variant. Null is said to "propagate" through expressions. a zero-length string. see "Null" in the Language Reference. Null is commonly used in database applications to indicate unknown or missing data. Variables are not set to Null unless you explicitly assign Null to them. The Null Value The Variant data type can contain another special value: Null. if any part of the expression evaluates to Null. you can use it in expressions. a Variant containing Null. so if you don't use Null in your application. Assigning Null to a Variant variable doesn't cause an error. y y You can also assign Null with the Null keyword: Z = Null You can use the IsNull function to test if a Variant variable contains Null: If IsNull(X) And IsNull(Y) Then Z = Null Else Z = 0 End If If you assign Null to a variable of any type other than Variant. the entire expression evaluates to Null. depending on the expression. a trappable error occurs.When a Variant contains the Empty value. and Null will propagate through expressions involving Variant variables (though Null does not propagate through certain functions). This allows you. Null values propagate through intrinsic functions that return Variant data types. unlike for other kinds of errors. normal application-level error handling does not occur. to take some alternative based on the error value. Error is a special value used to indicate that an error condition has occurred in a procedure. Null has some unique characteristics: y Expressions involving Null always result in Null. you don't have to write code that tests for and handles it. or Null) is assigned to a Variant variable. Because of the way it is used in databases. For More Information For information on how to use Null in expressions. . or the application itself. However. You can return Null from any Function procedure with a Variant return value. or an expression that evaluates to Null as an argument to most functions causes the function to return Null. Thus. Error values are created by converting real numbers to error values using the CVErr function. it is treated as either 0 or a zero-length string. The Empty value disappears as soon as any value (including 0.

For details on converting data types. however.For More Information For information on how to use the Error value in expressions. Most of the time." For additional information about the Variant data type. see "Debugging Your Code and Handling Errors. For More Information For information about the VarType function. For information on error handling. For example. in these cases. the value of VarType is the sum of the array and data type return values. and arrays are not physically stored in the Variant. or even to Currency: If VarType(X) = 5 Then X = CSng(X) ' Convert to Single. if you store values with decimal fractions in a Variant variable.) These internal representations correspond to the explicit data types discussed in "Data Types" earlier in this chapter. it is a variable that can freely change its type. Visual Basic always uses the Double internal representation. Visual Basic uses the most compact representation that accurately records the value. . you don't have to be concerned with what internal representation Visual Basic is using for a particular variable. see "Advanced Variant Topics Advanced Variant Topics Internal Representation of Values in Variants Variant variables maintain an internal representation of the values that they store. If you know that your application does not need the high accuracy (and slower speed) that a Double value supplies. see "CVErr Function" in the Language Reference. rather. (A Variant variable is not a variable with no type. no matter what you store in it. This representation determines how Visual Basic treats these values when performing comparisons and other operations. see "VarType Function" in the Language Reference. so any code you write that makes decisions based on the return value of the VarType function should gracefully handle return values that are not currently defined. you can use the VarType function. To read more about arrays. The actual data are stored elsewhere. With an array variable. Objects. If you want to know what value Visual Basic is using. you can speed your calculations by converting the values to Single. see "Data Types" earlier in this chapter. or a pointer to the string or array. four bytes of the Variant are used to hold either an object reference. Later operations may cause Visual Basic to change the representation it is using for a particular variable. When you assign a value to a Variant variable. For example. Note A variant always takes up 16 bytes. this array contains Double values: Private Sub Form_Click() Dim dblSample(2) As Double MsgBox VarType(dblSample) End Sub Future versions of Visual Basic may add additional Variant representations. see "Arrays" later in this chapter. strings. Visual Basic handles conversions automatically.

Visual Basic converts the representation of the number to a string automatically. you cannot perform any arithmetic operations on the value U2 even though it contains a numeric character.Numeric Values Stored in Variants When you store whole numbers in Variant variables. thousands separator.50") While these two statements would return false: IsNumeric("DM100") IsNumeric("1. Visual Basic provides several conversion functions that you can use to convert values into a specific type (see "Converting Data Types" earlier in this chapter). the reverse would be the case ³ the first two would return false and the second two true ³ if the country setting in the Windows Control Panel was set to Germany.560.50") However. Canada. The Format function . and decimal separator symbols. you use the CCur function: PayPerWeek = CCur(hours * hourlyPay) An error occurs if you attempt to perform a mathematical operation or function on a Variant that does not contain a number or something that can be interpreted as a number. For example. Likewise. Sometimes you want to use a specific representation for a number. if it is very large or has a fractional component. Visual Basic uses the most compact representation possible. it uses the Regional settings (specified in the Windows Control Panel) to interpret the thousands separator.560. Visual Basic will use a Long value or. For example. the Variant uses an Integer representation for the value. these two statements would return true: IsNumeric("$100") IsNumeric("1. you can perform calculations on the values +10 or -1. or Australia. If you assign a Variant containing a number to a string variable or property. Thus. For example. For this reason. The IsNumeric function performs this task: Do anyNumber = InputBox("Enter a number") Loop Until IsNumeric(anyNumber) MsgBox "The square root is: " & Sqr(anyNumber) When Visual Basic converts a representation that is not numeric (such as a string containing a number) to a numeric value. and currency symbol. because the entire value is not a valid number. a Double value.7E6 because they are valid numbers. To convert a value to Currency. You can also use the Format function to convert a number to a string that includes formatting such as currency. you often want to determine if a Variant variable contains a value that can be used as a number. If you want to explicitly convert a number to a string. you cannot perform any calculations on the value 1040EZ. for example. if you store a small number without a decimal fraction. however. decimal separator. If you then assign a larger number. use the CStr function. you might want a Variant variable to store a numeric value as Currency to avoid round-off errors in later calculations. if the country setting in the Windows Control Panel is set to United States.

use the & operator.automatically uses the appropriate symbols according to the Regional Settings Properties dialog box in the Windows Control Panel. regardless of the representation of the value in the variables. For More Information See "Format Function" and topics about the conversion functions in the Language Reference. it generates a Type mismatch error." . see "International Issues. however. Several functions return date/time values. 1) . the + operator adds the two values. then the + operator performs string concatenation. As mentioned earlier. For more information on Unicode. Visual Basic first attempts to convert the string into a number. the following code: Sub Form_Click () Dim X. the situation becomes more complicated. If both of the Variants contain strings. the + operator performs addition.Hour(rightnow) minutesleft = 60 . X & Y End Sub produces this result on the form: 67 13 67 67 Note Visual Basic stores strings internally as Unicode. To make sure that concatenation occurs.Minute(rightnow) Print daysleft & " days left in the year. if unsuccessful. storing and using strings in Variant variables poses few problems. daysleft = Int(DateSerial(Year(rightnow) _ + 1. If the conversion is successful. For information on writing code for applications that will be distributed in foreign markets." Strings Stored in Variants Generally. minutesleft rightnow = Now ' Now returns the current date/time. sometimes the result of the + operator can be ambiguous when used with two Variant values. X & Y X = 6 Print X + Y. If both of the Variants contain numbers. hoursleft. DateSerial returns the number of days left in the year: Private Sub Form_Click () Dim rightnow. For example. For example.rightnow) hoursleft = 24 . daysleft." Date/Time Values Stored in Variants Variant variables can also contain date/time values. But if one of the values is represented as a number and the other is represented as a string. see "International Issues. 1. Y X = "6" Y = "7" Print X + Y.

adding or subtracting fractions adds or subtracts time." Print minutesleft & " minutes left in the hour." End Sub You can also perform math on date/time values. For example. you can compare a Variant containing a date/time value with a literal date: If SomeDate > #3/6/93# Then Similarly. while subtracting 1/24 subtracts one hour. For example.Text) daysleft = DateSerial(Year(SomeDate) + _ 1. to December 31. If you do not include a date in a date/time literal. earlier or later in other countries) will be incorrect. These are all valid date/time values: SomeDate SomeDate SomeDate SomeDate = = = = #3-6-93 13:20# #March 27. Calculations on dates don't take into account the calendar revisions prior to the switch to the Gregorian calendar. 0100. The range for dates stored in Variant variables is January 1. however. see "International Issues. you can use the IsDate function to determine if a Variant contains a value that can be considered a valid date/time value. Visual Basic sets the date part of the value to December 30.Text = daysleft & " days left in the year. Visual Basic converts the text into a date and computes the days left until the end of the year: Dim SomeDate. 9999.Print hoursleft & " hours left in the day. 1. so calculations producing date values earlier than the year in which the Gregorian calendar was adopted (1752 in Britain and its colonies at that time. If the property contains text that can be considered a valid date.Text) Then SomeDate = CDate(Text1. Therefore. the following code tests the Text property of a text box with IsDate. daysleft If IsDate(Text1. 1993 1:20am# #Apr-2-93# #4 April 1993# For More Information For information on handling dates in international formats. 1) . adding 20 adds 20 days. Adding or subtracting integers adds or subtracts days. You can then use the CDate function to convert the value into a date/time value. Visual Basic accepts a wide variety of date and time formats in literals. Visual Basic sets the time part of the value to midnight (the start of the day). you can compare a date/time value with a complete date/time literal: If SomeDate > #3/6/93 1:20pm# Then If you do not include a time in a date/time literal.SomeDate Text2. You can use date/time literals in your code by enclosing them with the number sign (#)." . 1899." In the same way that you can use the IsNumeric function to determine if a Variant variable contains a value that can be considered a valid numeric value. in the same way you enclose string literals with double quotation marks ("").

"Creating Your Own Data Types. see "Date Function" in the Language Reference. all the elements in an array must have the same data type. and so on). including user-defined types (described in the section. Setting the data type of an array to Variant allows you to store objects alongside other data types in an array. numbers.Text & " is not a valid date. They are different from the control arrays you specify by setting the Index property of controls at design time. use the Private statement in the Declarations section of a module to declare the array.Else MsgBox Text1. You can declare an array of any of the fundamental data types. Objects Stored in Variants Objects can be stored in Variant variables. Arrays of variables are always contiguous. Arrays allow you to refer to a series of variables by the same name and to use a number (an index) to tell them apart. Declaring Fixed-Size Arrays There are three ways to declare a fixed-size array. the individual elements may contain different kinds of data (objects. This can be useful when you need to gracefully handle a variety of data types. you cannot load and unload elements from the middle of the array." End If For More Information For information about the various date/time functions. unlike control arrays. To create a module-level array. including objects. Of course. y y Setting Upper and Lower Bounds . depending on the scope you want the array to have: y To create a public array. when the data type is Variant. In Visual Basic there are two types of arrays: a fixed-size array which always remains the same size. strings. declared in code." in "More About Programming") and object variables (described in "Programming with Objects"). Because Visual Basic allocates space for each index number. and a dynamic array whose size can change at run-time. Arrays have both upper and lower bounds. use the Public statement in the Declarations section of a module to declare the array. you're probably familiar with the concept of arrays. Dynamic arrays are discussed in more detail in the section "Dynamic Arrays" later in this chapter. Arrays If you have programmed in other languages. use the Private statement in a procedure to declare the array. For example. avoid declaring an array larger than necessary. This helps you create smaller and simpler code in many situations. To create a local array. Note The arrays discussed in this section are arrays of variables. because you can set up loops that deal efficiently with any number of cases by using the index number. All the elements in an array have the same data type. and the elements of the array are contiguous within those bounds.

When declaring an array. these array declarations can appear in the Declarations section of a module: Dim Counters(14) As Integer Dim Sums(20) As Double ' 15 elements. To create a public array.647).147. The following code creates two arrays. provide it explicitly (as a Long data type) using the To keyword: Dim Counters(1 To 15) As Integer Dim Sums(100 To 120) As String In the preceding declarations.483. and populate it with other arrays of different data types. follow the array name by the upper bound in parentheses.147. For example. with index numbers running from 0 to 20. the index numbers of Counters range from 1 to 15. Dim countersB(5) As String For intX = 0 To 4 countersB(intX) = "hello" Next intX Dim arrX(2) As Variant ' Declare a new two-member ' array.483. ' 21 elements. It then declares a third Variant array and populates it with the integer and string arrays.648 to 2. To specify a lower bound. and the index numbers of Sums range from 100 to 120. one containing integers and the other strings. Arrays that Contain Other Arrays It's possible to create a Variant array. ' Declare and populate an integer array. The second creates an array with 21 elements. The upper bound cannot exceed the range of a Long data type (-2. Private Sub Command1_Click() Dim intX As Integer ' Declare counter variable. arrX(2) = countersB() MsgBox arrX(1)(2) ' Display a member of each . The default lower bound is 0. Dim countersA(5) As Integer For intX = 0 To 4 countersA(intX) = 5 Next intX ' Declare and populate a string array. arrX(1) = countersA() ' Populate the array with ' other arrays. with index numbers running from 0 to 14. you simply use Public in place of Dim: Public Counters(14) As Integer Public Sums(20) As Double The same declarations within a procedure use Dim: Dim Counters(14) As Integer Dim Sums(20) As Double The first declaration creates an array with 15 elements.

the following statement declares a two-dimensional 10-by-10 array within a procedure: Static MatrixA(9. to keep track of each pixel on your computer screen. This can be done using a multidimensional array to store the values. 1 To 10) As Double You can extend this to more than two dimensions.' array. you can declare arrays of multiple dimensions. For example: Dim MultiD(3. 1 To 10) As Double For I = 1 To 10 For J = 1 To 10 MatrixA(I. Be especially careful with Variant arrays. 9) As Double Either or both dimensions can be declared with explicit lower bounds: Static MatrixA(1 To 10. J) = I * 10 + J Next J Next I For More Information For information about loops. see "Loop Structures" later in this chapter. MsgBox arrX(2)(3) End Sub Multidimensional Arrays Sometimes you need to keep track of related information in an array. so use multidimensional arrays with care. 1 To 15) This declaration creates an array that has three dimensions with sizes 4 by 10 by 15. you need to refer to its X and Y coordinates. The total number of elements is the product of these three dimensions. these statements initialize every element in MatrixA to a value based on its location in the array: Dim I As Integer. or 600. the total storage needed by the array increases dramatically. For example. . For example. 1 To 10. Using Loops to Manipulate Arrays You can efficiently process a multidimensional array by using nested For loops. Note When you start adding dimensions to an array. With Visual Basic. because they are larger than other data types. J As Integer Static MatrixA(1 To 10. For example.

Sign up to vote on this title
UsefulNot useful