Home

Introduction to Visual Basic Built-In Functions

 

Overview of Built-In Procedures

 

Introduction 

A procedure is referred to as "built-in" if it shipped with its programming language. To make your job a little easier, the Visual Basic language is equipped with many procedures that you can use right away in your program. Based on this, before creating your own procedure, first check whether the functionality you are looking for is already implementing in one of the available procedures because those that ship with the Visual Basic language 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. The Visual Basic programming language provides one of the richest libraries you will ever see. In fact, it is the richest of the .NET-based languages, giving you access to functions that are not directly available to other languages such as C# or C++/CLI. Because there so many of those functions, we will review only the most usually used. Eventually, when necessary, in other lessons, we may introduce new ones.

 

Conversion Functions

You may recall that when studying data types, we saw that each had a corresponding function used to convert a string value or an expression to that type. As a reminder, 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 expression that would produce a value such as the result of a calculation. 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
CDbl Double Converts an expression into a floating-point number with double precision
CDec Decimal Converts an expression into a decimal number
CInt Integer Converts an expression into an integer (natural) number
CLng Long Converts an expression into a long integer (a large natural) number
CObj Object Converts an expression into an Object type
CSByte SByte Converts an expression into a signed byte
CShort Short Converts an expression into a short integer
CSng Single Converts an expression into a floating-point number with single precision
CUInt UInt Converts an expression into an unsigned integer
CULng ULong Converts an expression into an unsigned long integer
CUShort UShort Converts an expression into an unsigned short integer

These functions allow you to convert a known value to a another type. Besides these functions, the Visual Basic language provides a function named CType. Its syntax is:

CType(expression, typename)

As you can see, the CType() function takes two arguments. The first argument is the expression or the value that you want to convert. An example could be name of a variable or a calculation:

CType(250.48 * 14.05, ...)

The second argument is the type of value you want to convert the first argument to. From what have learned so far, this second argument can be one of the data types we reviewed in Lesson 3. Here is an example:

CType(250.48 * 14.05, Single)

If you choose one of the Visual Basic language's data types, the expression produced by the first argument must be able to produce a value that is conform to the type of the second argument:

  • The conversion from the first argument to the type of the second argument must be possible: the value produced by the first must be convertible to the second arguments. For example, if the first argument is a calculation, the second argument must be a number-based data type. In the same way, you cannot convert a date to a number-based type
  • If the first argument is a number or the result of a calculation, its resulting value must be lower than or up to the range of values of the second argument. Here is an example:
     
    Public Module Exercise
    
        Public Function Main() As Integer
    
            MsgBox(CType(250.48 * 14.05, Single))
    
            Return 0
        End Function
    
    End Module

    This would produce:

    Conversion

  • If the first argument is a number or the result of a calculation that produces an integer or a floating-point number, its resulting value must be convertible to an integer or a floating point number up to the range of values of the second argument. Here is an example:
     
    Public Module Exercise
    
        Public Function Main() As Integer
    
            MsgBox(CType(7942.225 * 202.46, UInteger))
    
            Return 0
        End Function
    
    End Module

    This would produce:

    Conversion

  • If the first argument is a number or the result of a calculation that produces an integer or a floating-point number, the second argument is a number-based data type but whose range cannot hold the resulting value of the first argument, the conversion would not be allowed (the conversion will fail):
     

    Conversion

After the CType() function has performed its conversion, it returns a value that is the same category as the second argument. For example, you can call a CType() function that converts an expression to a long integer. Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim Number As Long

        Number = CType(7942.225 * 202.46, Long)

        Return 0
    End Function

End Module

The function can also return a different type, as long as its type can hold the value produced by the expression. Here are two examples:

Public Module Exercise

    Public Function Main() As Integer
        Dim Number As UInteger

        Number = CType(7942.225 * 202.46, Long)

        Return 0
    End Function

End Module

Or

Public Module Exercise

    Public Function Main() As Integer
        Dim Number As Single

        Number = CType(7942.225 * 202.46, Long)

        Return 0
    End Function

