MIC 110

VB .Net Functions

[Methods] [How to Use MSDN Library]

[DateDiff] [End] [Format] [Format$] [FV] [InputBox] [Int] [isDate][isNumeric] [MsgBox] [Round] [Rnd] [Str] [Val]

[Reference Sources]

DateDiff

Specification

Returns a Variant (Long) specifying the number of time intervals between two specified dates.

Syntax

DateDiff(interval, date1, date2[, firstdayofweek[, firstweekofyear]])

The DateDiff function syntax has these named arguments:

Part Description
interval Required. String expression that is the interval of time you use to calculate the difference between date1 and date2.
date1 & date2 Required; Variant (Date). Two dates you want to use in the calculation.
firstdayofweek Optional. A constant that specifies the first day of the week. If not specified, Sunday is assumed.
firstweekofyear Optional. A constant that specifies the first week of the year. If not specified, the first week is assumed to be the week in which January 1 occurs.

Settings

The Interval argument can have one of the following settings.

Enumeration value
String
Unit of time difference
DateInterval.Day
d
Day
DateInterval.DayOfYear
y
Day
DateInterval.Hour
h
Hour
DateInterval.Minute
n
Minute
DateInterval.Month
m
Month
DateInterval.Quarter
q
Quarter
DateInterval.Second
s
Second
DateInterval.Weekday
w
Week
DateInterval.WeekOfYear
ww
Calendar week
DateInterval.Year
yyyy
Year

Remarks

You can use the DateDiff function to determine how many specified time intervals exist between two dates. For example, you might use DateDiff to calculate the number of days between two dates, or the number of weeks between today and the end of the year.

To calculate the number of days between date1 and date2, you can use either Day of year ("y") or Day ("d"). When interval is Weekday ("w"), DateDiff returns the number of weeks between the two dates. If date1 falls on a Monday, DateDiff counts the number of Mondays until date2. It counts date2 but not date1. If interval is Week ("ww"), however, the DateDiff function returns the number of calendar weeks between the two dates. It counts the number of Sundays between date1 and date2. DateDiff counts date2 if it falls on a Sunday; but it doesn't count date1, even if it does fall on a Sunday.

If date1 refers to a later point in time than date2, the DateDiff function returns a negative number.

The firstdayofweek argument affects calculations that use the "w" and "ww" interval symbols.

If date1 or date2 is a date literal, the specified year becomes a permanent part of that date. However, if date1 or date2 is enclosed in double quotation marks (" "), and you omit the year, the current year is inserted in your code each time the date1 or date2 expression is evaluated. This makes it possible to write code that can be used in different years.

When comparing December 31 to January 1 of the immediately succeeding year, DateDiff for Year ("yyyy") returns 1 even though only a day has elapsed.

Examples:

This example uses the DateDiff function to display the number of days between a given date and today.

Dim FirstDate, Msg As String   ' Declare variables.
Dim SecondDate As Date
FirstDate = InputBox("Enter a date")
SecondDate = CDate(FirstDate)
Msg = "Days from today: " & DateDiff(DateInterval.Day, Now, SecondDate)
MsgBox (Msg)

End: Terminates program. It's actually a statement rather than a function.

Format: Returns a string formatted according to instructions contained in a format String expression.

Parameters

Expression
Required. Any valid expression.
Style
Optional. A valid named or user-defined format String expression.

Settings

For information on how to create the Style argument, see the appropriate topic listed below:

To format Do this
Numbers Use predefined numeric formats or create user-defined numeric formats.
Dates and times Use predefined date/time formats or create user-defined date/time formats.
Date and time serial numbers Use date and time formats or numeric formats.
The following table identifies the predefined numeric format names. These may be used by name as the style argument for the Format function:

