Logo

Built-In Functions

 

Overview of Built-In Procedure

 

Introduction 

A procedure is referred to as "built-in" if it shipped with your language. To make your job a little easier, Microsoft Visual Basic comes equipped with many functions that you can use right away in your program. Based on this, before creating your own function, first check whether the functionality you are looking is already implementing in one of the available procedures because those that ship with Visual Basic are highly reliable and should be preferred.

Before using a built-in procedure, you must of course be familiar with it. This comes either by consulting the documentation or by experience. This means that you must know its name, its argument(s), its return value, and its role.

 

Conversion Functions

The first action you should take when dealing with a value or an expression is to convert it to the appropriate type. There are various conversion functions adapted to the different possible kinds of values. The general syntax of the conversion functions is:

ReturnType = FunctionName(Expression)

The Expression could be of any kind. For example, it could be a string or value the user would have entered in a form. It could also be the result of a calculation performed on another field or function. The conversion function would take such a value, string, or expression and attempt to convert it. If the conversion is successful, the function would return a new value that is of the type specified by the ReturnType in our syntax.

The conversion functions are as follows:

 
Function  
Name Return Type Description
CBool Boolean Converts an expression into a Boolean value
CByte Byte Converts an expression into Byte number
CDate Date Converts and expression into a date or time value
CDbl Double Converts an expression into a flowing-point (decimal) number
CInt Integer Converts an expression into an integer (natural) number
CCur Currency Converts an expression into a currency (monetary) value
CLng Long Converts an expression into a long integer (a large natural) number
CSng Single Converts an expression into a flowing-point (decimal) number
CStr String Converts an expression into a string
 

Practical Learning: Using Conversion Functions

  1. Start a new project and create a form as follows:
     

  2. Here are the names of the controls (the three left labels and the horizontal lines are provided "as is"):

    (Name) Caption (Name) Caption
    frmOperations Operations fraOperations Operations
    lblMainTitle Algebraic Operations optAddition Addition
    txtNumber1   optSubtraction Subtraction
    txtNumber2   optMultiplication Multiplication
    txtResult Result optDivision Division
  3. On the Project window, click the View Code button

  4. On the Object combo box, select optAddition.

  5. Since its default event is Click, implement it as follows:

    Private Sub optAddition_Click()
        Dim dblNumber1 As Double
        Dim dblNumber2 As Double
        Dim dblResult As Double
        
        dblNumber1 = CDbl(txtNumber1.Text)
        dblNumber2 = CDbl(txtNumber2.Text)
        dblResult = dblNumber1 + dblNumber2
        
        txtResult.Text = dblResult
    End Sub
  6. Implement the Click event of the other option buttons the (exact) same way, only changing the sign in the dblResult line. Here is the code:

    Private Sub optDivision_Click()
        Dim dblNumber1 As Double
        Dim dblNumber2 As Double
        Dim dblResult As Double
        
        dblNumber1 = CDbl(txtNumber1.Text)
        dblNumber2 = CDbl(txtNumber2.Text)
        dblResult = dblNumber1 / dblNumber2
        
        txtResult.Text = dblResult
    End Sub
    
    Private Sub optMultiplication_Click()
        Dim dblNumber1 As Double
        Dim dblNumber2 As Double
        Dim dblResult As Double
        
        dblNumber1 = CDbl(txtNumber1.Text)
        dblNumber2 = CDbl(txtNumber2.Text)
        dblResult = dblNumber1 * dblNumber2
        
        txtResult.Text = dblResult
    End Sub
    
    Private Sub optSubtraction_Click()
        Dim dblNumber1 As Double
        Dim dblNumber2 As Double
        Dim dblResult As Double
        
        dblNumber1 = CDbl(txtNumber1.Text)
        dblNumber2 = CDbl(txtNumber2.Text)
        dblResult = dblNumber1 - dblNumber2
        
        txtResult.Text = dblResult
    End Sub
  7. To test the form, press F5.

  8. Please, make sure you type a number, and a number other than 0, in the Second Number text box, especially before clicking the Division option button. This is because we didn't write a conditional statement that would check the content of those text boxes, and we know that it is "nasty" to divide a number by 0. Conditional statements will be studied later: one lesson at a time

String-Based Functions

 

Introduction

A string-based function is one that deals with functions; either it manipulates them or returns them. Microsoft Visual Basic allows you to be specific about the return value you are expecting. Some of the functions you will be using can be configured to return exactly a string. Such functions use the $ suffix that states it clearly. 

 