End Module

If you try storing the returned value into a variable that cannot hold it, you would receive an error:

Conversion

 

The Memory Used by a Data Type

In Lesson 3, we saw that different data types are used to store different values. To do that, each data type requires a different amount of space in the computer memory. To know the amount of space that a data type or a variable needs, you can call the Len() function. Its syntax is:

Public Shared Function Len( _
   ByVal Expression As { Boolean | Byte | SByte | Char | Double |
   Integer | UInteger | Long | ULong | Object | Short | UShort |
   Single | String | DateTime | Decimal } _
) As Integer

To call this function, you can declare a variable with a data type of your choice and optionally initialize with the appropriate value, then pass that variable to the function. Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim Value As Integer

        Value = 774554

        MsgBox(Value & " needs " & Len(Value) & " bytes to be stored in memory.")
        Return 0
    End Function

End Module

This would produce:

Length

The Message Box

 

Introduction

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

A message box is created using the MsgBox function. Its syntax is:

Public Function MsgBox( _
   ByVal Prompt As Object, _
   Optional ByVal Buttons As MsgBoxStyle = MsgBoxStyle.OKOnly, _
   Optional ByVal Title As Object = Nothing _
) As MsgBoxResult

The MsgBox() function takes three arguments and only the first one is required.

The Message of a Message Box

The Prompt argument is the string that the user will see displaying on the message box. As a string, you can display it in double quotes, like this "Your credentials have been checked.". Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        MsgBox("Your credentials have been checked.")
        Return 0
    End Function

End Module

This would produce:

Message Box

You can also create the message from other pieces of strings. The Prompt argument can be made of up to 1024 characters. To display the Prompt on multiple lines, you can use either the constant vbCrLf or the combination Chr(10) & Chr(13) between any two strings. Here is an example:

Public Function Main() As Integer
    MsgBox("Your logon credentials have been checked." & _
           vbCrLf & "To complete your application, please " & _
           "fill out the following survey")
    Return 0
End Function

This would produce:

Message Box

The Buttons of a Message Box

The Buttons argument specifies what button(s) should display on the message box. There are different kinds of buttons available and the Visual Basic language. The Buttons options are primary members of an enumerations named MsgBoxStyle. The members of the MsgBoxStyle enumeration that produce buttons are:

Button Value Alternative Numeric Value Display
MsgBoxStyle.OKOnly vbOKOnly 0 OK
MsgBoxStyle.OKCancel vbOKCancel 1 OK Cancel
MsgBoxStyle.AbortRetryIgnore vbAbortRetryIgnore 2 Abort Retry Message Box Button: Ignore
MsgBoxStyle.YesNoCancel vbYesNoCancel 3 Yes Message Box Button: No Cancel
MsgBoxStyle.YesNo vbYesNo 4 Yes Message Box Button: No
MsgBoxStyle.RetryCancel vbRetryCancel 5 Retry Cancel

When calling the MsgBox() function and specifying the button, you can use either a member of the MsgBoxStyle enumeration or one of the above constant numeric values. Here is an example that displays the Yes and the No buttons on the message box:

Public Function Main() As Integer
    MsgBox("Your logon credentials have been checked " & _
           "and your application has been approved: Congratulations!" & _
           vbCrLf & "Before leaving, would you like " & _
           "to take our survey survey now?", MsgBoxStyle.YesNo)
    Return 0
End Function

This would produce:

The Buttons of a Message Box

The Icon on a Message Box

Besides the buttons, to enhance your message box, you can display an icon in the left section of the message box. To display an icon, you can use or add a member of the MsgBoxStyle enumeration. The members that are meant to display an icon are:

Icon Constant Alternative Numeric Value Description
MsgBoxStyle.Critical vbCritical 16 Icon Stop
MsgBoxStyle.Question vbQuestion 32 Question Question
MsgBoxStyle.Exclamation vbExclamation 48 Exclamation Exclamation
MsgBoxStyle.Information  vbInformation  64 Information Information