Format name Description
General Number, G, or g Displays number with no thousand separator.
Currency, C, or c Displays number with thousand separator, if appropriate; display two digits to the right of the decimal separator. Output is based on system locale settings.
Fixed, F, or f Displays at least one digit to the left and two digits to the right of the decimal separator.
Standard, N, or n Displays number with thousand separator, at least one digit to the left and two digits to the right of the decimal separator.
Percent, P, or p Displays number multiplied by 100 with a percent sign (%) appended to the right; always display two digits to the right of the decimal separator.
Scientific, E, or e Uses standard scientific notation.
D, or d Displays number as a string that contains the value of the number in Decimal (base 10) format. This option is supported for integral types (Byte, Short, Integer, Long) only.
X, or x Displays number as a string that contains the value of the number in Hexadecimal (base 16) format. This option is supported for integral types (Byte, Short, Integer, Long) only.
Yes/No Displays No if number is 0; otherwise, displays Yes.
True/False Displays False if number is 0; otherwise, displays True.
On/Off Displays Off if number is 0; otherwise, displays On.

If you try to format a number without specifying Style, the Format function provides functionality similar to the Str function, although it is internationally aware. However, positive numbers formatted as strings using the Format function don't include a leading space reserved for the sign of the value; those converted using the Str function retain the leading space.

Remarks

If you are formatting a nonlocalized numeric string, you should use a user-defined numeric format to ensure that you get the look you want.

The String.Format method also provides similar functionality.

Example

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.

Dim MyDateTime As Date = #1/27/2001 5:04:23 PM#
Dim MyStr As String
' Returns current system time in the system-defined long time format.
MyStr = Format(Now(), "Long Time")
' Returns current system date in the system-defined long date format.
MyStr = Format(Now(), "Long Date")
' Also returns current system date in the system-defined long date 
' format, using the single letter code for the format.
MyStr = Format(Now(), "D")
' Returns the value of MyDateTime in user-defined date/time formats.
MyStr = Format(MyDateTime, "h:m:s")   ' Returns "5:4:23".
MyStr = Format(MyDateTime, "hh:mm:ss tt")   ' Returns "05:04:23 PM".
MyStr = Format(MyDateTime, "dddd, MMM d yyyy")   ' Returns "Saturday,
   ' Jan 27 2001".
MyStr = Format(MyDateTime, "HH:mm:ss")   ' Returns "17:04:23"

MyStr = Format(23)   ' Returns "23".
' User-defined numeric formats.
MyStr = Format(5459.4, "##,##0.00")   ' Returns "5,459.40".
MyStr = Format(334.9, "###0.00")   ' Returns "334.90".
MyStr = Format(5, "0.00%")   ' Returns "500.00%".

MyStr = Format(23.99, "$##,##0.00")   ' Returns "$23.00".

Format$: Provides both predefined numeric formats and user-defined formats.

Examples:

Format$(12345.6789, "Currency")
$12345.67
Format$(0.6789, "Fixed")

0.67

(At least one digit to the left and two digits to the right of the period.)

Format$(0.1234, "Percent")
12.34%

FV (Future Value): (Information directly from MSDN.) Returns a Double data type specifying the future value of an annuity based on periodic, fixed payments and a fixed interest rate. Refer to the Help.

 

InputBox: Displays an input dialog window. The first argument, e.g., "Enter a Number" is the prompt and the second argument, e.g., "Input" determines what is displayed in the input dialog's title bar.

Basic format and example: intNum1 = InputBox ("Enter a Number", "Input")

Int: Returns a whole-number part of a number.

Exaples:

Int(5.5)

5

The whole number portion of 5.5 is 5.

Int(-5.5)

-6

The whole number portion of -5.5 is 6. Think about a ruler. The whole number of a number means the closest integer on the left.

Int(0.890)
0
Int(1.999)
1

num1 = 1.23

Int(num1)

1

Sample program form and project

Test your knowledge with a program (Exe, Form, Project).

IsDate: Returns a Boolean value indicating whether an expression can be converted to a date. Refer to Help.

 

isNumeric: Test if the value is a numeric or not. If the argument or expression in the function is a number, it returns True, otherwise, it returns False value.

Remarks

  • IsNumeric returns True if the entire Expression is recognized as a number; otherwise, it returns False.
  • IsNumeric returns True if the data type of Expression is Short, Integer, Long, Decimal, Single, or Short. It also returns True if Expression is a String that can be successfully converted to a Double. It returns False if Expression is of data type Date.

