A function is similar to a procedure but the main purpose of the function is to accept an input from the
user and return a value which is passed on to the main program to finish the execution. There are two
types of functions, the built-in functions and the user-defined functions. The syntax of a function is:
FunctionName (arguments)
1. The MsgBox() Function
The MsgBox() function displays a message in a pop-up message box (no surprises there!). The user is
expected to respond by clicking on a button in order to be able to continue. The format of the statement
used to invoke a message box is as follows:
returnVal = MsgBox (prompt, styleVal, title)
The prompt parameter is a string value (either a string literal or a string variable) that supplies the
message to be displayed. The styleVal parameter is either an integer style value from 0 to 5, or a named
constant that can be used instead of the corresponding integer value, that determines which command
buttons will appear on the message box. The title parameter is another string literal or string variable that
supplies the title for the message box. The styles available are listed in the table below.
Message Box Styles
Style value Named constant Buttons displayed
0 vbOkOnly OK
1 vbOkCancel OK, Cancel
2 vbAbortRetryIgnore Abort, Retry, Ignore
3 vbYesNoCancel Yes, No, Cancel
4 vbYesNo Yes, No
5 vbRetryCancel Retry, Cancel
The returnVal value returned by the MsgBox() function is an integer value that indicates which button
the user has clicked in response to the message box being displayed. The possible return values together
with the named constants that may be used in their stead, are listed in the table below.
Message Box Return Values
Return value Named constant Button clicked
1 vbOk OK
2 vbCancel Cancel
3 vbAbort Abort
4 vbRetry Retry
5 vbIgnore Ignore
6 vbYes Yes
7 vbNo No
The message box can be further embellished by the inclusion of an icon that will appear beside the
message. There are four icons available. The icon is included either by incrementing the style value by a
fixed constant value, or by the inclusion of a second named constant.
Message Box Icons
Value Named constant Icon
16 vbCritical
32 vbQuestion
48 vbExclamation
64 vbInformation
The following statements would produce exactly the same message box, and are essentially equivalent to
one another:
MsgBox ("This message is for info!", 64, "Info")
MsgBox ("This message is for info!", vbOKOnly + vbInformation, "Info")
Example
You draw three command buttons and a label as shown in Figure.
The procedure for the test button:
Private Sub Test_Click()
Dim testmsg As Integer
testmsg = MsgBox("Click to test", 1, "Test message")
If testmsg = 1 Then
Display.Caption = "Testing Successful"
Else
Display.Caption = "Testing fail"
End If
End Sub
When the user click on the test button, the image like the one shown in Figure below will appear. As the
user click on the OK button, the message "Testing successful" will be displayed and when he/she clicks
on the Cancel button, the message "Testing fail" will be displayed.
Example
You draw the same Interface as in example 10.1 but modify the codes as follows:
Private Sub test2_Click()
Dim testMsg2 As
Integer testMsg2 = MsgBox("Click to Test", vbYesNoCancel + vbExclamation, "TestMessage")
If testMsg2 = 6 Then
display2.Caption ="Testing successful"
ElseIf testMsg2 = 7 Then
display2.Caption = "Are you sure?"
Else display2.Caption ="Testing fail"
End If
End Sub
2. The InputBox() Function
The InputBox() function displays a pop-up input box into which the user can type a message. The user is
expected to enter their message, then click on a button ("Cancel" or "OK") in order to continue. The
format of the statement used to invoke an input box is as follows:
returnString = InputBox (prompt, title, defaultText, xpos, ypos)
The returnString returned by the InputBox() function is the text entered by the user.
The prompt parameter is a text string (either a string literal or a string variable) that prompts the user to
enter some information. The title parameter is another string literal or string variable that supplies the title
for the input box. The defaultText parameter can be used to enter default content in the input box
(although it would probably be left blank in most cases). The xpos and ypos parameters specify
the x and y coordinates for the input box on screen.
Example
The procedure for the OK button
Private Sub OK_Click()
Dim userMsg As String
userMsg = InputBox("What is your message?", "Message Entry Form", "Enter your messge here", 500,
700)
If userMsg <>"" Then
message.Caption = userMsg
Else
message.Caption = "No Message"
End If
End Sub
When the user clicks the OK button, the input box as shown in Figure below will appear. Upon entering
the message and click OK, the message will be displayed on the caption, if the Cancel button is clicked,
"No message" will be displayed.
3. String Functions
Description
Function
Returns n characters from the text string referred to by str,
Mid (str, pos, n)
starting at character position pos.
Microsoft.VisualBasic.left Returns the n left-most characters from the text string referred
(str, n) to by str.
Microsoft.VisualBasic.right Returns the n right-most characters from the text string
(str, n) referred to by str.
Removes the white space (if any) at either end of the text string
Trim (str)
referred to by str, and returns the result.
Removes the white space (if any) at the left-hand end of the
LTrim (str)
text string referred to by str, and returns the result.
Description
Function
Removes the white space (if any) at the right-hand end of the
RTrim (str)
text string referred to by str, and returns the result.
Looks for an occurrence of the substring str2 within the
string str1, starting at character position n. If successful, the
InStr (n, str1, str2)
function returns the character position at which the substring is
found (or zero if the substring cannot be found).
Converts the string referred to by str to all upper-case
UCase (str)
characters, and returns the result.
Converts the string referred to by str to all lower-case
LCase (str)
characters, and returns the result.
Returns the ASCII character corresponding to the 8-bit
Chr (charCode) character code charCode (note – some characters are non-
printing characters, and will not be visible on screen).
Returns the 8-bit ASCII character code corresponding
Asc (character)
to character.
UCase
This function to return an uppercase version of a string.
Dim lowerCase As String = "Hello World 1234"
Dim upperCase As String = UCase(lowerCase)
LTrim
This example uses the LTrim function to strip leading spaces and the RTrim function to strip trailing
spaces from a string variable. It uses the Trim function to strip both types of spaces.
' Initializes string.
Dim testString As String = " <-Trim-> "
Dim trimString As String
' Returns "<-Trim-> ".
trimString = LTrim(testString)
' Returns " <-Trim->".
trimString = RTrim(testString)
' Returns "<-Trim->".
trimString = LTrim(RTrim(testString))
' Using the Trim function alone achieves the same result.
' Returns "<-Trim->".
trimString = Trim(testString)
Mid
This example uses the Mid function to return a specified number of characters from a string.
' Creates text string.
Dim testString As String = "Mid Function Demo"
' Returns "Mid".
Dim firstWord As String = Mid(testString, 1, 3)
' Returns "Demo".
Dim lastWord As String = Mid(testString, 14, 4)
' Returns "Function Demo".
Dim midWords As String = Mid(testString, 5)
Len
This example uses Len to return the number of characters in a string.
' Initializes variable.
Dim testString As String = "Hello World"
' Returns 11.
Dim testLen As Integer = Len(testString)
InStr
This example uses the InStr function to return the position of the first occurrence of one string within
another.
' String to search in.
Dim searchString As String = "XXpXXpXXPXXP"
' Search for "P".
Dim searchChar As String = "P"
Dim testPos As Integer
' A textual comparison starting at position 4. Returns 6.
testPos = InStr(4, searchString, searchChar, CompareMethod.Text)
' A binary comparison starting at position 1. Returns 9.
testPos = InStr(1, SearchString, SearchChar, CompareMethod.Binary)
' If Option Compare is not set, or set to Binary, return 9.
' If Option Compare is set to Text, returns 3.
testPos = InStr(searchString, searchChar)
' Returns 0.
testPos = InStr(1, searchString, "W")
4. Maths Functions
Description
Function
Math.Sqrt (n) Returns the square root of a number, n.
Math.Abs (n) Returns the absolute value of a number, n.
Returns the exponential value of a number, n – i.e. e n.
Math.Exp (n)
Note: e = 2.71828182
Fix (n) Returns the integer part of a floating point number, n.
Returns the integer part of a floating point number, n, for
Int (n) positive numbers, or the next smallest integer value for
negative numbers.
Math.Log (n) Returns the natural logarithm of a number, n.
Rnd () Returns a randomly generated value between 0 and 1.
Round (n,m) Rounds a number, n, up (or down) to m decimal places.
To use these functions without qualification, import the System.Math namespace into your project by
adding the following code to the top of your source file:
Imports System.Math
Example
This example uses the Abs method of the Math class to compute the absolute value of a number.
' Returns 50.3.
Dim MyNumber1 As Double = Math.Abs(50.3)
' Returns 50.3.
Dim MyNumber2 As Double = Math.Abs(-50.3)
Example
This example uses the Atan method of the Math class to calculate the value of pi.
Public Function GetPi() As Double
' Calculate the value of pi.
Return 4.0 * Math.Atan(1.0)
End Function
Example
This example uses the Cos method of the Math class to return the cosine of an angle.
Public Function Sec(ByVal angle As Double) As Double
' Calculate the secant of angle, in radians.
Return 1.0 / Math.Cos(angle)
End Function
Example
This example uses the Exp method of the Math class to return e raised to a power.
Public Function Sinh(ByVal angle As Double) As Double
' Calculate hyperbolic sine of an angle, in radians.
Return (Math.Exp(angle) - Math.Exp(-angle)) / 2.0
End Function
Example
This example uses the Log method of the Math class to return the natural logarithm of a number.
Public Function Asinh(ByVal value As Double) As Double
' Calculate inverse hyperbolic sine, in radians.
Return Math.Log(value + Math.Sqrt(value * value + 1.0))
End Function
Example
This example uses the Round method of the Math class to round a number to the nearest integer.
' Returns 3.
Dim MyVar2 As Double = Math.Round(2.8)
Example
This example uses the Sign method of the Math class to determine the sign of a number.
' Returns 1.
Dim MySign1 As Integer = Math.Sign(12)
' Returns -1.
Dim MySign2 As Integer = Math.Sign(-2.4)
' Returns 0.
Dim MySign3 As Integer = Math.Sign(0)
Example
This example uses the Sin method of the Math class to return the sine of an angle.
Public Function Csc(ByVal angle As Double) As Double
' Calculate cosecant of an angle, in radians.
Return 1.0 / Math.Sin(angle)
End Function
Example
This example uses the Sqrt method of the Math class to calculate the square root of a number.
' Returns 2.
Dim MySqr1 As Double = Math.Sqrt(4)
' Returns 4.79583152331272.
Dim MySqr2 As Double = Math.Sqrt(23)
' Returns 0.
Dim MySqr3 As Double = Math.Sqrt(0)
' Returns NaN (not a number).
Dim MySqr4 As Double = Math.Sqrt(-4)
Example
This example uses the Tan method of the Math class to return the tangent of an angle.
Public Function Ctan(ByVal angle As Double) As Double
' Calculate cotangent of an angle, in radians.
Return 1.0 / Math.Tan(angle)
End Function
5. Formatting Numbers
The Format() function allows you to specify precisely how numeric values are displayed. The function is
used as follows:
Format (n, "styleArg")
The first argument (n) is the number to be formatted. The value selected for the second argument
("styleArg") will determine how the number is displayed. The possible values are described in the table
below (note that a user-defined value for "styleArg" can also be used).
Format () Number Style Arguments
Style Argument Description
"General Number" Displays n with no separator between thousands.
Displays n with no separator between thousands,
"Fixed"
and rounds it up (or down) to two decimal places.
Displays n with separators between thousands, and
"Standard"
rounds it up (or down) to two decimal places.
Displays n prefixed by a "£" sign (if the locale is set
"Currency" to United Kingdom) , with separators between thousands,
and rounds it up (or down) to two decimal places.
Displays n as a percentage, rounds it up (or down) to two
"Percent"
decimal places, and adds a "%" symbol.
6. Formatting the Date and Time
The Format() function can also be used to specify how date and time values are displayed. The function
is used as follows:
Format (Date, "styleArg")
The first argument (Date) is the date to be formatted (note that if you are using the current date,
the Now function can be used as the argument. The value selected for the second argument ("styleArg")
will determine how the date value is displayed. The possible values are described in the table below (note
that a user-defined value for "styleArg" can also be used).
Format () Date Style Arguments
Style Argument Description
"General Date" Displays the date and time in the format: dd/mm/yyyy hh:mm:ss
Format () Date Style Arguments
Style Argument Description
"Long Date" Displays the date in the format: 06 October 2009
"Short Date" Displays the date in the format: dd/mm/yyyy
"Long Time" Displays the time in the format: h:mm:ss
"Short Time" Displays the time in the format: hh:mm
Example: Format
This example shows various uses of the Format function to format values using both String formats and
user-defined formats. For the date separator (/), time separator (:), and the AM/PM indicators (t and tt),
the actual formatted output displayed by your system depends on the locale settings the code is using.
When times and dates are displayed in the development environment, the short time format and short date
format of the code locale are used.
Note
For locales that use a 24-hour clock, the AM/PM indicators (t and tt) display nothing.
Dim testDateTime As Date = #1/27/2001 5:04:23 PM#
Dim testStr As String
' Returns current system time in the system-defined long time format.
testStr = Format(Now(), "Long Time")
' Returns current system date in the system-defined long date format.
testStr = Format(Now(), "Long Date")
' Also returns current system date in the system-defined long date
' format, using the single letter code for the format.
testStr = Format(Now(), "D")
' Returns the value of testDateTime in user-defined date/time formats.
' Returns "5:4:23".
testStr = Format(testDateTime, "h:m:s")
' Returns "05:04:23 PM".
testStr = Format(testDateTime, "hh:mm:ss tt")
' Returns "Saturday, Jan 27 2001".
testStr = Format(testDateTime, "dddd, MMM d yyyy")
' Returns "17:04:23".
testStr = Format(testDateTime, "HH:mm:ss")
' Returns "23".
testStr = Format(23)
' User-defined numeric formats.
' Returns "5,459.40".
testStr = Format(5459.4, "##,##0.00")
' Returns "334.90".
testStr = Format(334.9, "###0.00")
' Returns "500.00%".
testStr = Format(5, "0.00%")