For Each...Next Statement VB.NET

Syntax

For Each element In group [statements] [Exit For] [statements] Next [element] element Use: Required Data Type: Object or any user-defined object type

An object variable to which the current element from the group is assigned

group

Use: Required An object collection or array

statements

Use: Optional A line or lines of program code to execute within the loop

Description
Loops through the items of a collection or the elements of an array

Rules at a Glance

  • The For Each...Next code block is executed only if group contains at least one element. If group is an empty collection or an array that has not yet been dimensioned, an error (runtime errors 92, "For loop not initialized," and 424, "Object required," respectively, or a NullReferenceException exception) results.
  • All statements are executed for each element in group in turn until either there are no more elements in group or the loop is exited prematurely using the Exit For statement. Program execution then continues with the line of code following Next.
  • For Each...Next loops can be nested, but each element must be unique. For example:

uses a nested For Each...Next loop, but two different variables, myObj and subObject, represent element.

  • Any number of Exit For statements can be placed within the For Each...Next loop to allow for premature, conditional exit of the loop. Once the loop is exited, execution of the program continues with the line immediately following the Next statement. For example, the following loop terminates once the program finds a name in the myObj collection that has fewer than ten characters:

Programming Tips and Gotchas

  • Because the elements of an array are assigned to element by value, element is a "local" copy of the array element and not a reference to the array element itself. This means that you cannot make changes to the array elements, as the following example demonstrates:

which shows that the original array has not been changed.

VB .NET/VB 6 Differences
In VB 6, element had to be a variable of type Variant. VB .NET removes this restriction; elementcan be a strongly typed data type, as well as a variable of type Object, VB .NET's "universal" data type.

Format Function

Class

Microsoft.VisualBasic.Strings

Syntax

Format(expression[, style[, dayofweek[, _ weekofyear]]]) expression Use: Required Data Type: String/Numeric

Any valid string or numeric expression

style

Use: Optional Data Type: String

A valid named or user-defined format expression

dayofweek

Use: Optiona Data Type: FirstDayOfWeek enumeration

A constant that specifies the first day of the week

weekofyear

Use: Optional Data Type: FirstWeekOfYear enumeration

A constant that specifies the first week of the year

First Day of Week Constants

TABLE

First Day of Week Constants

First Week of Year Constants

TABLE

First Week of Year Constants

Return Value
A string containing the formatted expression

Description
Allows you to use either predefined or user-defined formats to output string, numeric, and date/time
data.

Rules at a Glance

  • style can be either a predefined or user-defined format.
  • User-defined formats for numeric values are created with up to four sections, delimited by semicolons. Each section is used for a different type of numeric value. The four possible sections are shown in the following table:

TABLE

Rules at a Glance

It is not necessary to include all four sections in the style clause. However, the number of sections present determines what types of numeric values each section defines, as the following table shows:

TABLE

TABLE

  • If you leave a section blank, it will use the same format as that defined for positive values. For example, the format string: "#.00;;#,##" means that negative values will appear in the same format as positive values.
  • Only one section is allowed where one of the named formats is used.
  • User-defined formats for string values can have two sections. The first is for all values; the second applies only to Null values or zero-length strings.
  • The predefined date and time formats are:

General Date
Example: Format("01/06/98","General Date")
Returns: 1/6/98

Long Date
Example: Format("01/06/98","Long Date")
Returns: Tuesday, January 06, 1998

Medium Date
Example: Format("01/06/98","Medium Date")
Returns: 06-Jan-98

Short Date
Example: Format("01/06/98","Short Date")
Returns: 1/6/98

Long Time
Example: Format("17:08:06","Long Time")
Returns: 5:08:06 PM

Medium Time
Example: Format("17:08:06","Medium Time")
Returns: 05:08 PM

Short Time
Example: Format("17:08:06","Short Time")
Returns: 17:08

  • The predefined numeric formats are:

General Number
Example: Format(562486.2356, "General Number")
Returns: 562486.2356

Currency
Example: Format(562486.2356, "Currency")
Returns: $562,486.24