To use one of these icons, you must combine the value of the button to the desired value of the icon. To perform this combination, you use the OR operator. Here is an example:

Private Sub cmdMessageBox_Click()
    Dim iAnswer As Integer
    
    iAnswer = MsgBox("Your logon credentials have been checked " & _
                    "and your application has been approved: Congratulations!" & _
                     vbCrLf & "Before leaving, would you like " & _
                     "to take our survey survey now?", vbYesNo Or vbQuestion)
End Sub

This would produce:

The Icon of a Message Box

When calling the MsgBox() function, if you want to show one or more buttons and to show an icon, you can use either two members of the MsgBoxStyle enumeration using the OR operator, or you can add one of the constant values of the buttons to another contant values for an icon. For example,  3 + 48 = 51 would result in displaying the buttons Yes, Ne, and Cancel, and the exclamation icon.

The Default Button of a Message Box

If you create a message box with more than one button, the most left button usually has a thick border, indicating that it is the default. If the user presses Enter after viewing the button, the effect would be the same as if he had clicked the default button. If you want, you can designate another button as the default. To do this, you can use or add another member of the MsgBoxStyle enumeration. The members used to specify the default button are:

Default Button Constant Alternative Numeric Value If the message box contains more than one button, the default would be
MsgBoxStyle.DefaultButton1  vbDefaultButton1  0 The first button
MsgBoxStyle.DefaultButton2  vbDefaultButton2  256 The second button
MsgBoxStyle.DefaultButton3  vbDefaultButton3  512 The third button

Once again, to specify a default value, use the OR operator to combine a Default Button Constant with any other combination. Here is an example:

Public Function Main() As Integer
    MsgBox("Your logon credentials have been checked " & _
           "and your application has been approved: Congratulations!" & _
           vbCrLf & "Before leaving, would you like " & _
           "to take our survey survey now?", _
           MsgBoxStyle.YesNo Or _
    	       MsgBoxStyle.Question Or MsgBoxStyle.DefaultButton2)
    Return 0
End Function

This would produce:

The Default Button of a Message Box

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

Constant  Value Effect
MsgBoxStyle.ApplicationModal 0 The user must dismiss the message box before proceeding with the current database
MsgBoxStyle.SystemModal 4096 The user must dismiss this message before using any other open application of the computer
 

The Title of a Message Box

The Title argument is the caption that would display on the title bar 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. The Title argument is optional. As you have seen so far, if you omit, the message box would display the name of the application on the title bar. Otherwise, if you want a custom title, you can provide it as the third argument to the MsgBox() function. The caption can be a simple string. Here is an example:

Public Function Main() As Integer
    MsgBox("Your logon credentials have been checked " & _
           "and your application has been approved: Congratulations!" & _
           vbCrLf & "Before leaving, would you like " & _
           "to take our survey survey now?", _
           MsgBoxStyle.YesNo Or MsgBoxStyle.Question, _
           "Crofton Circle of Friends - Membership Application")
    Return 0
End Function

This would produce:

The Title of a Message Box

Notice that the caption is now customized instead of the name of the application. The caption can also be a string created from an expression or emanating from a variable or value.

The Returned Value of a Message Box

The MsgBox() function can be used to return a value. This value corresponds to the button the user clicked on the message box. Depending on the buttons the message box is displaying, after the user has clicked, the MsgBox() function can return a value. The value can be a member of the MsgBoxResult enumeration or a constant numeric value recognized by the Visual Basic language. The value returned can be one of the following values:

If the user click The function returns or Numeric Value
OK MsgBoxResult.OK vbOK 1
Cancel MsgBoxResult.Cancel vbCancel 2
Abort MsgBoxResult.Abort vbAbort 3
Retry MsgBoxResult.Retry vbRetry 4
Ignore MsgBoxResult.Ignore vbIgnore 5
Yes MsgBoxResult.Yes vbYes 6
No MsgBoxResult.No vbNo 7

The Input Box

 

Introduction