Message Boxes

A message box is a special form used to display a piece of information to the user. As opposed to a regular form, the user cannot type anything on the box. There are usually two kinds of dialog boxes you will create: one that simply displays information and one that expects the user to make a decision.

To create a message box, you can use the MsgBox function. There are two techniques to use it. To display a simple message with just an OK button, use the MsgBox method whose syntax is

MsgBox Message

The parameter, Message, is the string to present to the user. As a normal, it should be passed in double-quotes. Here is an example:

Private Sub Form_Load()
    MsgBox "Welcome to the wonderful world of Microsoft Visual Basic"
End Sub

When the above version of the the MsgBox function is used, a rectangular form (we will learn later on that this type of form is called a dialog box) is presented to the user, display a string message and an OK button:

Message Box

Another version of the MsgBox function allows you to present a message that asks a question to the user, expecting a decision. This version displays a more informative prompt with more than one button. The user makes a decision by clicking one of the presented buttons. After the user has clicked a button, you can then retrieve the result and use it as you see fit. The syntax of this version is:

MsgBox Message, [Buttons], [Title], [HelpFile], [Context]

The Message argument is the string that the user will see displaying on the message box. As a string, you can display it in double quotes. You can also create it from other pieces of strings. The Message argument can be made of up to 1024 characters. To display the Message on multiple lines, you can use either the constant vbCrLf or the combination Chr(10) & Chr(13) between any two strings.

Besides the Message parameter, this version allows you to display more than one button. If you don't need to, you don't have to specify the buttons. If you don't, the message box would appear with only an OK button. Otherwise, you can specify what buttons to display. This is done using the Buttons argument. There are different kinds of buttons available and Visual Basic recognizes them by a numeric value assigned to each. The buttons are

Button Value Display
vbOKOnly 0
vbOKCancel 1
vbAbortRetryIgnore 2
vbYesNoCancel 3
vbYesNo 4
vbRetryCancel 5

Here is an example of a message box that display a Yes and a No buttons:

Private Sub Form_Load()
    MsgBox "Are you ready to rumbleeeeeeeeeee", vbYesNo
End Sub

This would produce:

A Message Box with various buttons

When a message box displays more than one button, one of the buttons usually has a thick button. That button is also called the default button. If the user presses Enter upon reading the message, the compiler would behave as if the default button was clicked. There are some buttons that are set automatically as default when you create the message box. If you don't like the set button to be the default, you can specify which one you prefer as default. To do that combine a second value with one of the above values for the buttons. You can set the default argument using the following table

Option Value
vbDefaultButton1  0
vbDefaultButton2  256
vbDefaultButton3  512
vbDefaultButton4  768

To combine one of these values with one of the buttons, use the OR operator between them. Here is an example:

Private Sub Form_Load()
    MsgBox "Are you ready to rumbleeeeeeeeeee", vbYesNo Or vbDefaultButton2
End Sub

This would produce:

A Message Box with a different default button

These additional buttons can be used to further control what the user can do:

Constant  Value Description
vbApplicationModal 0  
vbSystemModal 4096  

Besides the message and the button(s), you can also display a friendly icon on the message box. To do that, combine the button value with one of the following:

Icon Value Description
vbCritical 16
vbQuestion 32
vbExclamation 48
vbInformation  64

Here is an example:

Private Sub Form_Load()
    MsgBox "Are you ready to rumbleeeeeeeeeee", vbYesNo Or vbQuestion
End Sub

This would produce:

A Message Box with a friendly icon

As you can see on the message boxes we have used so far, by default, a message box displays the name of the application it belongs to in its title bar. If you want, you can display your own title. This is done using the Title argument which is also called the caption of the message box. It is a string whose word or words you can enclose between parentheses or that you can get from a created string.

If your application is using a help file, you can specify this and let the message box use it. The HelpFile argument is a string that specifies the name of the help file, and the Context argument provides the number that corresponds to the appropriate help topic for the message box.

The way we have been using it so far, the MsgBox is called a method. If you want to use it as a function, that is, if you want it to return a value, you must call it as a function. In other words, its list of arguments must be included in parentheses. The above message can be created as follows:

Private Sub Form_Load()
    MsgBox("Are you ready to rumbleeeeeeeeeee", vbYesNo Or vbQuestion)
End Sub

When treated as a function, MsgBox returns a value. This value corresponds to the button the user clicks on the message box. Depending on the buttons the message box is displaying, after the user has clicked, the MsgBox function can return one of the following values:

Button Return Value
vbOK 1
vbCancel 2
vbAbort 3
vbRetry 4
vbIgnore 5
vbYes 6
vbNo 7

 

Practical Learning: Using Message Boxes

  1. Create a new Standard EXE project
  2. Design the form as follows:
     
  3. The names of the buttons are btnMessage1, btnMessage2, btnMessage3, btnMessage4, btnMessage5, btnMessage6, btnMessage7, and btnMessage8
    Don't yet save the project.
  4. To start, double-click the Exit button to access its Click event.
  5. Implement it as follows:
    Private Sub cmdExit_Click()
        Unload Me
        End
    End Sub
  6. The simplest message box simply displays a message to the user. As an example, double-click the Message 1 button to access its Click event.
  7. Implement it as follows:
    Private Sub cmdMessage1_Click()
        MsgBox "As simple as it can get"
    End Sub
  8. To test the form, press F5.
  9. On the form, click the Message 1 button.
  10. Notice that a message box displays. Also notice the caption on the title bar displays Project1.
  11. Click OK to close the message box.
  12. Now, save the project as prjMessages
  13. Test the form again. And click the Message 1 button.
  14. Notice that the caption on the title bar has changed.
  15. Instead of the title bar displaying the name of the project as the caption, you can set your desired caption. This is done through the 3rd argument of the MsgBox function. To see an example, on the form, double-click the Message 2 button. Since the line we want to display is long for our Visual Basic Code Editor window, we will segment it in two lines although it will be displayed on one line only.
  16. Implement it as follows:
    Private Sub cmdMessage2_Click()
        MsgBox "Before formatting a floppy disk, " & _
            "make sure you know its content", , _
            "Disk Formatting Instructions"
    End Sub
  17. To test the form, press F5.
  18. Click the Message 2 button. Notice that the title bar displays an appropriate caption.
  19. Click one of the buttons and close the form.
  20. When creating a message box using the MsgBox function, you can decide which button you want to use, using one of the constants we have listed earlier.
    To see an example, double-click the Message 3 button.
  21. Implement the Click event of the button as follows:
    Private Sub cmdMessage3_Click()
        MsgBox "This will be your only warning", _
        vbOKOnly + vbExclamation, _
            "Attention! Attention!! Attention!!!"
    End Sub
  22. To test the form, press F5.
  23. Experiment with the buttons and see what they display.
  24. To close the running form, click its close button .
  25. If you want to display a message on different lines, you can use the vbCrLf constant. As an example, implement the Click event of the Message 4 button as follows:
    Private Sub cmdMessage4_Click()
        MsgBox "You are about to embark on a long journey." & _
            vbCrLf & "If your courage is still fresh, " _
            & "please let us know!", _
             vbOKCancel + vbQuestion, _
             "Accept or Cancel the Mission"
    End Sub
  26. Test the form and experiment with the buttons.
  27. Close the form to get back to Visual Basic.
  28. You can also display a message on various lines using the Chr() function. To see an example, implement the Click event of the Message 5 button as follows:
    Private Sub cmdMessage5_Click()
        MsgBox "This message usually appears when trying " & _
            "to format a floppy disk while the floppy drive " _
            & "is empty. " & Chr(13) & Chr(10) _
            & "When or if this happens, make sure you have a " _
            & " floppy disk in the floppy drive.", _
            vbAbortRetryIgnore + vbCritical, _
            "Floppy Disk Formatting"
    End Sub
  29. To test the form, press F5.
  30. Close the running form, click its close button Close
  31. The usefulness of the MsgBox function is demonstrated in your ability to perform an action based on the button the user has clicked on the message box function. Indeed, the implementation we have used so far were on the MsgBox method. If you want to get the button that the user has clicked, you have to use the function itself. The true capture of the clicked is revealed by your finding out the clicked button. This is done using conditional statements that we have not learned so far. Therefore, we will just learn how to implement the function and how to assign a response button to it; throughout this tutorial, and whenever necessary, we will eventually see what to do when a certain button has been clicked. To see an example, implement the Click event of the Message 6 button as follows:
    Private Sub cmdMessage6_Click()
        Dim intResponse As Integer
        
        intReponse = MsgBox("Your printing configuration " _
            & "is not fully set." & vbCrLf _
            & "If you are ready to print, click" & vbCrLf & _
            "(1) Yes: To print the document" & vbCrLf & _
            "(2) No: To configure printing" & vbCrLf & _
            "(3) Cancel: To dismiss printing", _
            vbYesNoCancel + vbInformation, _
            "Critical Information")
    End Sub
  32. To test the form, press F5.
  33. Close the running form, click its close button Close
  34. When a message box display, one of the buttons, if more than one is displaying, has a thicker border than the other(s); such a button is called the default button. By default, this is the 1st or most left button on the message box. If you want to control which button would be the default, use one of the default constant buttons listed above. To see an example, implement the Click event of the Message 7 button as follows:
    Private Sub cmdMessage7_Click()
        Dim intAnswer As Integer
        
        intAnswer = MsgBox("Do you want to continue this " _
            & "operation?", _
            vbYesNoCancel + vbQuestion + vbDefaultButton2, _
            "National Inquiry")
    End Sub
  35. To test the form, press F5.
  36. Close the running form, click its close button Close.
  37. Although the user cannot type on a message box, not only can you decide what it displays, but you can also use string variables that would be available only when the form is running. We will see a lot of examples throughout this tutorial. But as an example, implement the Click event of the Message button as follows:
    Private Sub cmdMessage8_Click()
        Dim strEmplName As String
        Dim intInquiry As Integer
        
        strEmplName = txtEmployeeName.Text
        intInquiry = MsgBox("Hi, " & strEmplName & Chr(13) & _
            "I think we met already." & vbCrLf & _
            "I don't know when. I don't know where." & vbCrLf & _
            "I don't know why. But I bet we met somewhere.", _
            vbYesNo + vbInformation, _
            "Meeting Acquaintances")
    End Sub
  38. To test the form, press F5.
  39. On the Employee Name text box, type Walter Bennett
  40. Click the Message 8 button and see the result
  41. Click one of the buttons to close the message box
  42. Close the running form, click its close button Close

 

