Visual Basic offers a rich set of built-in functions for manipulating dates, times, strings, and numbers. Built-in functions are important because they save you time and effort--you don't need to reinvent the wheel.
In this chapter, you will learn how to use functions in your programs. You will learn the syntax and nuances of various functions that will make your programming life easier. By the time you reach the end of this chapter, you will know how functions are used.
There are many Visual Basic functions, but not all could be covered in this chapter. All the fundamental functions you need to develop most of your program, however, are included. Some of the functions that are not discussed in this chapter include financial calculations, advanced mathematical operations (such as transcendental functions), functions for navigating through the DOS file structure, functions for manipulating DOS files and attributes, error-handling functions, and functions for use in the manipulation of Visual Basic objects such as control arrays.
Recognizing the benefits of using built-in functions is easy. For example, imagine how long it would take to accomplish the seemingly simple task of determining whether today is Monday. You would have to figure out how to get the date from your PC, find a formula for calculating the day of the week given that date, and write a small program to implement it. But Visual Basic's Weekday function returns the day of the week in one easy step.
To continue the example, if there weren't built-in functions for working with dates, you would have to buy or borrow reference material on PC internals in order to know where and how the date is stored. You would also need to figure out a way to access the specific memory location containing the date and time information--not an easy task since Visual Basic has no inherent means of accessing a specific memory location. There are third-party tools to give you access to memory, but you would still need a formula to calculate the day of the week. Even if you already had these items, it would take at least an hour to write the program and test it. In contrast, it takes only a moment to find the built-in function you need and incorporate it in your program.
How many days have passed since your birth? On what day of the week will Christmas fall next year? How long until your anniversary? When will your home mortgage be paid off? The answer to these questions requires the ability to work with dates.
To determine how many days have passed since your birth, you must subtract your birth date from the current date. Visual Basic has a function to calculate the difference between two dates; you'll see an example of it later in this chapter. Visual Basic also has functions that allow you to answer the other questions as well.
Visual Basic's date functions work with dates ranging from before 1,800 years ago to more than 8,000 years in the future.
Time is important to everyone on some scale. For a military operation, accuracy is often required to the second--or less; for a busy executive, every minute counts. Most people, however, are probably concerned with at least the hour. Even while you are on vacation you must stay conscious of the date and time, or you may be late returning to your more hectic life.
It's no wonder then that PCs keep track of both the date and time. Your PC has an internal clock that Visual Basic can reference in order to provide a fairly accurate time (see the sidebar).
The clock inside your PC is not a highly accurate chronograph; it is possible for it to be off by even a few seconds a day. For some applications this may not be acceptable. For the majority of users, however, it is quite acceptable. It all depends on the precision you need.
Simply noting the setting of the sun each evening is adequate for precision of days. A sundial provides precision of hours. A pendulum provides the basis for accurately marking the passing of minutes. A wristwatch is sufficient for seconds. A digital watch often provides stopwatch accuracy down to hundredths of a second. Mankind's quest for precision in the measurement of time has taken us so far we can measure the emissions of the cesium-133 atom to form the basis of a clock that provides accuracy beyond billionths of a second. Time can be measured with different precision.
Where does Visual Basic fit into this continuum of precision? Visual Basic's time-related functions provide precision to the second and can be used to get the current second, minute, hour, day, month, or year.
Visual Basic provides a variety of functions that allow you to access and manipulate both the date and time. Each function typically returns or uses the date and time stored in a variable using the Variant data type (see Chapter 4). This provides you with information you can readily use in your programs.
If you started a stopwatch at this moment and stopped it in 315,360,000 seconds, how much older would you be? Because humans don't have the lightening fast calculating speed of computers, it isn't very easy for us to make such calculations. With the aid of a calculator, you'll quickly see that you would be about 10 years older (not accounting for leap years).
What significant historical event occurred approximately 728,500 days ago? Again, most of us are at a loss. A properly programmed computer, however, would quickly determine the year as 0 AD. With that information you know that either the birth or death of Christ was the event (depending on which religious scholars you question).
Visual Basic handles date ranges of this magnitude quite handily by storing dates and times as a serial number in a double-precision number. Everything to the left of the decimal point represents the date, and everything to the right represents the time. You may remember from Chapter 4 that the range of numbers that can be stored in this data type is quite large; VB can handle dates that cover over a 10,000 year range.
The Date function is the starting point for many calculations involving dates. For example, if you want to know how long ago a certain date was or how far in the future a certain date will be, you must start with the current date.
The Date Function
The format of Date is
Datewhich returns a Variant data type (Variant Type 7).
ExampleDim TodaysDate As Variant TodaysDate = Date
Remember that when you use Date, the date returned is the date stored in the PC's internal clock. If the date stored in the PC is wrong, then Date will obviously not return the correct date.
If you must know the current time of day, use Time.
Note:Your PC contains an internal clock. Like a quartz watch, the internal clock of your PC is based on the vibration of a quartz crystal providing good short-term accuracy. The clock in most PCs is accurate to about plus or minus 15 seconds per month. This means that over time the PC's clock, such as a watch, can drift and require resetting.
To change the time or date stored in your PC's internal clock use the Date/Time icon in the Windows Control Panel.
The Time Function
The format of Time is
Timewhich returns a Variant data type (Variant Type 7).
Example
Dim CurrentTime As Variant CurrentTime = Time
Because Time returns the value stored in the PC's internal clock, as with Date, if the PC's clock is incorrect, then the value returned by Time will also be incorrect.
Sometimes you need both the current date and the current time. Although you can use both the Date and Time functions, there is a simpler way. You can use the Now function, which combines both Date and Time functions.
The Now Function
The format of Now is
Nowwhich returns a Variant data type (Variant Type 7).
Example
Dim TimeAndDate As Variant TimeAndDate = Now
Now is also convenient for timing the execution of your program. To find out how long part of your program takes to execute, use the code in Listing 5.1.
Listing 5.1 Timing your program.
StartTime = Now
'code to be timed here
TotalTime = Now - StartTime
Make sure that the section you are timing doesn't contain anything that will depend on user input (such as a button press or text entry), because it will distort the timing (unless of course, you want to time how long it takes for the user to respond).
Because the shortest amount of time Visual Basic can measure is one second, and because the CPU in your computer can execute thousands of lines of VB code per second, how can you time how long only a very few lines will take to execute? The answer is that you can't, at least not directly.
The pseudo-stopwatch, Visual Basic's Now function, has the same problem a real stopwatch has when trying to time an event that happens quickly. Its resolution is not fine enough to accurately time the event. For example, if you wanted to time how long it takes a car, traveling at a constant high speed, to go ten feet, you couldn't do it directly. The error incurred by the lack of precision with which you start and stop your stopwatch will introduce too much inaccuracy for a valid result.
By averaging the speed of the car over a longer distance, however, say 5,280 feet (a mile), and then dividing that time by the ratio of the desired distance to the measured distance (10/5280), you get the length of time for the car to travel only ten feet something you couldn't measure directly.
You can use the same technique with Visual Basic. If you have a sequence of instructions you want to time, place them inside of a For...Next loop. Execute the instructions hundreds or thousands of times, and time how long it takes to complete. Take that time and divide it by the number of times you executed the block of code. This will give you an approximation of the length of time necessary to complete just the few instructions.
Note:Because the For...Next loop consumes some processor time, your calculation will contain some error. The amount of error may not be important. For example, when you compare two alternative ways of doing the same thing, both methods will suffer from the same inaccuracy and therefore can be compared.
In addition, there are many different factors which affect the execution speed of a piece of code. Factors as diverse as the type of CPU, the frequency at which the processor is clocked, the access speed of the memory in the computer, whether the computer has cache memory, and even the speed of the hard disk drive can influence how long it takes your program to run.
The moral of the story is: Don't use your timings as hard fact unless they are accompanied by information on all the factors which influence them. This type of timing is most useful when used for comparative purposes on a single PC.
Sometimes you only need part of the date. For questions such as "Is today Wednesday?" and "Is this 1995?" Visual Basic provides the following four functions for extracting only the part of the date in which you're interested:
If someone asks you "When was the last time you used your PC?" would you answer "Last 3."? No, of course not. For calculation purposes, the integers returned by the Weekday function work just fine; for display, however, they just won't do.
The code in Listing 5.2 can be used to provide an English translation of the number returned from the Weekday function.
Listing 5.2 Weekday function
DOWNum = Weekday(Now) DOWString$ = Choose(DOWNum, "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
In this example, the Choose function selects one of the following variables based on DOWNum. If DOWNum = 1 then Choose selects the first one listed--"Sunday". If DOWNum = 2 then Choose selects "Monday".
If you were only interested in a portion of the time (for example, the hour), you could use Visual Basic's string functions to separate out the part in which you were interested.
The Year, Month, Day, and Weekday Functions
The format used by these functions is
Type(DateVariant)This function returns an integer. Type is any of the following: Year, Month, Day, or Weekday. DateVariant is a Variant which contains a valid date or a function which returns a Variant containing a valid date.
Examples
Dim ThisYear As Integer ThisYear = Year(Date)After this is executed, ThisYear will contain an integer value of the current year, such as 1994.
Dim ThisMonth As Integer ThisMonth = Month(Now)After this is executed, ThisMonth will contain an integer value of the current month, such as 12.
Dim ThisDay As Integer ThisDay = Day(Date)After this is executed, ThisDay will contain an integer value of the current day, such as 30.
Dim DayOfWeek As Integer DayOfWeek = Weekday(Now)In this example, the returned integer value will be in the range 1 to 7, where 1 represents Sunday, 2 represents Monday, and so on through 7, which represents Saturday.
Given the time 7:45:05 you could use InStr to find the first and second colon. Then, depending on which portion of the time you were interested in, you could use the Mid function to obtain that part.
An easier way, however, is by using any of the following functions: Hour, Minute, and Second.
Earlier in this chapter, you learned that you can use one of Visual Basic's built-in functions to determine the number of days since you were born. DateDiff is that function. DateDiff returns the number of days between two dates. If the first date is actually after the second, then DateDiff will return a negative number.
The Hour, Minute, and Second Functions
The format is
Type(DateVariant)Where Type is any of the following: Hour, Minute, or Second. DateVariant is a variable of the Variant type which contains either a valid time or a function that returns a Variant containing a valid time.
Examples
Dim ThisHour As Integer ThisHour = Hour(Now)When this example is executed, ThisHour will contain an integer value of the current hour. The value will be between 0 and 23.
Dim ThisMinute As Integer ThisMinute = Minute(Now)When this example is executed, ThisMinute will contain an integer value of the current minute. The value will be between 0 and 59.
Dim ThisSecond As Integer ThisSecond = Second(Now)When this example is executed, ThisSecond will contain an integer value of the current second. The value will be between 0 and 59.
The DateDiff Function
The format is
DateDiff(interval, startdate, enddate)Where interval is a string representing the units in which you want to measure the difference. They are:
Year yyyy Quarter q Month m Week ww DayofYear y Weekday w Day d Hour h Minute n Second sExample
Dim NumDays As Variant NumDays = DateDiff("d", Now, "6/5/86")This example calculates the number of days since June 5, 1986.
To show how the DateDiff function can work for you, you will create a date calculator. Figure 5.1 shows the bare-bones form layout for the calculator. Notice that you will need to use the following controls in the form:
Next, set the form and control properties shown in Table 5.1.
Fig. 5.1
The bare-bones form layout for the date calculator.
Table 5.1 Date calculator properties
Object Property Value Form Caption Date Calculator Command1 Caption Calculate Now Label1 Caption Begin Date Alignment Right Justify Label2 Caption End Date Alignment Right Justify Label3 Caption (Delete caption) Label4 Caption Interval Text1 Text (Delete text) Text2 Text (Delete text) Combo1 Style Dropdown list
Next, add the double-click on the command button control and make sure the Code window contains the code shown in Listing 5.3. Then you can close the Code window.
Listing 5.3 Code for the date calculator command button.
Sub Command1_Click ()
If Not IsDate(Text1) Or Not IsDate(Text2) Then
MsgBox "Please make sure the Begin and End dates are valid",48, "Date Calculator"
Exit Sub
End If
Select Case Combo1
Case "Years"
DiffType = "yyyy"
DiffUnits = " Year difference"
Case "Months"
DiffType = "m"
DiffUnits = " Month difference"
Case Else
DiffType = "d"
DiffUnits = " Day difference"
End Select
Label3 = DateDiff(Difftype, Text1, Text2) & DiffUnits
End Sub
Now double-click on the form itself, and make sure the Code window contains the code shown in Listing 5.4.
Listing 5.4 Code for the date calculator function.
Sub Form_Load () Combo1.AddItem "Years" Combo1.AddItem "Months" Combo1.AddItem "Days" End Sub
When you are finished, the form should look like figure 5.2.
Fig. 5.2
The finished form layout for the date calculator.
This project uses a few functions you won't learn about until later in the chapter, so here's a quick explanation of their purpose.
When you run the program, you can enter dates in the Begin and End Date fields, and choose a type of interval from the Interval list. Figure 5.3 shows an example of how the program operates.
To go the other way when you have a date and want to find a date in the future, use the DateAdd function.
Fig. 5.3
Running the date calculator.
The DateAdd Function
The format is
DateAdd(interval, number, date)Where interval is a string representing the type of units you want to add to date. interval can be any of the same values used in DateDiff. Finally, number is the number of those units you want added to date.
Example
Dim NumberOfDays As Variant, PastDate As Variant FutureDate = DateAdd("yyyy", 10, Now) PastDate = DateAdd("yyyy", -10, Now)
To begin the discussion of string functions, you are going to take a short trip into the workings of your computer.
Computers store all their information (even strings) as binary numbers. Binary means one of two states--either On or Off, 1 or 0. Computers work in binary because the electronic switches of which they're made are only capable of storing a 1 or a 0 at any particular location.
The binary numbering system is also referred to as the base 2 numbering system. You are accustomed to working in base 10. The value following the word base is the number of different values any one digit may have in that numbering system.
In the decimal system (base 10), each digit can have a value from 0 to 9--that's ten possible values. In base two, there are only two possible values--0 or 1.
To count in decimal, you start with a single digit. That digit contains the value 0. As you increment your count, you increase the value in that first digit. When you reach the maximum value for that digit, you reset it to 0 and increment the digit to the left. This process continues as long as necessary. Counting in base 2 follows the same rules, except there are fewer values to use in the digits. The first few binary numbers are shown in Table 5.2.
Table 5.2 Counting in binary
Binary Decimal 000 0 001 1 010 2 011 3 100 4 101 5 110 6 111 7
You can see how numbers could be stored using this system. But how does this relate to strings?
Characters are stored using a numeric code. By representing a character with a number, that number can be stored and later retrieved by the computer. When displayed, it is converted back into the character so that you can understand it. Table 5.3 shows a part of the list of characters and the values used by the computer to represent them.
Table 5.3 Codes used to represent characters
Character Decimal Binary 1 31 0011111 2 30 0100000 3 33 0100001 A 65 1000001 B 66 1000010 C 67 1000011 D 68 1000100 a 97 1100001 b 98 1100010 c 99 1100011 d 100 1100100
In order for computers made by different manufacturers to communicate with one another, a standard code was necessary for the representation of information. The American National Standards Institute (ANSI) has developed a code with values ranging from 0 to 255 which represent numbers, characters, and codes for special purposes such as carriage returns and line feeds. Windows, and hence Visual Basic, support a significant subset of this ANSI code. To see the ANSI codes and their characters, search on-line help for ASCII and select ANSI Character Set.
The first commonly used code for the interchange of computer information was ASCII (American Standard Code for Information Interchange). ASCII has codes only for the values 0 through 127. By the time Windows was developed, the need for additional symbols (not representable in ASCII) had necessitated a new standard. The ANSI standard was adopted to incorporate accented characters. The common characters typed on the keyboard are represented the same in ANSI as in ASCII.
Note:Take another look at the values in Table 5.3. Notice that there are different numeric values for upper- and lowercase letters. When Visual Basic sorts strings, it normally does so by using the numeric code assigned to each letter. Thus, those characters with the lowest ANSI values come first. That's why, when Visual Basic lists items alphabetically (in a sorted list box, for example), text beginning with a number appears before text beginning with a character, and uppercase letters appear before lowercase letters.
Visual Basic provides the StrComp function which allows you to quickly determine if two strings are equal. What about the following strings, however:
This is a test string. THIS IS A TEST STRING.
If you use the normal comparison operators (see Chapter 4) to do a comparison, these strings are not considered equal. With StrComp, however, you can instruct it to ignore the case of the letters in the string--it all depends on your needs. (If StrComp takes the case of the letters into account, it is considered case-sensitive.)
The StrComp Function
The format of StrComp is
StrComp(string1, string2, [comparison type])
Where string1 and string2 are the strings to compare and a comparison type of 0 performs a case-sensitive compare while a comparison type of 1 performs the comparison without regard to case. If the comparison type is omitted, then the default type specified for the module (using an Option Compare statement) is used.
The return values are:
--1 if string1string2
Example
Dim StringCompResults As Variant
StringCompResults = StrComp("Test this", "TEST THIS", 1)
StringCompResults will contain a 0 because it was instructed to perform a case-insensitive comparison.
More often than not, you will need to make certain conversions in text strings used in your programs. For example, you may need to ensure that a last name entered in a text box contains an initial uppercase character or that a variable is stored in all uppercase so an exact match can be made. Visual Basic's text conversion functions provide the means for easily manipulating strings.
Converting the Case of a String. For switching entire strings to all upper- or lowercase, the functions LCase and UCase work well. Pass the string to be converted to one of these functions, and a string is returned which is guaranteed to be all upper- or lowercase (depending on which function is used).
To convert just a single character, separate that character, convert it, and then splice it back in. Listing 5.5 shows an example of capitalizing the initial letter of a word using UCase.
Listing 5.5 Conversion of a single character.
LowerCaseString = "herberger" InitialUpper = UCase(Left$(LowerCaseString,1)) & Mid$(LowerCaseString,2)
Converting Characters to Values. You can use the Asc function to convert a single character to its ANSI value. Asc is short for ASCII. As you have already learned, Windows uses ANSI characters, though ANSI is based primarily on ASCII. For compatibility reasons, the Asc function was not renamed. Asc returns an integer value which is the ANSI value of first character in a string.
The Asc Function
The format of Asc is
Asc(string)This function returns an integer equal to the ANSI value of the first character of the passed string.
Example
Dim ANSIValue As Integer ANSIValue = Asc("C")
When this code is executed, ANSIValue will contain the value 67. Converting Values to Characters. The Chr$ function does just the opposite of Asc. It converts a number into an ANSI character.
When you were a child, did you ever have a secret decoder ring? The secret decoder ring was used to implement a simple substitution cipher. A substitution cipher works by replacing each character in the original message with a substitute. To decode the secret message, just reverse the process by replacing each substitute with the original character.
You can use Chr$ and Asc to encrypt text in this manner. To test this out, follow these steps:
You can now run the program. You should type some text into Text1 and then click the form. The encrypted version will appear in Text2.
Listing 5.6 Encryption using Chr$ & Acs.
Text2 = " " For LocalCounter = 1 to Len(Text1) Text2 = Text2 & Chr$(Asc(Mid$(Text1,LocalCounter,1))+3) Next LocalCounter
The Chr$ Functions
The format of Chr$ is
Chr$(number)This function returns the ANSI equivalent character, as a string, for number.
Example
Dim CharacterString As String CharacterString$ = Chr$(67)When this code is executed, CharacterString$ will contain the letter C.
Converting a String to a Number. There will be times when you want to convert a string to a number. This comes in handy when you get input from a user in the form of a string, but you must convert it to a number to process it further. (This was done in the calculator examples in Chapters 1 and 2.)
The Val function converts the numbers in a string into a value. If the string contains any non-numeric characters, then only that portion of the string before the first non-numeric character is converted. Val will also properly convert a negative sign or exponentiation signs (see Chapter 4).
The Val Function
The format of Val is
Val(string)This function converts the leading numbers in string into a number.
Example
Num = Val("12345abcde")When this code is executed, Num will contain the value 12345.
Converting a Number to a String. Many times you will want to convert a number to a string. The Str$ function allows you to do the opposite of the Val function. It converts a number into a string, adding a sign placeholder at the beginning (a space if the number is positive or a minus sign if the number is negative).
The Str$ Function
The format of Str$ is
Str(number)This function converts number into a string.
Example
OrigNum = 9876 NumOut$ = Str$(OrigNum)When this code is executed, NumOut$ will contain the characters " 9876". Notice the leading space, which is a placeholder for a negative sign.
Occasionally you will need a string of characters that are all the same. For example, you may be printing a report and need a line of dashes across the page. There are many ways to generate a string of some number of a specific character, but the built-in Visual Basic functions, Space and String, are the easiest.
Making a String of Characters. Suppose you needed that string of dashes and your page was 80 characters wide. The following code returns a string consisting of exactly 80 dashes:
DashString$ = String$(80,"-")
The String$ Function
The format of String$ is
String$(number, string)This function returns a string exactly number characters long, made up of string.
Example
AString$ = String$(5, "A")Returns the string "AAAAA".
Note:While you can pass a string containing more than one character, String will use only the first character of the string. For example, String$(5, "ABC") returns "AAAAA" not "ABCABCABCABCABC".
Making a String of Spaces. Often the character you need is the space, so there is a special function just for generating strings comprised of only spaces--Space.
The string you get using Space is no different than the string you get using String with a space character. If you prefer, you can always use the String function and forget about Space.
The Space Function
The format of Space is
Space(number)This function returns a string consisting of number spaces.
Example
SpaceString$ = Space(10)Returns a string consisting of 10 space characters.
So far you have learned that Visual Basic provides quite a few different string functions. You have not learned them all, however. Visual Basic also provides other functions that allow you to do things like determine the length of a string, determine if one string is contained within another, and extract different parts of a string.
The Len Function
The format of Len is
Len(string)This function returns an integer count of the number of characters in string.
Example
Dim CharCount As Integer CharCount = Len("How many here?")Returns 14. (Don't forget to count the spaces as characters.)
The InStr Function
The format of InStr is
InStr([start,] string1, string2)This function returns a Variant that is the position of the first occurrence of string2 in string1. If specified, start is the first position in string1 at which time InStr begins searching for a match.
Example
Dim FoundAt As Variant FoundAt = InStr("Where is found at found at?", "found at")FoundAt contains the number 10, which is the character position of the first occurrence of the phrase "found at".
Extracting the Ends of a String. If you only require the leftmost or rightmost portions of a word, then the Left$ and Right$ functions are the most convenient. All you need to do is tell Visual Basic how many characters to strip from the string.
The Left$ and Right$ Functions
The format of the Left$ and Right$ functions is
Left(string, number) Right$(string, number)These functions return a string consisting of either the leftmost (Left$) or rightmost (Right$) number characters of string.
Examples
ResString$ = Left$("The left eight", 8)When this is executed, ResString$ will equal the characters "The left".
ResString$ = Right$("The 20 rightmost characters",20)When this is executed, ResString$ will equal the characters "The 20 rightmost cha".
Extracting the Middle of a String. Mid$ is used to return (or extract) any portion of a larger string. You pass Mid$ the starting point in the larger string where you want to begin extracting, as well as how many characters to take from that point forward. If you don't specify the number of characters to take, Mid$ returns the rest of the string.
The Mid$ Function
The format of Mid$ is
Mid$(string, start[, length])Where string is the string from which you will extract characters, start is the position within that string at which extraction will begin and length is the number of characters which will be extracted.
Example
Center$ = Mid$("Extract the center of this", 13, 6)When this code is executed, Center$ will equal the characters "center".
Mathematics is an important part of everyday life. You do simple math hundreds of times each day. You buy things and count your change, you calculate the mileage your new car is getting, and many many more things involving simple math.
Sometimes the math you must do is a little more complex. If you're buying a house, you'll need more advanced functions to determine what your payments will be, given a particular interest rate, amount borrowed, and loan duration. If you are a scientist, engineer, or machinist, or you have one of many occupations which require the use of more advanced functions, you will appreciate the power inherent in Visual Basic's math functions.
If you think math is too difficult or you don't have a practical use for it, consider some of the examples you are about to see. Everyone uses math to make life easier, and Visual Basic provides you with the functions to perform that math more quickly and accurately.
If you are just interested in the portion of a number to the left of the decimal point, Int will return it for you.
The Int Function
The format of Int is
Int(number)Where number is any numeric value.
Example
Dim IntegerPortion As Integer IntegerPortion = Int(52.94387)When this code is executed, IntegerPortion contains the value 52. What if you're interested in only the decimal portion? Simple. Just subtract the Int part from the original number. The decimal portion remains.
Have you ever played a computer game where the computer deals cards, throws dice, or spins a roulette wheel? Did you ever wonder how the random outcome of those events was simulated? Using Visual Basic's Rnd function, you can easily generate random events.
Before using the Rnd function, you must understand that the random numbers generated by Visual Basic are not truly random. This is why you may hear them referred to as pseudo-random numbers. A complete discussion of random numbers and the theory behind generating them would require a book at least as large as this one.
So, if you build a game of chance based on the random number generator in Visual Basic and then develop a system which consistently beats your game, don't take your life savings to Las Vegas--their games generate far more random numbers.
The Rnd Function
The format of Rnd is
Rnd[(number)]Rnd returns a single-precision number equal to or greater than 0, and less than 1. If the optional number is included, it affects Rnd in the following way:
Number Result <0 Same random number is returned every time 0 The number returned last time Rnd was used> 0 The next random number
Example
Dim HelterSkelter As Single HelterSkelter = Rnd
When this is run, HelterSkelter will contain a random single-precision value. Something to be aware of when using Visual Basic's random number generator is that each time the program is run, under ordinary circumstances the same series of numbers will be generated. To ensure a different set of numbers, use the Randomize statement.
Typically, Randomize is issued when your program is started, although it doesn't hurt to issue it as many times as you want.
The Randomize Function
The format of Randomize is
RandomizeRandomize reseeds the random number generator resulting in a different sequence of numbers each time your program is run.
Example
Randomize
When performing mathematical operations, it is sometimes necessary to know the sign of a number, or whether it is equal to zero. For example, before dividing a number by a variable, it is good to know whether that variable is equal to zero. If it is, then the result of the division will be indeterminate and shouldn't be performed because an error would be generated in your program. If you are about to take an even root of a number, you will most likely want to know if that number is negative.
The Sgn function determines whether a number is equal to zero or greater than or less than zero all in one step. This is better than first testing the value to see if it is equal to zero and then testing to see if it was greater than zero or less than zero. The Sgn function is faster and more compact. One real purpose of the Sgn function is to determine whether a value is negative before textually formatting it.
The Sgn Function
The format of Sgn is
Sgn(number)If the number is equal to 0, Sgn returns 0. If the number is less than 0, Sgn returns "1. If the number is greater than 0, Sgn returns 1.
Example
ResultVal = Sgn(-3)When this is run, ResultVal will contain the value "1 because the number (--3) is less than 0.
In some calculations, such as square roots, negative numbers are not acceptable (unless you are prepared to write special and highly complex routines for handling imaginary numbers). Sometimes the calculation can continue by ensuring the number is positive. You could test a number before using it and multiply it by "1 if it was negative, thereby changing its sign, but there is an easier way.
The guaranteed result of the Abs function is a positive number.
The Abs Function
The format of Abs is
Abs(number)This function returns the positive value of number. Thus, if number was originally negative, it will be changed to positive. If number was positive, it will remain unchanged.
Example
ValidResult = Sqr(Abs(UnknownVariable))Using the Abs function within the square root function guarantees that an error won't occur if UnknownVariable is negative.
Formatting refers to the way in which you alter the looks of the information your program presents. The Format function allows you to easily format values for output. For example, consider the number 3.14159265359. When formatted as currency, it is shown as $3.14. When formatted as a percent, it is displayed as 314.16%. When formatted as a medium time, it gives 03:23 a.m. Formatting puts the number in context.
The Format Function
The format of Format isFormat(expression[, fmt])Where expression is a numeric or string expression and fmt is any of a wide range of different formats that can be applied. (For information on available formats, see either the on-line help or the Visual Basic Language Reference.)
Example
Dividends = 4423.7463 Text1 = Format(Dividends, "Currency")In this example, Text1 would display Dividends as $4,423.75.
All the preceding examples use one of the predefined formats. You also can create your own formats.
There are many additional standard and optional formats available in Visual Basic. Refer to on-line help or the Visual Basic Language Reference for an extensive list.
Two functions don't fit into any of the categories discussed so far. One causes your computer to make a beeping noise and the other helps coordinate program execution.
Did you ever wish your computer could talk to you? Visual Basic can't make that happen (at least not without some third party software), but it can give you an audible cue. This cue is given when you use the Beep statement.
TheBeep Statement
The format of Beep is
BeepExample
BeepCauses a short tone to be emitted by your PC.
You can increase the length of the tone by issuing Beep a number of times as in Listing 5.7.
Listing 5.7 Generating longer beeps.
For BeepCounter = 1 to 100 Beep Next BeepCounter
While the Beep command provides no direct means for controlling the frequency of the tone it issues, you can exercise a little control as shown in Listing 5.8.
Listing 5.8 Controlling beep frequency
For BeepDuration = 1 To 100 Beep For BeepPause = 1 To 1000 Next BeepPause Next BeepDuration
The sound of a single Beep command depends on your system and may vary if run on a different computer. As a result, the sound made by these code snippets also will vary.
With Windows, you can run more than one program at the same time. Well, almost at the same time. Actually each program takes a turn using the computer's central processing unit, or CPU. Because the CPU executes hundreds of thousands of instructions each second, it can give the appearance of doing many things at once by doing only one thing at a time, but switching quickly between them.
Using the multitasking capabilities of Windows is somewhat like driving. Have you ever tried to pull into heavy traffic from a side street that doesn't have a traffic light? Sometimes you get lucky and another driver will let you in almost immediately. Sometimes those other drivers aren't very cooperative and you wait for a long time.
The programs you run under Windows operate in a similar fashion. They must cooperate with one another in sharing the CPU, or some programs may have to wait a long time before getting a chance to execute. This is a frustrating experience, especially for those who know that it was an oversight on the part of the programmer.
When using Visual Basic, the mechanism for actively cooperating is DoEvents. By using DoEvents, you're telling Windows to check if any other processes need access to the CPU. If none are waiting, then your program continues execution; if there are waiting processes, Windows pauses your program while the others get a chance to run.
To see the implications of programs without DoEvents, examine this code:
Listing 5.9 Code without DoEvents.
For CounterOne = 1 to 10000
For CounterTwo = 1 to 10000
TempVar = Sin(TempVar)
Next CounterTwo
Next CounterOne
When running, this program gives the appearance that the computer is locked-up. What has really happened is that Visual Basic is performing a computationally intensive operation--calculating the sine of a variable 100,000,000 times.
DoEvents
You can use DoEvents as either a statement or a function. The only difference is that the function returns the number of visible forms.
The format of the DoEvents statement is
DoEventsThe format of the DoEvents function is
DoEvents ()ExamplesDoEventsYields control of the CPU to Windows so it can perform any waiting tasks. When those tasks are finished, control is returned to Visual Basic.
NumberOfVisibleForms = DoEvents ()When executed, NumberOfVisibleForms will equal the number of open windows in your application.
Visual Basic is not letting any other processes, including Windows, access the CPU. Because Windows can't access the CPU, it can't respond to your keystrokes or mouse clicks. Windows will queue up a number of your commands and execute them the next chance it gets, but that could take a while. Running the preceding code on a 66MHz 486 takes about one hour to complete. Upon completion, Windows goes on about its normal business; but during that time, the computer will not respond to your input.
Listing 5.10 shows how to insert DoEvents so that Windows remains responsive to your commands.
Listing 5.10 Code with DoEvents
For CounterOne = 1 to 100000
For CounterTwo = 1 to 100000
DoEvents
" additional instructions here
Next CounterTwo
Next CounterOne
When used this way, the DoEvents statement will allow other programs a chance to execute while your program is running.
DoEvents aren't free. They are somewhat costly with respect to time. In Listing 5.10, the DoEvents statement takes about four times as long to execute as the Sin function. Most loops, however, consist of more than just a single function call, so the ratio of time spent on productive work versus the time spent on DoEvents will be greater. Besides, even if it takes somewhat longer to execute your code you can be doing something else in the meantime, instead of just sitting and watching an unresponsive system.
The DoEvents statement costs time because when called, Windows must spend some time seeing if any other processes want to use the CPU. If you use DoEvents every time through a looping process, the aggregate time can be quite high. One solution is to call DoEvents less frequently. By moving the DoEvents call into an outer loop, as shown in Listing 5.11, it is called 100,000 times less frequently. This is still frequent enough to allow some other processing to occur if needed, but not so infrequent as to give the appearance of the system being locked up.
Listing 5.11 Better placement of DoEvents
For CounterOne = 1 to 100000
DoEvents
For CounterTwo = 1 to 100000
" additional instructions here
Next CounterTwo
Next CounterOne
The most useful place for the insertion of DoEvents is inside time-intensive loops.
DoEvents isn't the only way in which Visual Basic yields to Windows. On its own, Visual Basic will occasionally give Windows an opportunity to run, but DoEvents is the easiest way for you to ensure Windows has an opportunity to perform other work.
Using DoEvents in your Visual Basic programs will provide the same feeling you get when someone is kind enough to stop and let you into the flow of traffic.
In this chapter, you have sampled the wide variety of functions which make Visual Basic so powerful. You learned the following:
Copyright © 1994, Macmillan Publishing USA, a Simon and Schuster Macmillan Company.
Crash Course in Visual Basic 3