The Visual Basic language provides a function that allows you to request information from the user who can type it in a text field of a dialog box. The function used to accomplish this is called InputBox and its basic syntax is:

Public Function InputBox( _
   ByVal Prompt As String, _
   Optional ByVal Title As String = "", _
   Optional ByVal DefaultResponse As String = "", _
   Optional ByVal Xpos As Integer = -1, _
   Optional ByVal YPos As Integer = -1 _
) As String

Presenting the Message

The most basic piece of information you can provide to the InputBox() function is referred to as the prompt. It should be a string that the user will read and know what you are expecting. Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        InputBox("Enter your date of birth as mm/dd/yyyy")
        Return 0
    End Function

End Module

This would produce

The Prompt of an Input Box

Upon reading the message on the input box, the user is asked to enter a piece of information. The type of information the user is supposed to provide depends on you, the programmer. Therefore, there are two important things you should always do. First you should let the user know what type of information is requested. Is it a number (what type of number)? Is it a string (such as the name of a country or a customer's name)? Is it the location of a file (such as C:\Program Files\Homework)? Are you expecting a Yes/No True/False type of answer (if so, how should the user provide it)? Is it a date (if it is a date, what format is the user supposed to enter)? These questions mean that you should state a clear request to the user and specify what kind of value you are expecting. For example, instead of the question above, you can implement the InputBox() function as follows:

Public Function Main() As Integer
    InputBox("Please enter your date of birth as mm/dd/yyyy")
    Return 0
End Function

This would produce:

Prompt

Another solution, also explicit enough, consists of providing an example to the user.

The Title of an Input Box

The second argument to the InputBox() function allows you to optionally specify the title of the input box. This is the string that would appear on the title bar. Since this is an optional argument, if you don't pass it, the input box would display the name of the application. Otherwise, to display your own title bar, pass the Title argument.

The title is passed as a string. Here is an example:

Public Function Main() As Integer
    InputBox("Please enter your date of birth as mm/dd/yyyy", _
             "Student Registration")
    Return 0
End Function

This would produce:

The Title of an Input Box

Notice that the caption is now customized instead of the name of the application. The caption can also be a string created from an expression or emanating from a variable or value.

The Default Value of an Input Box

Sometimes, even if you provide an explicit request, the user might not provide a new value but click OK. The problem is that you would still need to get the value of the text box and you might want to involve it in an expression. You can solve this problem and that of providing an example to the user by filling the text box with a default value. To support this, the InputBox() function provides the third argument.

To present an example or default value to the user, pass a third argument to the InputBox() function. If you want to use this argument to provide an example the user can follow, provide it with the right format. Here is an example:

Public Function Main() As Integer
    InputBox("Enter Student Name:", _
             "Student Registration", "John Doe")

    Return 0
End Function

Here is an example of running the program:

The Default Value of an Input Box

Notice that, when the input box displays with a default value, the value is in the text box and the value is selected. Therefore, if the value is fine, the user can accept it and click OK. Another way you can use the default value is to provide a value the user can accept; that is, the most common or most likely value the user would enter. Here is an example:

Public Function Main() As Integer
    InputBox("Enter Birth State:", _
             "Student Registration", "VA")

    Return 0
End Function

Here is an example of running the program:

The Default Value of an Input Box

Once again, notice that the user can just accept the value and click OK or press Enter.

The Location of the Input Box

By default, when the input box comes up, it displays in the middle of the screen. If you want, you can specify where the input box should be positioned when it comes up. To assist you with this, the InputBox() function is equipped with a fourth and a fifth arguments. The fourth argument specifies the x coordinate of the input box; that is, the distance from its left border to the left border of the monitor. The fifth argument specifies the distance from the top border of the input box to the top border of the monitor.

The Return Value of an Input Box

When the input box displays, after typing a value, the user would click one of the buttons: OK or Cancel. If the user clicks OK, you should retrieve the value the user would have typed. It is also your responsibility to find out whether the user typed a valid value. Because the InputBox() function can return any type of value, it has no mechanism of validating the user's entry. To retrieve the value of the input box dialog when the user clicks OK, you can get the returned value of the InputBox() function.

After being used, the InputBox() function returns a string. Here is an example of getting it:

Public Function Main() As Integer
    Dim StudentName As String

    StudentName = InputBox("Enter Student Name:", _
                           "Student Registration")
    MsgBox("Student Name: " & StudentName)
    Return 0
End Function

You can also get any type of value from an input box. That is, when the InputBox() function exits, thanks to the flexibility of the Visual Basic language, the compiler can directly cast the returned value for you. Here is an example:

Public Function Main() As Integer
    Dim DateOfBirth As Date

    DateOfBirth = InputBox("Please enter your date of birth as mm/dd/yyyy", _
                           "Student Registration")
    MsgBox("Date of Birth: " & DateOfBirth)
    Return 0
End Function

Arithmetic Functions

 

Getting the Integral Part of a Number

If you have a decimal number but are interested only in the integral part, to assist you with retrieving that part, the Visual Basic language provides the Int() and the Fix() functions. Their syntaxes are:

Public Shared Function Int( _
    ByVal Number As { Double | Integer | Long | 
		      Object | Short | Single | Decimal }) _
    As { Double | Integer | Long | Object | Short | Single | Decimal }
Public Shared Function Fix( _
    ByVal Number As { Double | Integer | Long | 
		      Object | Short | Single | Decimal }) _
    As { Double | Integer | Long | Object | Short | Single | Decimal }

Each function must take one argument. The value of the argument must be number-based. This means it can be an integer or a floating-point number. If the value of the argument is integer-based, the function returns the (whole) number. Here is an example

Public Module Exercise

    Public Function Main() As Integer
        Dim Number As Integer

        Number = 286345
        MsgBox(Int(Number))

        Return 0
    End Function

End Module

This would produce:

Int

If the value of the argument is a decimal number, the function returns only the integral part. Here is an example

Public Module Exercise

    Public Function Main() As Integer
        Dim Number As UInteger

        Number = 7942.225 * 202.46
        MsgBox(Int(Number))

        Return 0
    End Function

End Module

This would produce:

Int

 

This function always returns the integral part only, even if you ask it to return a floating-point-based value. Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim Number As Single

        Number = 286345.9924
        MsgBox(Int(Number))

        Return 0
    End Function

End Module

This would produce:

Int

Random Functions

A random number is a value that is not known in advanced until it is generated by the compiler. To assist you with getting a random number, the Visual Basic language provides a function named Rnd. Its syntax is:

Public Shared Function Rnd[(Number)] As Single

This function takes an optional argument. If the argument is not passed, the compiler would simply generate a positive decimal number between 0 and 1. Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        
        MsgBox("Random Number: " & Rnd())

        Return 0
    End Function

End Module

This would produce:

Random Number

You may wonder how the compiler generates a random number. Without going into all the details, in most cases, a compiler refers to the system clock (the clock of the computer on which the application is). It uses a certain algorithm to get that number.

If you call the function like we did above, every time you execute the application, you are likely to get the same result. Depending on how you want to use the number, in some cases, you may want to get a different number every time. To support this, random arithmetic supports what is referred to as a seed. If you do not use a seed, the compiler would keep the same number it generated from the system clock the first time it was asked to produce a random number. Seeding allows the compiler to reset this mechanism, which would result in a new random number.

To assist you with seeding, the Visual Basic language provides a function named Randomize. Its syntax is:

Public Shared Sub Randomize ([ Number ])

This function takes one optional argument. If you can this function without the argument, the compiler would refer to the system clock to generate the new random number. Of course, to get the number, you must call this function before calling Rnd(). Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Randomize()

        MsgBox("Random Number: " & Rnd())

        Return 0
    End Function

End Module

This time, every time the Rnd() function is called, the compiler generates a new number. Instead of letting the compiler refer to the system clock, you can provide your own seed value. To do this, pass a number to the Randomize() function.

We mentioned that the Rnd() function generates a number between 0 and 1. Of course, in some cases you will want the number to be in a higher range, such as between 0 and 100 or between 0 and 100000. All you have to do is to multiply the result to a number of your choice. Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Randomize()

        MsgBox("Random Number: " & CStr(100 * Rnd()))

        Return 0
    End Function

End Module

This would produce:

Random Number

Also notice that the result is a decimal number. If you interested in only the integral part of the number, you can call the Int() function.

Besides Visual Basic's own combination of the Rnd() and the Randomize() functions, the .NET Framework supports random numbers in another way (using Random).
 

Formatting a Value

 

Introduction

So far, after performing a calculation, we were presenting the result "as is". To appropriately display a value, the Visual Basic language provides a function named Format. This function can be used for different types of values The most basic technique consists of passing it an expression that holds the value to display. The syntax of this function is:

Public Shared Function Format( _
   ByVal Expression As Object, _
   Optional ByVal Style As String = "" _
) As String

As mentioned above, this function can be used in various scenarios. The simplest way to use this function is to pass it a number, a string, or a date/time). The function would then produce that number.