For example:

strValue = txtInput.Text

If IsNumeric(strValue) Then
      txtDisplay.Text = "a number."
Else
      txtDisplay.Text = "not a number."
End If

If txtInput.Text hold a numeric value, IsNumeric(txtInput.Text) will return True, otherwise, it will return False.


Depending the situation, you may compare the return value with another condition. For example:

If ( IsNumeric(txtInput.Text) = True ) Then
      txtDisplay.Text = "a number."
Else
      txtDisplay.Text = "not a number."
End If

It is essentially the same as the previous example, except it is longer. However, if you set the condition as:
( IsNumeric(txtInput.Text) = False ), then it turns out to be the opposite from the original one. Basically, the expression tests if the value from the IsNumeric function, which could be either True or False, is equal to False. So if txtInput.Text holds non-numeric value, the IsNumeric function will return False which is equal t o False. And it leads to a logic error..

Remark: IsNumeric returns False if expression is a date expression.

MsgBox: Prompts a dialog box that displays a message.

Examples:

MsgBox ("Thank You for the Help!")

Information from the MSDN: MsgBox Function

Parameters

Prompt
Required. String expression displayed as the message in the dialog box. The maximum length of Prompt is approximately 1024 characters, depending on the width of the characters used. If Prompt consists of more than one line, you can separate the lines using a carriage return character (Chr(13)), a linefeed character (Chr(10)), or a carriage return/linefeed character combination (Chr(13) & Chr(10)) between each line.
Buttons
Optional. Numeric expression that is the sum of values specifying the number and type of buttons to display, the icon style to use, the identity of the default button, and the modality of the message box. If you omit Buttons, the default value is zero.
Title
Optional. String expression displayed in the title bar of the dialog box. If you omit Title, the application name is placed in the title bar.

Settings

The MsgBoxStyle enumeration values are listed in the following table.

Enumeration Value Description
OKOnly
0
Displays OK button only.
OKCancel
1
Displays OK and Cancel buttons.
AbortRetryIgnore
2
Displays Abort, Retry, and Ignore buttons.
YesNoCancel
3
Displays Yes, No, and Cancel buttons.
YesNo
4
Displays Yes and No buttons.
RetryCancel
5
Displays Retry and Cancel buttons.
Critical
16
Displays Critical Message icon.
Question
32
Displays Warning Query icon.
Exclamation
48
Displays Warning Message icon.
Information
64
Displays Information Message icon.
DefaultButton1
0
First button is default.
DefaultButton2
256
Second button is default.
DefaultButton3
512
Third button is default.
ApplicationModal
0
Application is modal. The user must respond to the message box before continuing work in the current application.
SystemModal
4096
System is modal. All applications are suspended until the user responds to the message box.
MsgBoxSetForeground
65536
Specifies the message box window as the foreground window.
MsgBoxRight
524288
Text is right-aligned.
MsgBoxRtlReading
1048576
Specifies text should appear as right-to-left reading on Hebrew and Arabic systems.

The first group of values (05) describes the number and type of buttons displayed in the dialog box; the second group (16, 32, 48, 64) describes the icon style; the third group (0, 256, 512) determines which button is the default; the fourth group (0, 4096) determines the modality of the message box, and the fifth group specifies whether or not the message box window is the foreground window, along with the alignment and direction of the text. When adding numbers to create a final value for the Buttons argument, use only one number from each group.

Return Values

Constant
Value
OK
1
Cancel
2
Abort
3
Retry
4
Ignore
5
Yes
6
No
7

Exceptions/Errors

Exception type
Error number Condition
ArgumentException
5
Prompt is not a String expression, or Title is invalid.
InvalidOperationException
5
Process is not running in User Interactive mode.
InvalidEnumArgumentException
5
One or more parameters not a member of MsgBoxResult or MsgBoxStyle enumerations.

Remarks

