Clearly Visual Basic: Programming with Microsoft Visual Basic · Read more Upgrading Microsoft Visual Basic to Microsoft Visual lesforgesdessalles.info 6 / Microsoft® Visual Basic® Developer's Workshop What's Been Left Out Introductory material on the history of Basic has been left out of this book. Visual Basic 6 Black Book - Free ebook download as PDF File .pdf), Text File . txt) or read book online for free.
|Language:||English, Spanish, Indonesian|
|Genre:||Politics & Laws|
|ePub File Size:||24.62 MB|
|PDF File Size:||15.16 MB|
|Distribution:||Free* [*Regsitration Required]|
PDF Drive is your search engine for PDF files. As of today we have 78,, eBooks for you to download for free. No annoying ads, no download limits, enjoy . Title Introduction: Visual BASIC ; Author(s) Gary Haggard, Wade Steven Holzner, Lou Tylee; Publisher: Bookboon (); ebook PDF, pages, MB . Visual Basic ” They are not intended to be a Microsoft Visual Basic Language Reference Manual Example Accessing the Books Database.
Its tempting to set up a global variable, intNumberBalloons, which you fill in the dialog box when the user clicks on the OK button. Well begin the chapter by getting an overview of Visual Basic forms. Move Command1. Select the Align item in the Format menu, opening the Align submenu, as shown in Figure 2. Format Yields This on January 1, at 1:
Heres a list of those menus and what they do: Note that one important job of the File menu is to create EXE files for your program.
Well see a great deal more about these menus and the items they contain in the Immediate Solutions section of this chapter. This toolbar contains buttons matching popular menu items, as you can see in Figure 2.
Besides the main toolbar, you can also display other dockable toolbars in Visual Basic: To display one of these toolbars, just select it using the Toolbars item in the View menu; the toolbar appears.
If youre unsure what a particular tool in the toolbar does, just rest the mouse over it. A tool tip a small yellow window displaying text will display the tools purpose. Form Designers And Code Windows The last parts of the IDE that well take a look at in our overview are form designers and code windows, which appear in the center of Figure 2.
Form designers are really just windows in which a particular form appears. You can place controls into a form simply by drawing them after clicking the corresponding controls tool in the toolbox. Code windows are similarly easy to understand: There are two drop-down list boxes at the top of the code window: That completes our overview of the IDE.
Lets get into the actual meat of the chapter now, task by task. The Visual Basic IDE comes with all kinds of preset colorsblue for keywords, green for comments, black for other code, and so on. But as when you move into a new house, you might want to do your own decorating. Visual Basic allows you to do that. Here are the text items whose colors you can select: You can also set text font and font sizes in the same wayjust specify the new setting and click on the OK button to customize the text the way you want it.
Visual Basic is very If youve got a number of controls that should be aligned in a straight line, it can be murder to have to squint at the screen, aligning those controls in a line down to the very last pixel. Fortunately, theres an easier way to do it: Hold down the Ctrl key and click all the controls you want to align.
Make sure you have one control in the correct position, and click that one last. Sizing handles, the eight small boxes that you can grasp with the mouse to resize a control, appear around all the clicked controls. The sizing handles appear hollow around all but the last control you clicked, as shown in Figure 2.
The other controls will be aligned using this key controls position. To align all the selected controls to the same left, right, or center position of the key control, you continue with these steps: Select the Align item in the Format menu, opening the Align submenu, as shown in Figure 2.
Select the type of alignment you want in the Align submenu: While the controls are still collectively selected, you can move them, if you like, as a group to any new location now that they are aligned as you want them. To size all selected controls the same as the key control, follow Steps 1 and 2, and then continue this way: Choose the appropriate item in the Make Same Size submenu to size the controls as you want them: To space multiple controls vertically or horizontally, follow Steps 1 and 2 and then continue: Select the Horizontal Spacing or Vertical Spacing item in the Format menu, opening that submenu, as shown in Figure 2.
To space the controls horizontally or vertically, select one of the items in the corresponding submenu: The grid is made up of the array of dots you see on a form at design time.
This grid is to help you place controls on a form, and by default, controls are aligned to the grid which means they are sized to fit along vertical and horizontal lines of dots. You can change the grid units in twips in the Options box when you click the General tab, as shown in Figure 2.
To open the Options box, select the Options item in the Tools menu. Figure 2. Besides setting the units of the grid, you can also specify whether or not controls.
Visual Basic programs mean windows, right? Not necessarily. Visual Basic programs do not need to have any windows at all, in fact. That case is a little extreme, but there are times when you dont want to start your program with code in a form.
For example, you might want to display a flash screen when your program first starts, without waiting for the first possibly complex form to load, and then switch to the form when it does load. Follow these steps: Select the Properties item in the Project menu to open the Project Properties box, as shown in Figure 2. Add this code to the new modules General section in the code window:.
Sub Main End Sub 5. Place the code you want in the Main subroutine. Selecting The Startup Form On the other hand, you might have a number of forms in a projecthow do you specify which one is displayed first? You do that with the General tab of the Project Properties box, just as weve added a Main subroutine to our program. To specify the startup form for a project, just open the Project Properties box as we ve done in the previous section and select the appropriate form in the Startup Object box, as shown in Figure 2.
Now when your program starts, that form will act as the startup form. Youre designing a new program, and you want a form with a complete File menu on it.
You dont want to use the Application Wizard, because that add-in would redesign your whole project for you. Rather than designing a complete standard File menu from scratch, theres an easier way: To add one of the predefined Visual Basic menus, follow these steps: Select the form you want to add the menu to by clicking it with the mouse. Open the Visual Component Manager from the Tools menu.
If your version of Visual Basic does not come with the Visual Component Manager, refer to the discussion after these steps. Open the Templates folder in the Visual Basic folder. Open the Menus folder in the Templates folder, as shown in Figure 2. Select the type of menu you want and double-click it.
These are the available menus: The new menu will be added to the form you selected, as shown in Figure 2. Besides menus, you can add a whole selection of predefined forms to your projects by finding the Forms folder in the Templates folder in the Visual Component Manager.
Here are the available forms, ready to be added to your project with a click of the mouse: For example, to add a predefined form to your project, just select Add Form from the Project menu, opening the Add Form dialog box, as shown in Figure 2. As you can see, the predefined forms are here, so you can add them to your project with a simple click of the mouse.
Adding menus is a little different here, because you actually add a whole new form with that menu, instead of adding that menu to an already-existing form. For example, to add a new form with a File menu already in place, click the Existing tab in the Add Form dialog box, click the Menus folder, and double-click the Filemenu. This adds a new form to your project, complete with File menu.
However, the user is a little puzzled. He can do that by interrogating the files version information. A programs version information includes more than just the version number of the program; it also can include the name of the company that makes the software, general comments to the user, legal copyrights, legal trademarks, the product name, and the product description.
All these items are available to the user, and if youre releasing your software commercially, you should fill these items in. Heres how you do it: Select the Make tab, as shown in Figure 2.
Fill in the information you want, including the programs version number, product name, and so on. To look at the version information in CDU As you can see in Figure 2. Sometimes, version information is all that users have to go on when they encounter your program, so be sure to include it before releasing that product. The stockholders meeting is in five minuteshow can you change your EXE files name? To set the EXE files name, you just set the projects name. Select the General tab in the Project Properties box if its not already selected.
Enter the name of the project you want to use, such as CDU in Figure 2. Now youve named your EXE file, but how do you set the programs icon that will appear in Windows? The programs icon is just the icon of the startup form, and you can set that by setting that forms Icon property in the Properties window. If you have a new icon in ICO file format, you can load that icon right into that form by setting the forms Icon property to the ICO file name. By default, Visual Basic displays one toolbar, the standard toolbar.
However, there are other toolbars availablethe Debug, Edit, and Form Editor toolbars. If you want them, you add those toolbars with the Toolbars submenu of the Visual Basic View menujust click the new toolbar you want to add.
You can also remove one or all toolbars the same way. The Debug toolbar has the following buttons: When you use arrays, Visual Basic checks to make sure that you dont inadvertently try to access memory past the end or before the beginning of the array when the program runs, which is an error that could corrupt memory. In the early days of programming, however, you could use array index values that were past the end of an array without causing a compiler error, and some programmers used to rely on that to create some programming tricks involving accessing memory far beyond what they were supposed to stick with especially in C, where the name of an array is really a pointer.
That practice is heavily discouraged today, but some programmers must still have a soft spot for it, because Visual Basic allows you to turn off array bounds checking. In fairness, there are one or two other reasons you might want to turn off bounds checking, such as not having the program halt for bounds violations while youre trying to track down a bug or, conceivably, for performance reasons.
What does a bounds violation look like? Heres an example in code where we set up an array and then try to access a location past the end of it:.
End Sub If you were to run this code, youd get the error box shown in Figure 2. You can turn off bounds checking by following these steps: Select the Properties item in the Project menu to open the Project Properties box.
Select the Compile tab in the Project Properties window. Select the Remove Array Bounds Checks checkbox to turn off array bounds checking. Thats itnow youve turned off array bounds checking. Before turning off array bounds checking, however, make sure you have a really good reason for doing so; you may find your program crashing Windows as it makes illegal use of memory.
Some time ago, one version of the Intel Pentium suffered from a well-publicized hardware bug in the floating point instruction named FDIV. Intel responded quickly and offered to replace the defective chips, but its reasonable to expect some are still out there.
For that reason, Visual Basic has a check to make sure the Pentium your program runs on is safe. That check is enabled by default, but if for some reason you want to turn it off although it is hard to see why you would , you can turn off the Pentium FDIV check with these steps: Click the Advanced Optimizations button in the Project Properties window to open the Advanced Optimizations box as shown earlier in Figure 2.
Although you might want to do this yourself if you know what youre doing, its not recommended that you do this in any software you release commercially.
The deadline for your project is fast approaching, and the pressure is on. Suddenly it occurs to you that youve already written a lot of the components you need to use the day is saved! But how can you access those components? One easy way is to use the Visual Component Manager. How do you add it?
Heres how to use the Add-In Manager: The Add-In Manager opens, as shown in Figure 2. Select the add-ins you want, as also shown in Figure 2. Thats itnow youve added the add-in you want. To remove it, simply deselect the add-ins box in the Add-In Manager.
Some add-ins have an annoying habit of starting when Visual Basic starts, grinding on for a long time while it loads and taking up a lot of memory, which can be annoying if you dont need the add-in any more. Been away from Visual Basic for a while and need to get back into the swing of things?
Youve been designing your project but suddenly realize you need a Microsoft Grid control. Thats an ActiveX controlhow do you add those again? Use the Add File To Project menu item? Double-click the toolbox and hope an Insert dialog box comes up? Add a reference to the actual Grid controls OCX file, asctrls. None of thoseheres how you do it: Select the Project menus Components item. The Visual Basic Components box opens, as shown in Figure 2.
Select the ActiveX control you want to add in the Components box, then close the Components box. The new control will appear in the toolbox. If the ActiveX control you want to add to a Visual Basic project doesnt appear in the Components dialog box, it may not have been registered with Windows properly. Try using the regsvr You can also add insertable objects like Microsoft Word or Microsoft Excel objects to a Visual Basic project by using the Components dialog box.
Instead of the Controls tab in the Components box, however, you use the Insertable Objects tab and select the object you want; that object will appear in the toolbox, and you can use it in your project from then on. For example, weve inserted an Excel worksheet into the Visual Basic project in Figure 2. Visual Basic might be nice, but its just not set up as youd like it. You might think, for example, that the Start menu itemto run programssurely should be in the Edit menu.
Well, if youd like to place it there, its possible just dont expect anyone else to be able to use Visual Basic after youve customized it that way Heres how you move items between menus or toolbars: Right-click the menu bar to open the Customize box. Next, find the menu item you want to add to another menu or to a toolbar; here, well move the Start menu item to the Edit menu.
Using the mouse, drag the menu item from the Customize dialogs Command box to the new location in a menu or a toolbar, as shown in Figure 2. Releasing the mouse adds the menu item to its new location.
Finally, click Close in the Customize box to close that dialog. Besides moving menu items to new locations in menus and toolbars, you can also move whole menus. For example, to move the Edit menu in the menu bar, just open the Customize box and find the Built-in Menus item in the Categories box of the Commands tab. Next, drag the menu you want to movesuch as the Edit menufrom the Commands box to its new location in the menu bar. You can move menus to either the menu bar or other toolbars this way.
If you use one particular menu item a lot, you might consider moving it directly into the menu bar where it will appear among all the menu names. You can do that the same way youd drag that item to a new menujust drag it into the menu bar instead. The toolbars in Visual Basic are dockable, of course, so that means you can move them around as youd likeeven above the menu bar. Just grasp the double upright bars at left in the toolbar Visual Basic uses Explorer-style toolbars and move the toolbar to its new location.
You can set the forms Left and Top properties if you like, but there s an easier and more interactive way using the Form Layout window. This window appears in Figure 2. Setting a forms initial position couldnt be easierjust drag the form into the new location using the mouse. If you want to know the forms exact new position, watch the first set of numbers in the toolbarthose numbers record the location of the upper left of the form in twips.
Using the Form Layout window, you can even place forms off screen, beyond the edges of the display. That means, of course, that if you want to see the form when the program runs, youll have to move it, either by setting its Left and Top properties or with the Move method.
These features are as follows: This is a useful feature that can save you time looking up parameter order or type. The Auto List Members feature lists the members of an object as youre typing the objects name actually when you type the dot [. This is useful if you cant remember exactly what property you want to work with for example, do I want the Text property, or was it the Caption.
Visual Basic Data Tips are tip tools that appear while youre debugging a program, and theyre a truly useful innovation. When Visual Basic is in the Debug state, you can let the mouse rest over a variable name in your code, and Visual Basic will display that variables current value in a Data Tip, as shown in Figure 2. Note that Data Tips can only display the values of simple variables, not complex ones like objects or arrays.
For those objects, you must use either the Immediate window or the Watch window. Syntax Checking speaks for itselfwhen you move the text insertion point away from a line of Visual Basic code while writing that code, Visual Basic will check the lines syntax and display an error box if there is an error. That can get annoying if youre the type of programmer who likes to move around in a file while writing code What was the name of that variable again?
You can turn all of these features on and off following these steps: Select the Options item in the Tools menu. Select the Editor tab in the Options box, as shown in Figure 2.
Select the options you want from the checkboxes: Thats all it takes. Youre feeling crampedis it your chair? Your office? No, this time, its your screen. With the proliferation of windows in the Visual Basic IDE, there seems to always be more and more of them clamoring for your attention. Want to clear some IDE windows out to make room for the important ones? Just close the windows by clicking their close buttons the button marked x in the top right of the window. Whoopsnow you need the Form Layout window back.
But how do you get it back? Or how would you get the toolbox back if it disappeared? Or the Properties window? The solution is easy: All you have to do is to select the window you want to show again in the View menu, and itll reappear.
Open the View menu as shown in Figure 2. This is a simple task indeed, but its worth including here; more than one programmer has panicked after closing the toolbox by mistake and wondering if Visual Basic must be reinstalled to get it back! Forms, modules, class modules, MDI formshow are you supposed to keep them all straight?
These days, there are more files than ever in a Visual Basic project, and anything that can give you an overview can help. The Project Explorer is one such tool. This window gives you an overview of your entire project, organized into folders. However, there are times when thats not good enoughtimes when you need more details. One such occasion is when you want to find all the occurrences of specific text throughout an entire projectfor example, you might want to find all the places a particularly troublesome variable is used.
To do that, you can now just use the Edit menus Find item. Selecting that item opens the Find box, as shown in Figure 2. Now you can search all the code in an entire project if the code window is openjust click the Current Project option button before searching, as shown in Figure 2.
Even if youre familiar with searching for text throughout an entire project, theres. To jump to a variables or procedures definition, just right-click that variable or procedure any place its used in the code. Doing so opens a pop-up menu, as shown in Figure 2. To jump to the variables or procedures definition, just select the Definition item in the pop-up menu. This is very useful when, for example, youve set up a new procedure somewhere but cant quite remember what parameters you pass to that procedure, and in what order.
Besides jumping to a variable or procedures definition in code, you can also jump to its previous use in codejust select the pop-up menus Last Position item. Your project works the way you want it, but now the users are complaining about the size of the EXE file. Isnt there any way to make it less than MB? Well, that might be a bit of an exaggeration, but Visual Basic does let you optimize your project in several different ways, and one of them is to optimize the code for size.
To optimize your program for code size or speed, follow these steps: Select the Properties item in the Visual Basic Project menu. The Project Properties box opens, as shown in Figure 2. Select the Compile tab in that box. Select the kind of code optimization you want in the " Properties box: The Pentium Pro is currently the only processor Visual Basic lets you optimize for, but it does have one automatic check: Your project is nearly finished.
Now its time to add an About dialog box. So how do you add new forms to a project? You do that in one of a couple of ways: First, you can use the View menu, as shown in Figure 2. The Visual Basic Project menu allows you to add these items to a project: The Add submenu opens, and it holds the same items.
These designers let you design new objects that are part of your project. Select the Components item in the Project menu, opening the Components box as shown in Figure 2. Select the Designers tab in the Components box. Select the designer you want to add, such as the Add-In Designer, and close the Components box. You can reach the new object designer to design the addition to your project with the Add ActiveX Designer item in the Project menu.
That item opens a submenu. Its been a long night and its nearly dawn, but youre still programming because the deadlines in a few hours. Now youve lost your place in the dozen separate code files that make up the project. There are 10 separate windows open in the IDE and youre switching back and forth between them.
Isnt there a better way to mark a location and jump back to it when you need to? There certainly isyou can use a bookmark. You mark a line of code by toggling a bookmark on or off at that location, and when youre ready you can jump back to that bookmark.
Setting Bookmarks You set a bookmark at a particular line of code by clicking that line of code and selecting the Toggle Bookmark item in the Bookmarks submenu of the Edit menu, as shown in Figure 2. Selecting this same item again would remove the bookmark. Jumping To A Bookmark Now that youve set a bookmark and moved away from it while editing your code, how do you get back to it? You jump back to a bookmark with the two items in the Bookmarks submenu marked Next Bookmark and Previous Bookmark.
It would be convenient if Visual Basic allowed you to name bookmarks and select from a list of them where to jump to; perhaps that will appear in some future version of Visual Basic.
One of the best ways of getting an overview of your project is to use the Object Browser. The Object Browser is very useful to get overviews, especially in larger projects. If your version of Visual Basic includes the Visual Basic Object Browser, you open it by selecting the Object Browser item in the View menu or by clicking its icon in the toolbar.
The Object Browser opens, as shown in Figure 2. You can scan through all the objects in the project by moving up and down in the. Classes list. When you find the type of object you want to examine, select it; its properties and methods appear in the Members pane, as also shown in Figure 2. If you want to learn more about a property or method, just select it with the mouse; youll see an explanation of the property or method and the list of parameters for methods.
The Visual Basic Language. In Depth This chapter is all about what makes the various parts of a Visual Basic program work: In this chapter, well see the components of the Visual Basic language and how to use them.
After designing and creating the interface for your application using the Visual Basic IDE, and filling your program with forms and controls, youll need to write the code that makes those controls and forms do something.
The Visual Basic language supports a large number of programming constructs and elements, and that language is the foundation on which well build in this book. A good start here is essential for the work well do throughout the book.
If youve programmed in other languages, much of the material in this chapter will probably be familiar to youand once you understand the basics, you will be able to create powerful applications using Visual Basic. Were going to take a look at the elements of the Visual Basic language that will let us make Visual Basic code work.
What will that code look like? Some of our code will be short, such as when we check for multimedia device errors like this in Chapter Select Case MMControl1. End Sub Thats what the Visual Basic language looks like at work. As you can imagine, knowing how to write the code is necessary to get anywhere in Visual Basic. In the topics coming up, then, well see how to declare variables, functions, and subroutinesand what those elements mean.
Well see how to use text strings, conditionals, operators, loops, and math techniques. Well even see how to handle special Visual Basic formats like dates and financial data. And well see some items that programmers like but dont often encounter in programming books, such as how to use Switch and Choose. Well cover tasks that involve some complexity and whose syntax is hard to remember. In this way, this chapter also acts as a reference for easy lookup of those hard-to-remember itemsand can save you from reinventing the wheel.
Well see a lot of syntax in this chapter, and theres one convention you should be aware of before starting: Dim [WithEvents] varname [ [subscripts] ] [As [New] type] [, [WithEvents] varname[ [subscripts] ] [As [New] type]] Here, all the elements in square brackets are optional, and the variable names in italics are placeholdersyou fill them in with the names of your variables as appropriate for your program Its time to turn to the Immediate Solutions nowno further introduction is needed.
Youve filled your code with numeric valuesand now its time to change them all as you start work on the. What a pain to have to track down and change all the numeric values called magic numbers throughout all the code. Isnt there a better way? There is: Use constants and declare them all in one place, then refer to the constants by name throughout the code instead of hardwiring numeric values in the code.
When its time to change those values, you just change the constants, all in one well-defined part of the code. How do you use constants? You declare constants in Visual Basic with the Const statement:.
This keyword is not allowed in procedures. The Private keyword is used at the module or form level to declare constants that are private, which means only available within the module or form where the declaration is made. Like the Public keyword, Private is not allowed in procedures constants in procedures are always private anyway. The constname identifier is the actual name of the constant.
The expression identifier holds the value you want for this constant. It may be a literal, other constant, or any combination that includes all arithmetic or logical operators except the Is operator. You can use a constant anywhere you can use any Visual Basic expression, and you usually use them for numeric or string values that you want to use many places in a program.
That way, when you want to modify the value of the constant, you only have to change it in its declaration, not in many places around the program. Also, constants dont change their values, which can make them more useful than variables in certain circumstances.
You cant use variables, user-defined functions, or intrinsic Visual Basic functions in expressions assigned to constants. Before using variables, you have to set aside memory space for themafter all, thats what they are, locations in memory.
Usually, you use the Dim statement to declare variables, although you can also use the Private declare a private variable , Public declare a global variable , Static declare a variable that holds its value between procedure calls , ReDim redimension a dynamic array , or Type declare a user-defined type keywords to declare variables, as well see in the tasks covered in this chapter.
The Dim Statement Heres how you use the Dim statement:. The WithEvents keyword is valid only in class modules. This keyword specifies that varname is an object variable used to respond to events triggered by an ActiveX object. The varname identifier is the name of the variable you are declaring. You use subscripts if youre declaring an array. You set up the subscripts argument this way:. The New keyword enables creation of an object.
If you use New when declaring the object variable, a new instance of the object is created on first reference to it. This means you dont have to use the Set statement to assign the object reference.
Heres an example:. If you dont specify a type, the default is Variant, which means the variable can act as any type. By default in Visual Basic, numeric variables are initialized to 0, variable-length strings are initialized to a zero-length string , and fixed-length strings are filled with zeros. Variant variables are initialized to Empty. Its better to require all variables to be explicitly declared, however, because misspelling a variable name can declare a new variable and cause problems, as we saw in this code from Chapter 1, where we think were toggling a Boolean variable named xNow but are placing the result in a new and misspelled variable named xNoww:.
To force variable declarations to be explicit that is, to insist that each variable be declared , add the Option Explicit statement at the module or form level to the General declarations object. Its time to create a new variablebut what type should you use? For that matter, exactly what type of variable types are there and what do they do?
Even if you remember what types there are, you probably wont remember the range of possible values that variable type allows. Theres a wide range of data types, so well use a table here. The Visual Basic variable types appear in Table 3. We also include the literal suffix symbols for numeric values in Table 3. Table 3. As you can see in Table 3. The Variant type deserves special mention, because its the default variable type.
If you dont declare a type for a variable, it is made a variant:. End Sub In this case, the variable NumberTrains is a variant, which means it can take any type of data. End Sub Be careful of variants, howeverthey waste time because Visual Basic has to translate them into other data types before using them, and they also take up more space than other data types.
Visual Basic supports a number of ways of converting from one type of variable to anotherin fact, thats one of the strengths of the language. The possible conversion statements and procedures appear in Table 3. Note that you can cast variables from one type to another in Visual Basic using the functions CBool , CByte , and so on. Youve just finished creating a new dialog box in your greeting card program, and it s a beauty. However, you realize theres a problem: Its tempting to set up a global variable, intNumberBalloons, which you fill in the dialog box when the user clicks on the OK button.
That way, youll be able to use that variable in the rest of the program when the dialog box is closed. But in this case, you should resist the temptation to create a global variableits much better to refer to the text in the text box this way assuming the name of the dialog form you ve created is Dialog:.
This avoids setting up a global variable needlessly. In fact, one of the most important aspects of Visual Basic programming is variable scope. In general, you should restrict variables to the smallest scope possible. There are three levels of variable scope in Visual Basic, as follows: These variables are available throughout the module. Note that you cannot use Public in procedures. You can get an overview of the scope of variables in a Visual Basic project in Figure 3.
If you use the Option Private Module statement in a module or form, all variables in the module or form become private to the module, no matter how they are declared. You can change a variables type with ReDim in Visual Basic, assign objects to variables using Set, and even convert standard variables into arrays. For these and other reasons, Visual Basic has a number of data verification functions, which appear in Table 3.
Does This Function. Note in particular the IsMissing function, which many programmers dont know about; this function tells you if the call to the current procedure included a value for a particular variant. For example, heres how we check if the call to a subroutine CountFiles included a value in the optional parameter intMaxFiles:.
End If End Sub. Its time to start coding that database program. But wait a momenthow are you going to handle the data? Its just a simple program, so you dont want to start tangling with the full Visual Basic database techniques. An array would be perfect; how do you set them up again? You can use Dim standard arrays , ReDim dynamic arrays , Static arrays that dont change when between calls to the procedure theyre in , Private arrays private to the form or module theyre declared in , Public arrays global to the whole program , or Type for arrays of user-defined types to dimension arrays.
Well start with standard arrays now. Standard Arrays You usually use the Dim statement to declare a standard array note that in Visual Basic, arrays can have up to 60 dimensions:. You use subscripts to declare the array. The type argument specifies the data type of the variable, which may be Byte, Boolean, Integer, Long,.
Here are a few examples of standard array declarations:. You use the Option Base statement at the form- or module-level to set the lower bound for all arrays. The default value is 0, but you can use either of these two statements: Option Base 0 or Option Base 1.
Dynamic Arrays You can use the Dim statement to declare an array with empty parentheses to declare a dynamic array. Dynamic arrays can be dimensioned or redimensioned as you need them with the ReDim statement which you must also do the first time you want use a dynamic array. Heres how you use ReDim:. ReDim [Preserve] varname subscripts [As type] [, varname subscripts [As type]] You use the Preserve keyword to preserve the data in an existing array when you change the size of the last dimension.
The varname argument holds the name of the array to re dimension. This is one of those topics that is made easier with an example, so heres an example using dynamic arrays, where we declare an array, dimension it, and then redimension it, like this:.
Heres how you use Array:. Array arglist The arglist argument is a list of values that are assigned to the elements of the array contained within the variant. Heres an example that creates an array with the values 0, 1, and Well finish this topic with a summary of array-handling techniques.
Array-Handling Techniques Summary Visual Basic has a number of statements and functions for working with arrays, and they appear in overview in Table 3. Everyone knows about subroutines: Unlike functions, subroutines do not return values; but like functions, you can pass values to subroutines in an argument list. For references sake, heres how you declare a subroutine:. End Sub The Public keyword makes a procedure accessible to all other procedures in all modules and forms.
The Private keyword makes a procedure accessible only to other procedures in the module or form in which it is declared. The Friend keyword is used only in class modules and specifies that the procedure is visible throughout the project, but not visible to a controller of an instance of an object.
The Static keyword specifies that the procedures local variables should be preserved between calls. The name identifier is the name of the procedure. The arglist identifier is a list of variables representing arguments that are passed to the procedure when it is called. You separate multiple variables with commas. The statements identifier is the group of statements to be executed within the procedure. The arglist identifier has the following syntax:.
When you use ByVal, you pass a copy of a variable to a procedure; when you use ByRef, you pass a reference to the variable, and if you make changes to that reference, the original variable is changed.
The Exit Sub keywords cause an immediate exit from a Sub procedure. Finally, End Sub ends the procedure definition. You call a Sub procedure using the procedure name followed by the argument list.
Heres an example of a subroutine:. There are two types of procedures in Visual Basic: Subroutines can take arguments passed in parentheses but do not return a value; functions do the same but do return values which can be discarded. A function is a block of code that you call and pass arguments to, and using functions helps break your code up into manageable parts.
For references sake, heres how you declare a function:. End Function. The Public keyword makes a procedure accessible to all other procedures in all modules and forms.
The arglist identifier has this following syntax:.
The type identifier is the data type returned by the function. The Exit Function keywords cause an immediate exit from a Function procedure.
You call a Function procedure using the function name, followed by the argument list in parentheses. You return a value from a function by assigning the value you want to return to the functions name like this: Finally, End Function ends the procedure definition. Heres an example showing how to use a function:. Youve written a function named Counter to keep track of the number of times the user clicks a particular button.
Each time the user clicks the button, you call the Counter function to increment the count of button clicks, and then display the result in a message box.
But the counter never seems to be incremented; instead it always returns 1. Lets look at the code:. The solution is to declare intCountValue as static. This means it will retain its value between calls to the Counter function. Heres the working code:. Youve decided to lead the way into the future by letting your users type in English sentences as commands to your program.
Unfortunately, this means that you have to parse that is, break down to individual words what they type. So what was that string function that lets you break a string into smaller strings again? Well get an overview of string handling in this topic. Two Kinds Of Strings There are two kinds of strings: You declare a variable-length string this way:.
Dim strVariableString As String A variable-length string can contain up to approximately 2 billion characters, and it can grow or shrink to match the data you place in it. A fixed-length string can contain 1 to approximately 64K characters. The String-Handling Functions.
There are quite a number of string-handling functions in Visual Basic. For example, you use Left , Mid , and Right to divide a string into substrings, you find the length of a string with Len , and so on. For reference, the Visual Basic string-handling functions appear in Table 3. To Do Use This This. Youre all set to write your SuperDeluxe calculator program in Visual Basicbut suddenly you realize that the user will be entering numbers in text form, not in numeric form.
How can you translate text into numbers, and then numbers into text to display your results? Its common in Visual Basic to have to convert values from numbers to strings or from strings to numbers, and its easy to do. You can use the Str to return a string representation of a number, and you use Val to convert a string to a number.
Thats all there is to it, but its easy to forget those two functions, so we include them here for reference. Besides Str and Val , you can also use Format , which lets you format an expression into a string this way:. Format expression [, format[, firstdayofweek[, firstweekofyear]]] Here, expression is the expression to format into the string, format is a valid named or user-defined format expression, firstdayofweek is a constant that specifies the first day of the week, and firstweekofyear is a constant that specifies the first week of the year.
For more information about how to use this function and format strings, see Handling Dates And Time Using Dates later in this chapter. Youve done well in your computer classso well that the instructor has asked you to calculate the average grade on the final. Nothing could be easier, you think, so you put together the following program:. That doesnt look so goodwhats wrong? Instead of adding the final grade, however, it first divides that grade by NumberStudents, because the division operation has higher precedence than addition.
The solution here is to group the values to add together this way using parentheses:. This example points out the need to understand how Visual Basic evaluates expressions involving operators.
Visual Basics operator precedence, arranged by category, appears in Table 3. ComparisonLogical Arithmetic. When expressions contain operators from more than one category in Table 3. Also, comparison operators actually all have equal precedence, which means they are evaluated in the left-to-right order in which they appear.
If in doubt, use parenthesesoperations within parentheses are always performed before those outside. Within parentheses, however, operator precedence is maintained.
The If statement is the bread and butter of Visual Basic conditionals, but you can forget the syntax every now and then that is, is it ElseIf or Else If? If condition Then [statements] [ElseIf condition-n Then [elseifstatements]] What can you do? You use Select Case to test an expression, seeing which of several cases it matches, and execute the corresponding code.
Heres the syntax:. Select Case testexpression [Case expressionlist-n [statements-n]] Heres an example using Select Case. In this example, we read a positive value from the user and test it, responding according to its value.
Note that we also use the Select Case Is keyword not the same as the Is operator to check if the value we read in is greater than a certain value, and Case Else to handle values we dont explicitly provide code for. Heres the example:. Select Case intInput Case 1: MsgBox "Thank you. MsgBox "That's fine. MsgBox "Your input is getting pretty big now MsgBox "You are approaching the maximum! MsgBox "Too big, sorry. MsgBox "Please try again. For some reason, few books on Visual Basic cover the Switch and Choose functions.
They certainly have their uses, however, and well take a look at them here. The Switch Function The Switch function evaluates a list of expressions and returns a Variant value or an expression associated with the first expression in the list that is true.
Switch expr-1, value-1[, expr-2, value If expr-1 is not True but expr-2 is, Switch returns value-2 and so on. Heres an example showing how to use Switch. In this case, we ask the user to enter a number and use Switch to calculate the absolute value of that value having temporarily forgotten how to use the built-in Visual Basic absolute value function, Abs:.
Choose index, choice-1 [, choice-2, Heres an example using Choose. This code snippet accepts an ID value from the user and uses Choose to display the corresponding employee name:. To make it easier, well include examples here of all the Visual Basic loops, starting with the Do loop.
The Do Loop The Do loop has two versions; you can either evaluate a condition at the beginning. Note that the second form of the Do loop ensures that the body of the loop is executed at least once.
On the other hand, you sometimes want to make sure the loop doesnt run even once if the condition is not met. For example, when reading from a file, you shouldnt read from a file before checking for the end of file in case the file is empty. Heres the syntax for the For loop:. Although its been common practice to use a loop index after a loop completes to see how many loop iterations were executed , that practice is now discouraged by people who make it their business to write about good and bad programming practices.
Heres its syntax:. For Each element In group [statements] [Exit For][statements] Next [element] You can get a look at this loop in action with an example like this one, where we display all the elements of an array in message boxes:. Heres the While loops syntax:.
Many Visual Basic functions, like EOF , are explicitly constructed to return values of True or False so that you can use them to control loops such as Do and While loops. The With Statement Properly speaking, the With statement is not a loop, but it can be as useful as a loop and in fact, many programmers actually think of it as a loop.
You use the With statement to execute statements using a particular object. With object [statements] End With Heres an example showing how to put With to work. Here, we use a text box, Text1, and set several of its properties in the With statement:. With Text1. Using collections, you can group related items together. Collections can be heterogeneousthat is, members of a collection dont have to share the same data type, and that can be very useful, because life doesnt always present you with collections made up of items of the same type.
You create a collection as you would any other object:.
You can also reach specific members in the collection using the Item method. Collections are very useful and are one of the high points of Visual Basic. Its time to print out the screen spreadsheets youve created in your new spreadsheet program to show the boss. Regrettably, there just doesnt seem to be any way to print them out except one at a time, using the File menus Print item.
Can Visual Basic help here? You can use the SendKeys function to send keys to the program that currently has the Windows focus, just as if you typed in those keys yourself. Using the Alt key, you can reach the menu items in your spreadsheets File menu. The day is saved, because now you can automate your printing job, even waiting until the spreadsheet program processes the current keystroke before continuing.
Heres how you use SendKeys:. SendKeys string [, wait] The string expression is the string you want to send to the other program. The wait argument is a Boolean value indicating the wait mode. If False which is the default , control returns right after the keys are sent. If True, the keystrokes must be processed by the other program before control returns. If the keys you want to send are not simple text, just embed the codes you see in Table 3.
Code Key. Heres an example showing how to use SendKeys. Here, we give the Windows WordPad program the focus with the Visual Basic AppActivate function, passing it the title of that program which appears in its title bar , and send the string Hello from Visual Basic!
Visual Basic. NET Programming. Programming Microsoft Visual Basic. Net Core Reference. Programming Visual Basic. NET programming. Visual Basic Microsoft Office Reference. Beginning Microsoft Visual Basic Mastering Microsoft Visual Basic Developer's Workshop. Microsoft Visual Basic Design Patterns.
Visual Basic Microsoft Graph Objects. Word Visual Basic Programming. Microsoft Visual Studio Programming. Visual Basic 6. Recommend Documents. Programming with Microsoft Visual Basic This is an electronic version of the print textbook. Due to electronic rights restrictions, some third party content ma