Besides the Format() function, the Visual Basic language provides some additional functions we will review below.

Formatting a Number

So far, to display a number, we simply passed it to the MsgBox() function or to another procedure. In some cases, you may want the number to display in a particular format. To control how the number should display, you can pass the second argument of the Format() function. This argument would be passed as a string.

To produce the number in a general format, you can pass the second argument as "g", "G", "f", or "F" .

To display the number with a decimal separator, pass the second argument as "n", "N", or "Standard". Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim Number As Double

        Number = 20502.48

        MsgBox("Number: " & Format(Number, "STANDARD"))
        Return 0
    End Function

End Module

This would produce:

Format

An alternative to get this format is to call a function named FormatNumber. Its syntax is:

Function FormatNumber(
   ByVal Expression As Object,
   Optional ByVal NumDigitsAfterDecimal As Integer = -1,
   Optional ByVal IncludeLeadingDigit As TriState = TriState.UseDefault,
   Optional ByVal UseParensForNegativeNumbers As TriState = TriState.UseDefault,
   Optional ByVal GroupDigits As TriState = TriState.UseDefault
) As String

Only the first argument is required and it represents the value to display. If you pass only this argument, you get the same format as the Format() function called with the Standard option. Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim Number As Double

        Number = 20502.48

        MsgBox("Number: " & Format(Number, "STANDARD"))
        MsgBox("Number: " & FormatNumber(Number))
        Return 0
    End Function