If the dialog box displays a Cancel button, pressing the ESC key has the same effect as clicking Cancel. If the dialog box contains a Help button, context-sensitive Help is provided for the dialog box. However, no value is returned until one of the other buttons is clicked.

Note   To specify more than the first argument, you must use the MsgBox function in an expression. If you omit any positional arguments, you must retain the corresponding comma delimiter.

Example

This example uses the MsgBox function to display a critical-error message in a dialog box with Yes and No buttons. The No button is specified as the default response. This is done by combining the MsgBox constant values into one numeric expression. In this case, adding 4 (the Yes/No button combination) and 16 (the Critical Message window) and 256 (the second button as default button) gives a total of 276. The value returned by the MsgBox function depends on the button chosen by the user: Yes returns a value of 6; No returns a value of 7.

Dim msg As String
Dim title As String
Dim style As MsgBoxStyle
Dim response As MsgBoxResult
msg = "Do you want to continue?"   ' Define message.
style = MsgBoxStyle.DefaultButton2 Or _
   MsgBoxStyle.Critical Or MsgBoxStyle.YesNo
title = "MsgBox Demonstration"   ' Define title.
' Display message.
response = MsgBox(msg, style, title)  ' or MsgBox(msg, MsgBoxStyle.YesNo, title)
If response = MsgBoxResult.Yes Then   ' User chose Yes.
   ' Perform some action.
Else
   ' Perform some other action.
End If

Round: Rounds a number to a certain decimal places. If the decimal specification is omitted, an integer is returned.

Examples:

Round (5.999)
6
Round (5.1234, 3)
5.123

num1 = 1.12345

Round (num1, 2)

1.12

num1 = 1.125

Round (num1, 2)

1.26

It rounds up the 3rd decimal place to the 2nd decimal place.

 

Rnd: Generates a random number between 0 and 1, including 0 but excluding 1. In a mathematical expression, it is written as 0 <= rnd < 1.

Example:

dieFace = 1 + Int (6 * Rnd ( ) )

It can be 1, 2, 3, 4, 5, or 6.

The Rnd ( ) generates a number between 0 and 1.

Then it is multiplied by 6. Now it is in between 0 and 5.9999.

Once the Int function returns an integer value, it is in between 0 and 5.

Then add 1 to it, so it is in between 1 and 6.

N = Int ( Rnd( ) * 10 )
0 <= N <= 9
N = 1 + Int ( Rnd( ) * 10 )
1 <= N <= 10
N = 1 + Int ( Rnd( ) * 100 )
1 <= N <= 100
N = 50 + Int ( Rnd( ) * 49 )
50 <= N <= 99

A Basic Format:

N = LowestNumber + Int ( Rnd( ) * ( HighestNumber - LowestNumber + 1 ))

For example, 50 <= N <= 99:

N = 50 + Int ( Rnd( ) * ( 99 - 50 + 1))

    = 50 + Int ( Rnd( ) * 50 )

The Rnd function does not generate a random number in a true sense. It picks up a number from the "junk yard" of the RAM. To get truer random number, you can use the Randomize statement before using the Rnd function.

Str: Converts numbers to strings. The returning string comes with a leading blank space. For negative numbers, a minus sign appears rather than a leading space. Also, refer to Format and Format$ functions for formating the string.

Example:

Str(1.123)

1.123

(in string)

intNum1 = 789

Str(intNum1)

789

(in string)

intNum1 = -789

Str(intNum1)

-789

(in string)

Val: Converts strings to numbers, so that the values can be used in calculations. In Visual Basic, it is not required so convert string values into numeric values for calculations. However, it is a good practice since many other programming languages require the conversion.

Example:

strNum1 = "789"

Val(strNum1)

789

(in numeric)

strNum1 = "-789"

Val(intNum1)

-789

(in numeric)

 
 
 
 

How to Use MSDN Library

MSDN Library is a great resource for learning functions. If you have the learning version of Visual Basic, you may not have this component, so you may have to use the college computer lab to use it. As you can imagine, the professional or developer versions would have a lot more functions.

To open the MSDN Library, click on Help then Contents. On the left-window, open the folder as shown below.

 

Reference Sources