Fixed
Example: Format(0.2, "Fixed")
Returns: 0.20

Standard
Example: Format(562486.2356, "Standard")
Returns: 562,486.24

Percent
Example: Format(.7521, "Percent")
Returns: 75.21%

Scientific
Example: Format(562486.2356, "Scientific")
Returns: 5.62E+05

Yes/No
Example #1: Format(0,"Yes/No")
Returns: No
Example #2: Format(23,"Yes/No")
Returns: Yes

True/False
Example #1: Format(0,"True/False")
Returns: False
Example #2: Format(23,"True/False")
Returns: True

On/Off
Example #1: Format(0,"On/Off")
Returns: Off
Example #2: Format(23,"On/Off")
Returns: On

Characters used to create user-defined date and time formats are:
c
Element: Date
Display as: A date and/or time based on the short-date and short-time international settings of
the current Windows system
Example: Format("01/06/98 17:08:06", "c")
Returns: 1/6/98 5:08:06 PM

dddddd
Element: Date
Display as: A complete date based on the long-date international setting of the current
Windows system
Example: Format("01/06/98", "dddddd")
Returns: Tuesday, January 06, 1998
(/ )
Element: Date separator
Display as: A date delimited with the specified character
Example: Format("01/06/98", "mm-dd-yyyy")
Returns: 01-06-1998

d
Element: Day
Display as: A number (1-31) without a leading zero
Example: Format("01/06/98", "d")
Returns: 6

dd
Element: Day
Display as: A number (01-31) with a leading zero
Example: Format("01/06/98", "dd")
Returns: 06

ddd
Element: Day
Display as: An abbreviation (Sun-Sat)
Example: Format("01/06/98", "ddd")
Returns: Tue

Dddd
Element: Day
Display as: A full name (Sunday-Saturday)
Example: Format("01/06/98", "dddd")
Returns: Tuesday

ddddd
Element: Date
Display as: A date based on the short date section in the computer's Windows international settings
Example: Format("01/06/98", "ddddd")
Returns: 1/6/98

h
Element: Hour
Display as: A number (0-23) without leading zeros
Example: Format("05:08:06", "h")
Returns: 5

hh
Element: Hour
Display as: A number (00-23) with leading zeros
Example: Format("05:08:06", "hh")
Returns: 05

n
Element: Minute
Display as: A number (0-59) without leading zeros
Example: Format("05:08:06", "n")
Returns: 8

nn
Element: Minute
Display as: A number (00-59) with leading zeros
Example: Format("05:08:06", "nn")
Returns: 08

m
Element: Month
Display as: A number (1-12) without a leading zero
Example: Format("01/06/98", "m")
Returns: 1

mm
Element: Month
Display as: A number (01-12) with a leading zero
Example: Format("01/06/98", "mm")
Returns: 01

mmm
Element: Month
Display as: An abbreviation (Jan-Dec)
Example: Format("01/06/98", "mmm")
Returns: Jan

mmmm
Element: Month
Display as: A full month name (January-December)
Example: Format("01/06/98", "mmmm")
Returns: January

q
Element: Quarter
Display as: A number (1-4)
Example: Format("01/06/98", "q")
Returns: 1

s
Element: Second
Display as: A number (0-59) without leading zeros
Example: Format("05:08:06", "s")
Returns: 6

ss
Element: Second
Display as: A number (00-59) with leading zeros
Example: Format("05:08:06", "ss")
Returns: 06

ttttt
Element: Time
Display as: A time based on the 12-hour clock, using the time separator and leading zeros specified in Windows locale settings
Example: Format("05:08:06", "ttttt")
Returns: 5:08:06 AM

AM/PM
Element: Time
Display as: A 12-hour
clock format using uppercase AM and PM
Example: Format("17:08:06", "hh:mm:ss AM/PM")
Returns: 05:08:06 PM

am/pm
Element: Time
Display as: A 12-hour clock format using lowercase am and pm
Example: Format("17:08:06", "hh:mm:ss am/pm")
Returns: 05:08:06 pm