End Module

This would produce the same result as above.

If you call the Format() function with the Standard option, it would consider only the number of digits on the right side of the decimal separator. If you want to display more digits than the number actually has, call the FormatNumber() function and pass a second argument with the desired number. Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim Number As Double

        Number = 20502.48

        MsgBox("Number: " & Format(Number, "STANDARD") & vbCrLf & _
               "Number: " & FormatNumber(Number, 4))
        Return 0
    End Function

End Module

This would display:

Format Number

In the same way, if you want the number to display with less numbers on the right side of the decimal separator, specify that number.

As a third alternative, you can call the Format() function. In reality, the second argument is used to format the number with many more options. To represent the integral part of a number, you use the # sign. To specify the number of digits to display on the right side of the decimal separator, type a period on the right side of # followed by the number of 0s representing each decimal place. Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim Number As Double

        Number = 20502.48

        MsgBox("Number: " & Format(Number, "#.00000"))
        Return 0
    End Function

End Module

The five 0s on the right side of the period indicate that you want to display 5 digits on the right side of the period. This would produce:

Format

You can enter as many # signs as you want; it wouldn't change anything. Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim Number As Double

        Number = 20502.48

        MsgBox("Number: " & Format(Number, "##########.00000"))
        Return 0
    End Function

End Module

This would produce the same result as above. To specify that you want to display the decimal separator, include its character between the # signs. Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim Number As Double

        Number = 20502.48

        MsgBox("Number: " & Format(Number, "###,#######.00000"))
        Return 0
    End Function