The Input Box

Like a message box, an input box is a (relatively) small form (in reality, it is a dialog box) that displays a message to the user. Unlike a message box, an input box presents a small text box that expects the user to enter a value. After using it, the user can either send the form with the new value or dismiss it without any change.

To create an input box, you can use the InputBox function procedure prompts the user to enter some information in a message box, and the function will return the content of that box.

The Character To ASCII Conversion

The Chr function is used to associate an entered character with its ASCII character equivalent. It could be used to convert a number to a character. It could also be used to break a line in a long expression. The syntax of the Chr function is:

Chr(Number)

A combination of Chr(13) and Chr(10) would break a line in an expression.

 

Case Conversion

If you are presented with a string or an expression whose cases must be the same, you can convert all of its characters in either uppercase or lowercase.

To convert a character, a string or an expression to uppercase, you can call the UCase or the UCase$ function. These functions take one argument as the string or expression to be considered. The syntaxes are:

Function UCase(Letter As Char) As Char
Function UCase(Expression As String) As String

The first version receives one character as argument. If the character is already in uppercase, it would be return the same. If the character is not a readable character, no conversion would happen and the function would return it. If the character is in lowercase, it would be converted to uppercase and the function would then return the uppercase equivalent.

The second version considers the argument supplied as a string. Any letter that is in lowercase in the string would be converted to uppercase. Any letter that is in uppercase would be preserved and would not be changed. Any non-alphabetic character in the string would be kept "as is".

 

Logical Functions

 

Is it Empty?

A logical function is one that checks whether an expression is true or false and then return a Boolean value.

The IsEmpty function check whether a field is empty. Its syntax is:

IsEmpty(Expression)

In this case, the Expression argument will be checked. If it is empty, the IsEmpty function returns True. If the expression or field is not empty, that is, if it contains something, the function returns False.

 

Is it Null?

Another problem you may encounter when involving an operation or the contents of a control is whether it has never contained a value. This operation is sometimes confused with that of checking whether a field is empty. Here is the difference (it is important to understand this because it is used in many other environments):

  • Imagine a text box control is used for first name and the field displays Paul. If the user comes to that record, the field is not empty, it already contains a name, which is this case is Paul. If the user clicks in the field and deletes Paul, the field becomes empty. It is not null
  • Imagine a field is used for first name. If the user comes to a new record, the field for the first name may be empty (if you did not give it a default value). In this case, the field is Null: it is not empty because it has never contained anything. If the user types a name, and then deletes it, the field is not considered Null anymore: it has become empty

To check whether an expression or the value of a control is null, you can call the IsNull() function. Its syntax is:

IsNull(Expression)