A/P
Element: Time
Display as: A 12-hour clock format using an uppercase "A" for AM and "P" for PM
Example: Format("17:08:06", "hh:mm:ss A/P")
Returns: 05:08:06 P

a/p
Element: Time
Display as: A 12-hour clock format using a lowercase "a" for AM and "p" for PM
Example: Format("17:08:06", "hh:mm:ss a/p")
Returns: 05:08:06 p

(: )
Element: Time separator
Display as: A time format using a nonstandard character
Example: Format("17:08:06", "hh::mm::ss")
Returns: 17::08::06

ww
Element: Week
Display as: A number (1 - 54)
Example: Format("01/06/98", "ww")
Returns: 2

w
Element: Weekday
Display as: A number (1 for Sunday through 7 for Saturday)
Example: Format("01/06/98", "w")
Returns: 3

y
Element: Day of Year
Display as: A number (1 - 366)
Example: Format("01/06/98", "y")
Returns: 6

yy
Element: Year
Display as: A 2-digit number (00 - 99)
Example: Format("01/06/98", "yy")
Returns: 98

yyyy
Element: Year
Display as: A 4-digit number (100 - 9999)
Example: Format("01/06/98", "yyyy")
Returns: 1998

  • Characters used to create user-defined number formats are as follows:

(0 )
Description: Digit placeholder. If expression contains a digit in the appropriate position, the digit is displayed; otherwise, a 0 will be displayed. The format definition dictates the number of digits after the decimal point, forcing the number held within an expression to be rounded to the given number of decimal places. It does not, however, affect the number of digits shown to the left of the decimal point.
Example #1: Format(23.675, "00.0000") returns 23.6750
Example #2: Format(23.675, "00.00") returns23.68
Example #3: Format(2658, "00000") returns 02658
Example #4: Format(2658, "00.00") returns 2658.00