End Module

This would produce:

Format

You can include any other character or symbol you want in the string to be part of the result, but you should include such a character only at the beginning or the end of the string, otherwise the interpreter might give you an unexpected result.

Getting a Currency Number

Another regular type of number used in applications and finances is the currency. A currency value uses a special character specified in the Control Panel. In US English, this character would be the $ sign:

Currency

Of course, to display a symbol in the result, you can simply add it as part of the second argument to the Format() function. Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim Number As Double

        Number = 205.5

        MsgBox("Number: " & Format(Number, "$###,#######.00"))
        Return 0
    End Function

End Module

This would produce:

Fortunately, there are more professional options. Besides the Format() function, to support currency formatting of a number, the Visual Basic language provides the FormatCurrency() function. Its syntax is:

Function FormatCurrency(
   ByVal Expression As Object,
   Optional ByVal NumDigitsAfterDecimal As Integer = -1,
   Optional ByVal IncludeLeadingDigit As TriState = TriState.UseDefault,
   Optional ByVal UseParensForNegativeNumbers As TriState = TriState.UseDefault,
   Optional ByVal GroupDigits As TriState = TriState.UseDefault
) As String

Only the first argument is required. It is the value that needs to be formatted. Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim UnitPrice As Double

        UnitPrice = 1450.5

        MsgBox("Dress Price: " & FormatCurrency(UnitPrice))
        Return 0
    End Function

End Module

This would produce:

Format

Notice that, by default, the FormatCurrency() function is equipped to display the currency symbol (which in US English is the $ sign), the decimal separator (which is US English is the comma), and two decimal digits. If you want to control how many decimal digits are given to the result, pass a second argument as an integer. Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim UnitPrice As Double

        UnitPrice = 1450.5

        MsgBox("Dress Price: " & FormatCurrency(UnitPrice, 4))
        Return 0
    End Function

End Module

Instead of calling the FormatCurrency() function to format a number to currency, you can use the Format() function. If you do, pass it a second argument as "Currency", "c", or "C". Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim CarPrice As Double

        CarPrice = 42790

        MsgBox("Car Price: " & Format(CarPrice, "Currency"))
        Return 0
    End Function

End Module

This would produce:

Format

Formatting a Percentage Value

A percentage of a number represents its rate on a scale, usually of 100 (or more). The number is expressed using digits accompanied by the % sign. Besides the Format() function, to support percent values, the Visual Basic language provides a function named FormatPercent. Its syntax is:

Function FormatPercent(
   ByVal Expression As Object,
   Optional ByVal NumDigitsAfterDecimal As Integer = -1,
   Optional ByVal IncludeLeadingDigit As TriState = TriState.UseDefault,
   Optional ByVal UseParensForNegativeNumbers As TriState = TriState.UseDefault,
   Optional ByVal GroupDigits As TriState = TriState.UseDefault
) As String

Only the first argument is required and it is the number that needs to be formatted. When calling this function, pay attention to the number you provide as argument. If the number represents a percentage value as a fraction of 0 to 1, make sure you provide it as such. An example would be 0.25. In this case, the Visual Basic interpreter would multiply the value by 100 to give the result. Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim DiscountRate As Double

        DiscountRate = 0.25

        MsgBox("Discount Rate: " & FormatPercent(DiscountRate))
        Return 0
    End Function

End Module

This would produce:

Format

On the other hand, if you pass the value in the hundreds, the interpreter would still multiply it by 100. Although it is not impossible to get a percentage value in the hundreds or thousands, you should make sure that's the type of value you mean to get.

Besides the FormatPercent() function, to format a number to its percentage equivalent, you can call the Format() function and pass the second argument as "Percent", "p", or "P". Here is an example:

Public Module Exercise

    Public Function Main() As Integer
        Dim DiscountRate As Double

        DiscountRate = 0.25

        MsgBox("Discount Rate: " & Format(DiscountRate, "Percent"))
        Return 0
    End Function

End Module
 

Previous Copyright © 2008-2010 FunctionX Next