Also used on fields, the IsNull() function checks the state of a field (remember, this functions does not check whether a field is empty or not; it checks if the field has ever contained a value). If the field it null, this function returns True. If the field is not null, this function returns False.

 

Date and Time Functions

 

Current Data and Time

Microsoft Visual Basic provides various functions to perform date and time related operations. These functions allow you to add dates or times, find the difference between dates or times, or add constant values to dates or times.

The current date is represented by a function called Date. The Date() function is used to get the system date of the computer. You can use it to display today's date, provided your computer has the correct date.

The current time of the computer is represented by a function called Time. The Time() function is used to get the system time of the computer.

The Date() and Time() functions can be combined and are represented by a function called Now.

Practical Learning: Using Date and Time

  1. On the main menu of Microsoft Visual Basic, click View -> Immediate Window.

  2. In the Immediate window, type ?Date and press Enter

  3. Notice that the system date is displayed.

  4. Still in the Immediate window, type ?Time and press Enter

  5. Again, in the Immediate window, type ?Now and press Enter

 

Day - Month - Year

The Day function is used to get the numeric value that represents a day in the month. It ranges from 1 to 31 included.

The formula of the Day function is Day(DateValue)

The Month function displays the numeric month of a date. It ranges from 1 to 12 included.

The formula of the Month function is Month(DateValue)

The Year function returns the numerical year of a date.

The formula is the Year function is Year(DateValue)

 

Practical Learning: Using Day, Month, and Year Values

  1. In the Immediate window, type ?Day(#12/14/00#) and press Enter
  2. Notice that the result is 14 as the numeral day of that date
  3. Still in the Immediate window, type ?Day(Date()) and press Enter
  4. Notice that the result is the numeric day of the system date
  5. In the Immediate window, type ?Day(Date()+2) and press Enter
    This would display the numeral of 2 days from today
  6. In the Immediate window, type ?Month("June 12, 1990") and press Enter
  7. Notice that the result in 6, because June represents the 6th month of the year
  8. In the Immediate window, type ?Month("Tuesday, October 02, 1990") and Press Enter.
    This would result in 10.
  9. In the Immediate window, type ?Month(#02/25/90#) and press Enter
    This produces 2 since February is the 2nd day of the year.
  10. In the Immediate window, type ?Year(Date()) and press Enter.
  11. Notice that this displays the current year of the system date.
 

Adding a Date

The DateAdd function is used to add a date value to another date. It can be used to add a number of days, weeks, months, or years to another date. The formula for the DateAdd function is

DateAdd(Interval, Number, date)

Required, the Interval argument specifies the kind of value you want as a result. This argument will be enclosed between double quotes and can have one of the following values:

Interval Used To Get
s Second
n Minute
h Hour
w Numeric Weekday
ww Week of the Year
d Day
y Numeric Day of the Year
m Month
q Quarter
yyyy Year

Required also, the Number argument specifies the number of units you want to add. If you set it as positive, its value will be added. On the other hand, if you want to subtract, make it negative.

The number represents the units of the Interval argument you want to add.

The date argument is the date to which you want to add the number.

 

Subtracting a Date

The DateDiff function is used to find the difference between two date or time values. It allows you to find the number of seconds, minutes, hours, days, weeks, months, or years from two valid date or time values. The DateDiff function takes 5 arguments, 3 are required and 2 are optional.

The formula of the function is

DateDiff(Interval, Date1, Date2, Option1, Option2)

Required, the Interval argument specifies what kind of value you want as a result. This argument will be enclosed between double quotes and can have one of the following values:

Interval Used To Get
s Second
n Minute
h Hour
w Numeric Weekday
ww Week of the Year
d Day
y Numeric Day of the Year
m Month
q Quarter
yyyy Year

Required also, the Date1 and Date2 argument specify the date or time values that will be used when performing the operation.

By default, the days of a week are counted starting on Sunday. If you want to start counting those days on another day, supply the Option1 argument using one of the following values: vbSunday, vbMonday, vbTuesday, vbWednesday, vbThursday, vbFriday, vbSaturday. There are other variances to that argument.

If your calculation involves weeks or finding the number of weeks, by default, the weeks are counted starting January 1st. If you want to count your weeks starting at a different date, use the Option2 argument to specify where the program should start.

 

Practical Learning: Subtracting Dates

  1. In the Immediate window, type ? DateDiff("d", #12/12/2000#, Now()) and press Enter
  2. Notice this displays the number of days that have since the stated date and today
 

Previous Copyright © 2001-2004-2014 FunctionX, Inc. Next