VB Tutorial 3
 
Visual Basic Tutorial 3 - The Syntax of the Language 1

Every programming language has some elements that you must know by heart - its like knowing a core vocabulary in a language. Sure you could look a word up in a dictionary; but things go a lot faster knowing a core vocabulary by heart. It used to be one could commit the whole of a language like C or FORTRAN and all their APIs to memory; but with Visual Basic's large syntax and huge API including now more of the native Windows SDK, that is a superhuman task.

So here are four essential parts of Visual Basic syntax to know and understand very well - 1) all the variable types (integer, string,etc.) and when to use them; 2) the naming and scope conventions for variables, 3)all the commands in Visual Basic's syntax that control flow of operations(for, if - then, etc.), and 4)how parameters are passed and treated when used in subroutines. This tutorial will touch on some of these critical elements of VB syntax with a Timer VB program.

Figure 1 - Timer program

Visual Basic Variables

All programs manipulate values contained in variables.Variables are stored temporarily in memory and/or permanently on hard disk. For storage efficiency and runtime speed, different types of variables can be used in a Visual
basic program. There are 12 different variable types which can be grouped into two major categories - numeric and
other special types. In addition, using the Type statement you can create your own variable type (and will do so in later tutorials on database access). But here are all the Visual Basic variable types defined using VB syntax (remember, a comment in Visual Basic is any line beginning with an apostrophe, or all the text after an apostrophe):

Numeric types

Dim cByte as Byte 'declare cByte as 1 byte numeric value ranging from 0 to 255. Used in bit/byte manipulations.
Dim Ip as Integer 'declares "Ip" as a numeric variable of 2 bytes whose values can range between -32768 to 32767
' use Integers for loop variables, counters and small table indexes.
Dim Lval as Long 'declares "Lval" as a whole number of 4 bytes with range between -2,147,483,648 to 2,147,483,647
' use Longs for indexes into large tables, file i/o, and other VB counters;
Dim Bucks as Currency 'declares "Bucks" as a numeric variable of 10 bytes with high calculation accuracy
' which ranges from -922,337,203,685,477.5808 to 922,337,203,685,477.5807.
' Use this data type for calculations involving money and fixed decimal point accuracy.
' Currency calculations are about as fast as longs.
Dim dontUse as Single 'declares "dontUse" as a single precision floating point variable.
' Use Double rather than Single except where demanded by VB/Windows API;
' Double is much more accurate and even runs about 10-20% faster than Single.
Dim Realone as Double 'declares "Realone" as a double precision floating point variable of 8 bytes which can range from
' -1.79769313486232E308 to -4.94065645841247E-324 for negative values;
' 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
' Use when a numeric value can have several decimal places or range to extreme sizes.


Other Types

Dim curDate as Date 'declares curDate as a Date value which stores both date and time in one 8 byte variable.
' As Y2K proves, it is very useful to know date functions well.
Dim vString as String ' declares "vString" as a dynamic string of varying length. Strings are used everywhere in VB;
' there is a fixed string type, but given trivial speed/storage advantages, stick with dynamic strings.
Dim objPtr as Object 'declares "objPtr as an Object variable of 4 bytes in size. Objects will be used in advanced topics.
Dim dVar as Variant 'declares "dVar" as a Variant variable of minimum 16 bytes in length. Variants, as the name implies,
' can store date or numeric or string or object/reference values. It is the default variable type.
' The trade-off with Variants is their flexibility/ease of use versus storage size cost and speed
' disadvantage, about 3 times slower than integer or longs, 4-6 times slower than doubles. Variants
' also have the nagging ability to camouflage bugs in coding. Use carefully.
Dim objType as File 'declares "objType" as the VB predefined object-type, File. In VBA there are hundreds like
' Application, Document, Sheet and others; you will use many object-types there.


In a sampling of ten of my own plus a dozen other Visual Basic programs the three most frequently used variable types were by far - Integer, String, and Double. So it will pay dividends to get to know by heart the various conversion routines and functions associated with these variable types. Format(), Mid(), Instr(), Ucase(), Value() are five of about 25-30 functions that you will find yourself using constantly.

The Timer Program

The Timer program illustrates a number of the variable types just discussed. It also underlines some of the coding standards which I urge you to adopt. This is a program I constantly use to test the speed of different operations, especially with different variable types. It is by no means a professional benchmarking program; but does give users a good feel for the relative performance of different VB operations and variables.

First let us create the form. Drag on a label and a textbox. Set the form's caption in the property sheet to "Timer Program". Set the label's Caption property to "Iteration Increment". Click the label's Font property to make it bold and 12pt. For the textbox, blank out the"Text1" in the text property. Now add a second label centered just below the label and textbox. Blank out the Caption (the program will change the label's caption to"print" the timing results right on the form. So again make the label's caption more readable by

Now all that is necessary is to add two command buttons to make the form look like Figure 1. Change the captions on the command buttons to read "Time" and "Exit" respectively. And we are now finished designing the GUI interface. Now all we have to do is to add the program code to make all the elements work together.

But first it is worthwhile taking note of this process. In VB, the whole trick is to divide the processing into manageable tasks. Then for each task build the interfaces for input and output. In this case, we are using the same Timer dialog for input and output. One of the key advantages of VB and Java is that with their advanced IDEs, the GUI interface can be tested and modified very quickly - so ideas can be quickly tried out and refined.

The Timer Programming