(# )
Description: Digit placeholder. If expression contains a digit in the appropriate position, the digit is displayed; otherwise, nothing will be displayed.
Example #1: Format(23.675, "##.##") returns 23.68
Example #2: Format(23.675, "##.####") returns 23.675
Example #3: Format(12345.25, "#,###.##") returns 12,345.25

(. )
Description: Decimal placeholder. The actual character displayed as a decimal placeholder depends on the international settings of the local Windows system.

(% )
Description: Percentage placeholder. Displays expression as a percentage by first multiplying the value of expression by 100.
Example: Format(0.25, "##.00%") returns 25.00%

(, )
Description: Thousands separator. The actual character displayed as a thousands separator depends on the international settings of the local Windows system. You only need to show one thousands separator in your definition.
Example: Format(1000000, "#,###") returns 1,000,000

(E- E+ e- e+ )
Description: Scientific format. If the format expression contains at least one digit placeholder (0 or #) to the right of E-, E+, e-, or e+, the number is displayed in scientific format, and the letter E or e that was used in the format expression is inserted between the number and its exponent. The number of digit placeholders to the right determines the number of digits displayed in the exponent. Use E- or e- to place a minus sign next to negative exponents. Use E+ or e+ to place a minus sign next to negative exponents and a plus sign next to positive exponents.

- + $ ( )

Description: Displays a literal character.
Example: Format(2345.25, "$#,###.##") returns $2,345.25

( )
Description: The character following the backslash will be displayed as a literal character. Usethe backslash to display a special formatting character as a literal.
Example: Format(0.25, "##.00\%") returns .25%
Note: Note the difference between the result of this example and the result of the % formattingcharacter.

Programming Tips and Gotchas

  • A little known and very important use of the Format function is to prevent an "Invalid Use ofNull" error from occurring when assigning values from a recordset to a variable within yourprogram. For example, if a field within either a DAO or RDO recordset created from either an
    Access or SQL Server database contains a Null value, you could trap this and change its value to as follows:

recordset field can do away with this long and tedious coding, as the following line of code illustrates:

sMyString = Format(rsMyRecordSet!myValue)

  • If you are passing a date to SQL Server, what date format should you use? By default, SQL Server expects an American date format, mmddyy, but it is possible for the database to have been altered to accept other date formats, or you could be passing data to a stored procedure that begins with a date-time conversion statement (SET DATEFORMAT dateformat). The only sure way of passing a date into SQL Server is by using the ANSI standard date format 'yyyymmdd' (including the single quotation marks).
  • When passing a date to a Jet (Access) database, you should surround the date with hash characters (#); for example, #12/31/1999#.
  • Formatting numbers using Format without a format definition is also preferable to simply using the Str function. Unlike Str, the Format function removes the leading space normally reserved for the sign from positive numbers.
  • You can also use the Format function to scale numbers by 1000. This is achieved by placing a thousands separator to the immediate left of the decimal point for each 1000 you wish the number to be scaled by. Thus:

VB .NET/VB 6 Differences
The VB 6 version of the Format function defined five special symbols (@, &, <, >, and !) for creatinguser-defined string formats. In beta 2 of VB .NET, these symbols are treated as literal characters.

FormatCurrency, FormatNumber, FormatPercent

Functions

Class

Microsoft. VisualBasic. Strings

Syntax

Use: Required Data Type: Object

The number or numeric expression to be formatted.

NumDigitsAfterDecimal

Use: Optional Data Type: Long

The number of digits the formatted string should contain after the decimal point.

IncludeLeadingDigit

Use: Optional Data Type: TriState constant

Indicates whether the formatted string is to have a 0 before floating point numbers between 1 and -1.

UseParensForNegativeNumbers

Use: Optional Data Type: TriState constant

Specifies whether parentheses should be placed around negative numbers.

GroupDigits

Use: Optional Data Type: TriState constant

Determines whether digits in the returned string should be grouped using the delimiterspecified in the computer's regional settings. For example, on English language systems, thevalue 1000000 is returned as 1,000,000 if GroupDigits is True.

Return Value

String

Description
Functions used to format currency, numbers, and percentages.
The three functions are almost identical. They all take identical arguments. The only difference is thatFormatCurrency returns a formatted number beginning with the currency symbol specified in the computer's regional settingsFormatNumber returns just the formatted number, and FormatPercent returns the formatted number followed by a percentage sign (%).

Rules at a Glance

  • If NumDigitsAfterDecimal is not specified, its default value is -1, which means that the value in the computer's regional settings is used.
  • The TriState constant values are True, False, and UseDefault.
  • When optional arguments are omitted, their values are defined by the computer's regional settings.
  • In the FormatCurrency function, the position of the currency symbol in relation to the currency value is defined by the computer's regional settings.

Programming Tips and Gotchas
These three functions first appeared in VBScript Version 2 as "light" alternatives to the Format function,which had originally been left out of VBScript due to its size. They are quick and easy to use and makeyour code more self-documenting; you can instantly see what format is being applied to a number
without having to decipher the format string.

FormatDateTime Function

Class

Microsoft.VisualBasic.Strings
Syntax
FormatDateTime(expression[,dateformat])

expression

Use: Required Data Type: Date

Date variable or literal date

dateformat

Use: Optional Data Type: DateFormat enum

Defines the format of the date to return

Return Value
String representing the formatted date or time

Description
Formats a date or time expression based on the computer's regional settings

Rules at a Glance

  • The Dateformat enum is:

DateFormat.GeneralDate
Value: 0
Displays a date and/or time. If there is a date part, displays it as a short date. If there is a time
part, displays it as a long time. If present, both parts are displayed.

DateFormat.LongDate
Value: 1
Uses the long-date format specified in the client computer's regional settings.

DateFormat.ShortDate
Value: 2
Uses the short-date format specified in the client computer's regional settings.

DateFormat.LongTime
Value: 3
Uses the time format specified in the computer's regional settings.

DateFormat.ShortTime
Value: 4
Uses a 24-hour format (hh:mm).

  • The default date format is GeneralDate.

Programming Tips and Gotchas

  • Remember that date and time formats obtained from the client computer are based upon the client computer's regional settings. It is not uncommon for a single application to be used internationally, so date formats can vary widely. Not only that, but you can never be sure that a user has not modified the regional settings on her computer. In short, never take a date coming in from a client machine for granted; ideally, you should always verify that it is in the format you need prior to using it.
  • There is no appreciable difference in either coding or performance between these two statements:

sDate = FormatDateTime(dDate, LongDate)
sDate = Format(dDate, "Long Date")

FreeFile Function

Class

Microsoft.VisualBasic.FileSystem

Syntax
FreeFile( )

Return Value
An integer representing the next available file number

Description
Returns the next available file number for use in a FileOpen function

Programming Tips and Gotchas

  • It is good programming practice to always use FreeFile to obtain a file number to use in the FileOpen procedure.
  • You should call FreeFile and store the returned file number to a variable rather than passing the FreeFile function directly as the filenumber argument of the FileOpen procedure. In this way, you save the file handle for a subsequent call to the FileClose procedure. After using the FreeFile function to retrieve a file handle, you should immediately call the FileOpen procedure, particularly if your file access code resides in a multithreaded application or
  • component. Failure to do so may cause the same handle to be assigned to two different variables, so that one of the calls to FileOpen fails.

Friend Keyword

Description
The Friend keyword is used to declare classes, module-level variables (but not local variables), constants, enumerations, properties, methods, functions, and subroutines.
When the Friend keyword is used, the item being declared has direct access scope inside of the class module in which the item is declared, as well as in all derived classes in the same project. However, if the item is declared using Protected Friend, then the scope is all derived classes, including those that are in other projects.
Class Statement
Const Statement
Enum Statement
Function Statement
Property Statement
Sub Statement

Function Statement

Syntax

Use: Optional Type: Keyword

One of the following keywords:

Overloads
Indicates that more than one declaration of this function exists (with different argument signatures).

Overrides
For derived classes, indicates that the function overrides the function by the same name (and argument signature) in the base class.

Overridable
Indicates that the function can be overridden in a derived class.

NotOverridable
Indicates that the function cannot be overridden in a derived class.

MustOverride
Indicates that the function must be overridden in a derived class.

Shadows
In a derived class definition, indicates that calls to derived class members that are madethrough a base class ignore the shadowed implementation.

Shared
A shared function is callable without creating an object of the class. It is, in this strange sense,shared by all objects of the class. These are also called static functions.

AccessModifier

Use: Optional Type: Keyword

One of the following keywords: Public, Private, Protected, Friend, Protected Friend. The upcoming table describes the effects of the various access modifiers. Note that direct access refers to accessing the member without any qualification, as in: classvariable = 100 and class/object access refers to accessing the member through qualification, either with the class name or the name of an object of that class.

TABLE

TABLE

name

Use: Required Type: String literal

The name of the function.

arglist

Use: Optional

A comma-delimited list of variables to be passed to the function as arguments from the calling procedure.

Optional

Use: Optional Type: Keyword

An optional argument is one that need not be supplied when calling the function. However, all arguments following an optional one must also be optional. A ParamArray argument cannot be optional.

ByVal

Use: Optional Type: Keyword

The argument is passed by value; that is, the local copy of the variable is assigned the value of the argument.

ByRef

Use: Optional Type: Keyword

The argument is passed by reference; that is, the local variable is simply a reference to the argument being passed. All changes made to the local variable will be also reflected in the calling argument. ByVal is the default method of passing variables.

ParamArray

Use: Optional Type: Keyword

Indicates that the argument is an optional array of Objects containing an arbitrary number of elements. It can only be used as the last element of the argument list, and it cannot be used with the ByRef, ByVal, or Optional keywords.

varname

Use: Required Type: String literal

The name of the local variable containing either the reference or value of the argument.

type

Use: Optional Type: Keyword

The data type of the argument.
defaultvalue

Use: Optional Type: String literal

For optional arguments, you must specify a default value.

type

Use: Optional Type: Keyword

The return data type of the function.

statements

Use: Optional Program code to be executed within the function.

expression

Use: Optional The value to return from the function to the calling procedure.

Description
Defines a function procedure

Rules at a Glance

  • Functions cannot be nested, that is, you cannot define one function inside another function. (This applies to all procedures.)
  • If you do not include one of the access keywords, a function will be Public by default.
  • Any number of Exit Function statements can be placed within the function. Execution will continue with the line of code immediately following the call to the function. If a value has not been assigned to the function when the Exit Function statement executes, the function will return the default initialization value of the data type specified for the return value of the function. If the data type of the function was an object reference, the exited function will return Nothing.
  • The return value of a function is passed back to the calling procedure by assigning a value to the function name. This may be done more than once within the function.
  • To return arrays of any type from a procedure, you must use parentheses after the data type in the return value of the function declaration, as in:

Public Function Test() As Integer( )

  • If you specify an optional parameter in your function declaration, you must also provide a default value for that parameter. For example:Private Function ShowMessage(Optional sMsg _ As String = "Not given")

Programming Tips and Gotchas

  • There is often confusion between using the ByRef and ByVal methods to assign arguments to a function. ByRef assigns a reference of the variable in the calling procedure to the variable in the function; any changes made to the variable from within the function are in reality made to the variable in the calling procedure. On the other hand, ByVal assigns the value of the variable in the calling procedure to the variable in the function. Changes made to the variable in the function have no effect on the variable in the calling procedure. In general, ByRef arguments within class modules take longer to perform, since marshaling back and forth between function and calling module must take place; so unless you explicitly need to modify a variable's value within a function, it's best to pass parameters by value.
  • Since a variable passed to a function by reference is actually modified by the function, you can use such variables to "return" multiple values from the function.

VB .NET/VB 6 Differences

  • If a parameter array is used in VB 6, it is a comma-delimited list of values in the calling procedure that is treated as an array of variants in the called function. In VB .NET, the arguments can be any data type, and they can be either an comma-delimited list of scalar values or an array.
  • In VB 6, the elements in parameter arrays are passed by reference; in VB .NET, they are passed by value.
  • If you do not specify whether an individual element in arglist is passed ByVal or ByRef, it is passed by reference in VB 6. In VB .NET, it is passed by value.
  • In VB 6, you can call a function that has arguments in a number of ways:
  • x = SomeFunction(arg1, arg2)
  • Call SomeFunction(arg1, arg2)
  • SomeFunction arg1, arg2

In VB .NET, parentheses are required in the function call:
x = SomeFunc(arg1, arg2)
Call SomeFunc(arg1, arg2)
SomeFunc(arg1, arg2)

  • In VB 6, optional arguments do not require that you specify a default value. Instead, the IsMissing function is used to determine whether the optional argument is supplied (although in some cases it is unreliable). In VB .NET, you must assign a default value to an optional argument.

FV Function

Class

Microsoft.VisualBasic.Financial

Syntax
FV(rate, nper, pmt[, pv [, due]])
rate

Use: Required

Data Type: Double

The interest rate per period

nper

Use: Required Data Type: Integer

The number of payment periods in the annuity

pmt

Use: Required Data Type: Double

The payment made in each period

pv

Use: Optional Data Type: Variant

The present value of the loan or annuity

due

Use: Optional

Data Type: Constant of the DueDate enumeration that specifies whether payments are due atthe start or the end of the period. The value can be DueDate.BegOfPeriod or DueDate.EndOfPeriod (the default).

Return Value
A Double specifying the future value of an annuity

Description
Calculates the future value of an annuity (either an investment or loan) based on a regular number ofpayments of a fixed value and a static interest rate over the period of the annuity.

Rules at a Glance

  • The time units used for the number of payment periods, the rate of interest, and the payment amount must be the same. In other words, if you state the payment period in months, you must also express the interest rate as a monthly rate and the amount paid per month.
  • The rate per period is stated as a fraction of 100. For example, 10% is stated as .10. If you are calculating using monthly periods, you must also divide the rate per period by 12. Therefore, 10% per annum, for example, equates to a rate per period of .00833.
  • The pv argument is most commonly used as the initial value of a loan. The default is 0.
  • Payments made against a loan or added to the value of savings are expressed as negative numbers.
  • The default value for the due argument is DueDate.EndOfPeriod.


All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

VB.NET Topics