Before jumping into the programming, there are two standards which I would encourage users to adhere to. First, under Tools | Options | Editor click the checkbox for  Require Variable Declaration. This causes VB to insert the command Options Explicit in the form's code every time a new form is created. This means that VB will require that every variable in a program be declared (or Dim -ed). Why drop one of the conveniences of VB, its ability to allow variables to be created and used right on the fly ? Bugs. Lots of subtle bugs tough to get rid of. Example, a variable vTime is declared and intitialized. A little later in the program, vTimer is calculated and printed. But the values are not what you expected. Problem - vTime and vTimer are two different variables. With Options Explicit VB would flag the fact that vTimer had not been declared - bug avoided. Let me tell you as programs get bigger, tracking simple bugs like these can take hours - avoid the frustration.

Second standard - adopt any naming convention you are comfortable with for variable names, but make sure at least one letter get capitalized. Why ?. Because VB's editor is smart. As you type in in your program, each line is syntax checked and fancy formatted. Included in the fancy formatting is VB's ability to restore capitalization in any variable name. Thus I always type in lowercase, and then watch as VB pops in the Caps. If a glance indicates variable doesn't pop into Caps - I know I have made a mistake in spelling the variable's name and can correct the problem (bug squashed) immediately.

Now for the programming. Double click on the Exit command button. Add the command End to the Command2_Click() routine. This ensures that you have a graceful way to exit from the program. Also we want to change the number of iterations - hence the Iteration Increment textbox.

So we want to initialize the Iterations Increment textbox on program start-up. The Form_Load() routine is used for this. To set the Form_Load you could start typing in right away. But it is easier to go to the Object combo box in the text editor (see

Figure 2 - VB Text Editor

Figure 2) and select Form as the object. Automatically VB creates the skeleton of the Form_Load() routine. We just add the 3 lines of comments and code as shown in Figure 2. Lets run the program right away - the results should look like Figure 1 except there will be a blank space instead of timing numbers.

Recommendation- run VB right away to check out intermediate results. It is a simple Run | Start set of menu commands. A quick check confirms that the program starts up properly; so now we can work on the timing calculations.
Those are easy too. When the user clicks on Time button, 10000 (or some user specified) iterations are done on some
variable or formula to check its timings. To do so, a time stamp is taken just before and then immediately after the loop which contains the calculations to be timed. Let's follow the Visual Basic code in the Command1_Click() procedure which is triggered when the Time button is clicked.

'Number of iterations
Iters = Val(Text1.Text)
' Take the time just before Calculations
vTime = Now


Note that the number of iterarions is read directly from the form using Text1.text - that is the Text property contains the the string "10000" in this case. Because it is a string we have to convert it into a number using the Val() function. This as well as the Now are two of the frequently used functions that a VB user should get to know well. Now provides a time and date stamp at the moment it is called. Thus, the Variant vTime (we used a Variant rather than a Date variable because Variants are accepted in more VB subroutines) contains, exact to the second, the time just before the iterations start.

'this loop will repeat an operation to be timed
' it will do so "Iters" times for the Currency variable Vc
Vc = 1000
For ii = 1 To Iters
Vc = Vc * ii / (ii + 111)
Next ii
'Get the time after finishing the operation
fTime = Now


This next segment of code performs the calculations to be timed, in this case timings on the speed of Currency calculations. the "For" loop repeats the VC = ... calculation Iters times. A "For" loop is only one of 3 or 4 ways these calculations could be done - upcoming tutorials will explore other methods using some alternate VB flow of control commands. Note again we take the time immediately after the calculations are done. Using this routine we found Currency calculations to be 3 times faster than Variants. Just change Dim Vc as Currency to Dim Vc as Variant and run the program again and see for yourself.

'Now output the results
vMins = Minute(fTime - vTime)
vSecs = Second(fTime - vTime)
Label1.Caption = "Iters=" & Format(Iters) & " - " & Format(vMins, "00") & ":" & Format(vSecs, "00")
End Sub


The final chunk of code does the timing calculations and displays the results. Here we take advantage of the fact that the Minute() and Second() functions will return the difference in minutes and seconds between fTime (when the calculations finished) and vTime(when they started). But these values contained in vMins and vSecs respectively, are stored in numeric format. We need to convert them to strings for output. The Format() function accomplishes that trick. Format is one of the most frequently used functions in VB - so get to know it well. In this case, Format(vSecs, "00") tells VB to convert vSecs to a string that is always two characters long with zero used as a fill character like so:
vSec = 0 Format(vSecs, "00") = "00"
vSec = 6 Format(vSecs, "00") = "06"
vSec = 23 Format(vSecs, "00") = "23"
Finally note how we have taken advantage of the fact that many control properties are programmable at runtime. Thus, in this case we join or concatenate together (& is the concatenate operator) the substrings into one display message. And that message is just the Caption for Label1. In effect we are taking a static design time property, Caption, and changing it at runtime (or programmatically) for outputting results. In general, you will find yourself using this VB trick often enough.Note when the End Sub command is encountered, the program returns control to the dialog and awaits your next input. So our timer program is done.


Summary


In this tutorial we have reviewed all the VB variable types, learned some highly useful VB functions and tried some of the tricks in a useful VB program for timing. In fact, when an operation seems to be taking too much time use the Timer program to try variations on the calculations to speed things up. In upcoming tutorials, more of the 4 essentials of VB syntax will be covered. Meantime check the resources below for further reading and exercises.




Resources:

The book Beginning VB6/Wrox covers variables on pages 174-192; VB6 Black Book/Coriolis does the same on pages 85-96. An interesting exercise would be to add a button labelled 1sec which when pressed would report how many iterations of a calculation could be done in one second.
 
Top of Page  Tutorials Home