RaiseEvent Statement VB.NET

Syntax

RaiseEvent eventName([arglist])

Description

Generates a predefined, custom event within any procedure of an object module

Rules at a Glance

  • eventName must already be defined in the Declarations section of the module using the Event statement.
  • arglist must match the number and data type of parameters defined in the Event statement and must be surrounded by parentheses.
  • The RaiseEvent and Event statements can only be used in object modules and not in code modules.

Example

The following code snippet demonstrates how you can use an event to communicate a status message back to the client application and, at the same time, use a ByRef argument to trap a user response in the client application. This gets around the fact that events can't return values. To take advantage of this functionality, the client must declare a reference to this class using the WithEvents keyword.

Programming Tips and Gotchas

  • To allow the client application to handle the event being fired, the object variable must be declared using the WithEvents keyword.
  • VB custom events do not return a value; however, you can use a ByRef argument in arglist to simulate a return value, as shown in the previous example.
  • RaiseEvent is not asynchronous. In other words, when you call the RaiseEvent statement in your class code, your class code will not continue executing until the event has been either handled by the client or ignored (if the client is not handling the events raised by the class). This can have undesirable side effects, and you should bear it mind when planning your application. For example, you may have a recordset open or a transaction pending and have to wait for the user to respond to a message dialog box at the client. This could easily turn into a bottleneck, adversely affecting the scalability of your application.

Randomize Procedure

Class

Microsoft.VisualBasic.VBMath

Syntax

Randomize([number])

Description

Initializes the random-number generator

Rules at a Glance

  • Randomize uses number as a new seed value to initialize the random-number generator used by the Rnd function. The seed value is an initial value that is used to generate a sequence of pseudorandom numbers.
  • If you do not pass number to the Randomize procedure, the value of the system timer will be used as the new seed value.
  • Repeatedly passing the same number to Randomize does not cause Rnd to repeat the same sequence of random numbers.

Programming Tips and Gotchas

If you need to repeat a sequence of random numbers, you should call the Rnd function with a negative

number as an argument immediately prior to using Randomize with any numeric argument.

Rate Function

Class

Microsoft.VisualBasic.Financial

Syntax

Rate(nper, pmt, pv[, fv[, due[, guess]]])

A flag indicating whether payments are due at the beginning of the payment period (a value of DueDate.BegOfPeriod) or at the end of the payment period (a value of DueDate.EndOfPeriod, the default).

An estimate of the value to be returned by the function. If omitted, its value defaults to .1 (10%).

Return Value

A Double representing the interest rate per period

Description

Calculates the interest rate for an annuity (a loan or an investment) that consists of fixed payments over a known duration

Rules at a Glance

  • For pv and fv, cash paid out is expressed as a negative number; cash received is expressed as a positive number.
  • The function works using iteration. Starting with guess, Rate cycles through the calculation until the result is accurate to within 0.00001 percent. If a result can't be found after 20 tries, the function fails.

Programming Tips and Gotchas

  • In the case of a loan, pv is the loan amount. In the case of an investment, pv is the beginning balance.
  • In the case of a loan, fv is typically 0, reflecting that the entire loan has been paid. In the case of an investment, fv is the value of the investment with interest at the end of the investment period.
  • If the function fails because it could not calculate an accurate interest rate in 20 iterations, try a different value for guess.
  • The value returned by the function rate is the interest rate for the same time period as payments were made. Typically, this is one month, in which case you must multiply by 12 to derive the annual percentage rate.

ReDim Statement

Syntax

ReDim [Preserve] varname(subscripts) _

[, varname(subscripts) ...

The number of upper bounds specified is the number of dimensions. Each upper bound specifies the size of the corresponding coordinate.


Description

Used within a procedure to resize and reallocate storage space for an array

Rules at a Glance

  • Arrays can be sized or resized using the ReDim statement. There is no limit to the number of times you can redimension a dynamic array.
  • The dimension cannot be changed, nor can the data type of the array be changed.
  • If you do not use the Preserve keyword in redimensioning the array, you can resize any of the coordinates of the array.
  • Use of the Preserve keyword allows you to retain the current values within the array, but it also allows you to resize only the last coordinate of an array.
  • You can redimension an array in a called procedure if you pass the array to the procedure by reference. For example:


Note that this is contrary to the documentation, which indicates that arrays passed to called procedures by reference will return unmodified.

Programming Tips and Gotchas

  • If the ReDim Preserve statement is used to reduce the number of array elements, the data in the discarded elements is lost. And although this can be interpreted as a "narrowing" operation, it is unaffected by the state of the Option Strict setting.
  • Redimensioning an array, and particularly a large string array, can be expensive in terms of an application's performance. Consequently, frequent redimensioning, such as in the code fragment:

ReDim Preserve aNames(aNames(UBound)+1)

is not a good idea. Instead, it's best to allocate a "pool" of array elements by creating an array larger than needed, then using a counter to keep track of how many elements remain to be filled. For example:

VB .NET/VB 6 Differences

  • In VB 6, it is possible (though not recommended) to declare a dynamic array using the ReDim statement, then to use the ReDim statement again to redimension it. In VB .NET with Option Explicit Off, using the ReDim statement to declare an array is not permitted and generates a compiler error.
  • In VB 6, only arrays declared without an explicit number of elements, such as:

Dim arr( ) As Variant

were dynamic arrays and could be redimensioned using ReDim. In VB .NET, all arrays are dynamic.

  • VB 6 allows you to redimension both the upper and lower bounds of an array. Since VB .NET does not allow you to configure an array's lower bound, you can modify the array's upper bound only.
  • In VB 6, it is possible to change the number of dimensions of an array as long as the Preserve keyword isn't used. VB .NET, on the other hand, does not allow you to change the number of dimensions of an array.
  • Although neither VB 6 nor VB .NET permit you to change the data type of an array, the ReDim statement in VB 6 nevertheless supports an As type clause that allows you to declare the redimensioned array's data type. As long as type is the same as the originally declared type, ReDim won't generate a compiler error. In VB .NET, the use of the As type clause is not supported.

Rem Statement

Syntax

Rem comment

' comment

Description

Use the Rem statement or an apostrophe (') to place remarks within the code.

Rules at a Glance

  • Text or code commented out using either the Rem statement or an apostrophe is not compiled into the final program and, therefore, does not add to the size of the executable.
  • If you use the Rem statement on the same line as program code, a colon is required after the program code and before the Rem statement. For example:

This is not necessary when using the much more common apostrophe:

  • Apostrophes held within quotation marks are not treated as comment markers, as this code snippet shows:

myVar = 'Something'

Programming Tips and Gotchas

  • The Visual Studio development environment contains block-comment and block-uncomment buttons on the Text Editor toolbar, which allow you to comment out or uncomment a selection of many rows of code at once.
  • You cannot use the line-continuation character with comments.

VB .NET/VB 6 Differences

In VB 6, if a line containing a comment ends in an underscore (the line continuation character), the

following line is interpreted as a comment as well. In VB .NET, line continuation characters are ignored

at the end of a comment line; each comment line must be prefaced with the Rem statement or the 'symbol.

Rename Procedure

Class

Microsoft.VisualBasic.FileSystem

Syntax

Rename(oldpath, newpath)

Description

Renames a disk file or folder

Rules at a Glance

  • newpath must not already exist, or an error will be generated.
  • oldpath must exist; the Rename procedure isn't able to create a new file or directory.
  • When renaming a file or folder, both newpath and oldpath should include a path to the same folder, or the function will move the file or directory. For instance, the statement:

Rename("c:TempGraphics", "Images")

renames the Graphics folder to Images and moves it so that it becomes a subdirectory of the current directory.

  • Path information included in newpath and oldpath can take the form of the local system's path or the UNC path. The local system path can be either a fully qualified path or a relative path from the current directory.
  • newpath and oldpath can be on different drives, but if they are, Rename cannot both move the files and rename them.
  • newpath and oldpath cannot include the wildcard characters ? and *.
  • You cannot use the Rename procedure with a file that is already open.

Programming Tips and Gotchas

The Rename procedure can be used to move a file from one folder to another and, optionally, to change the file's name at the same time. If the folder specified in newname exists and is different from that stated in oldname, the file will be moved to the folder specified in newname. If the filename in newname is also different, the file will be renamed at the same time.

VB .NET/VB 6 Differences

The Rename procedure is new to VB .NET.

Replace Function

Class

Microsoft.VisualBasic.Strings


Syntax

Replace(expression, find, replace [, _

start[, count[, compare]]])

The character position in expression at which the search for find begins

The method used to compare find with expression; its value can be CompareMethod.Binary (for case-sensitive comparison) or CompareMethod.Text (for case-insensitive comparison)

Return Value

The return value from Replace depends on the parameters you specify in the argument list, as the following table shows.

TABLE

TABLE

Description

Replaces a given number of instances of a specified substring in another string

Rules at a Glance

  • If start is omitted, the search begins at the start of the string.
  • If count is omitted, all instances of the substring after start are replaced.
  • CompareMethod.BinaryCompare is case sensitive; that is, Replace matches both character and case, whereas CompareMethod.Text is case insensitive, matching only character regardless of case.
  • The default value for compare is CompareMethod.Binary.
  • start not only specifies where the search for stringToReplace begins, but also where the new string returned by the Replace function will commence.

Programming Tips and Gotchas

  • If count is not used, be careful when replacing short strings that may form parts of unrelated words. For example, consider the following:

Because we don't specify a value for count, the call to Replace replaces every occurrence of "you" in the original string with "we". But the fourth occurrence of "you" is part of the word "your", which is modified to become "wer".

  • You must also be aware that if start is greater than 1, the returned string starts at that character and not at the first character of the original string, as you might expect. For example, given the statements:

  • sNew will contain the value:

"string tests the Replace function"

  • You can use the Mid function on the left side of an argument to replace part of string, but to replace more than one instance of a substring requires a complicated Do While loop that constantly checks for the position of any remaining instances of the substring to be replaced.
  • The BCL's System.String class also has a public instance Replace method, which replaces all occurrences of a character or string with another. Its syntax is:

sString.Replace(oldValue, newValue)

where oldValue is a String or Char value containing the text to be replaced and newValue is a String or Char value containing the replacement text.

Reset Procedure

Class

Microsoft.VisualBasic.FileSystem


Syntax

Reset( )

Description

Closes all files that have been opened using the FileOpen procedure

Rules at a Glance

The contents of any current file buffers are written to disk by the Reset procedure immediately prior to

Reset closing the respective files.

Programming Tips and Gotchas

The Reset procedure is generally used as a last resort, cleaning up if your program is terminating abnormally. Normally, you should write code to close each open file using the FileClose procedure.

Resume Statement

Syntax

Resume [0]

Resume Next

Resume label

Description

Used to continue program execution when an error-handling routine is complete

Rules at a Glance

Resume can take any of the forms shown in the following table.

TABLE

TABLETABLE

Programming Tips and Gotchas

  • You can only use the Resume statement in an error-handling routine; otherwise, a runtime error will be generated.
  • An error-handling routine does not necessarily have to contain a Resume statement. If the error-handling routine is at the end of the procedure and the result of the error handling would be to exit the procedure, you can simply allow the program to execute the End Sub or End Function statement. This has the effect of both resetting the Err object and exiting the procedure. This is shown in the following simple code snippet:

Return Statement

Syntax

In a subroutine:

Return

In a function:

Return ReturnValue

Description

Returns to the calling program from a subroutine or function

Rules at a Glance

  • If the Return statement appears in a function, it must specify a return value for the function.
  • Return causes program flow to leave the function or subroutine and return to the calling program; any statements in the function or subroutine that follow Return are not executed.

Example

Programming Tips and Gotchas

  • Return is identical in operation to the Exit Sub statement: it prematurely transfers control from a
  • procedure to the calling routine. It is also similar to the Exit Function statement; while it prematurely transfers control out of the function, it also allows a particular value to be returned by the function.

VB .NET/VB 6 Differences

In VB 6, Return is a legacy statement that returns control after GoSub has invoked a subroutine within a procedure. In VB .NET, however, Return returns control from a called function or procedure and optionally allows the function's return value to be defined.

RGB Function

Class

Microsoft.VisualBasic.Information

Syntax

RGB(red, green, blue)

Return Value

An Integer representing the RGB color value

Description

Returns a system color code that can be assigned to object color properties

Rules at a Glance

  • The RGB color value represents the relative intensity of the red, green, and blue components of a pixel that produces a specific color on the display.
  • The RGB function assumes any argument greater than 255 to be 255.
  • The following table demonstrates how the individual color values combine to create certain colors:

TABLE

TABLE

Programming Tips and Gotchas

  • The RGB value is actually derived using the following formula:

In other words, the individual color components are stored in the opposite order than you would expect. VB stores the red color component in the low-order byte of the integer's loworder word, the green color in the high-order byte of the low-order word, and the blue color in the low-order byte of the high-order word.

  • Visual Basic now contains a wide range of intrinsic color constants that can be used to assign color values directly to color properties of objects.

Right Function

Class

Microsoft.VisualBasic.Strings

Syntax

Right(string, length)

Return Value

String

Description

Returns a string containing the rightmost length characters of string

Rules at a Glance

  • If length is 0, a zero-length string ("") is returned.
  • If length is greater than the length of string, string is returned.
  • If length is less than zero or is Nothing, an error is generated.
  • If string contains a Nothing, Right returns Nothing.

Example

The following function assumes that it is passed either a filename or a complete path and filename,

and it returns the filename from the end of the string:

Programming Tips and Gotchas

Use the Len function to determine the total length of string.

RmDir Procedure

Class

Microsoft.VisualBasic.FileSystem

Syntax

RmDir(path)

Description

Removes a folder

Rules at a Glance

  • You may include a drive letter in path; if you don't specify a drive letter, the folder is assumed to be on the current drive.
  • path can be a fully qualified, relative, or UNC pathname.
  • If the folder contains files or other folders, RmDir will generate runtime error 75, "Path/File access error."

Example

The following subroutine deletes all the files in a folder and removes its subfolders. If those contain files or folders, it deletes those too by recursively calling itself until all child folders and their files are removed.

Programming Tips and Gotchas

  • Use the Kill procedure to delete any remaining files from the folder prior to removing the folder.
  • The effects of using Kill and RmDir are irreversible, since these statements do not move deleted files to the Recycle Bin.

Rnd Function

Class

Microsoft.VisualBasic.VBMath

Syntax

Rnd[(number)]

Return Value

A Single data type random number

Description

Returns a random number

Rules at a Glance

  • The behavior of the Rnd function is determined by number, as described in the following table:

TABLE

behavior of the Rnd function is determined by number

  • The Rnd function always returns a value between and 1.
  • If number is not supplied, the Rnd function will use the last number generated as the seed for the next generated number. This means that given an initial seed (seed), the same sequence will be generated if number is not supplied on subsequent calls.

Example

The following example uses the Randomize procedure along with the Rnd function to fill 100 cells of an Excel worksheet with random numbers. It requires that a reference to the Microsoft Excel Object Library be added to the project. It also leaves the instance of Excel running once the code has finished execution.

Programming Tips and Gotchas

  • Before calling the Rnd function, you should use the Randomize procedure to initialize the random-number generator.
  • The standard formula for producing numbers in a given range is as follows:

Int((highest - lowest + 1) * Rnd + lowest)

where lowest is the lowest required number in the range and highest is the highest.

Round Function

Class

System.Math

Syntax

Math.Round( value[,digits])

Return Value

The same data type as value

Description

Rounds a given number to a specified number of decimal places

Rules at a Glance

  • digits can be any whole number between 0 and 16.
  • Round follows standard rules for rounding. If the digit in the position to the right of digits is 5 or greater, the digit in the digits position is incremented by one; otherwise, the digits to the right of digits are dropped.
  • This is a Shared member, so it can be used without creating any objects.

Programming Tips and Gotchas

  • Round with digits set to 2 is the equivalent of Format (expression, "#.##").

If value is a string representation of a numeric value, Round will convert it to a numeric value before rounding. However, if expression is not a string representation of a number, Round generates runtime error 13, "Type mismatch." The IsNumeric function can be used to ensure that expression is a proper numeric representation before calling Round

  • If value contains fewer decimal places than digits, Round does not pad the return value with trailing zeroes.

VB .NET/VB 6 Differences

The named parameters of the Round function differ in VB 6 and in the .NET Framework. In VB 6, the

named arguments are number and numdigitsafterdecimal. In VB .NET, they're value and digits.

RTrim Function

Class

Microsoft.VisualBasic.Strings

Syntax

RTrim(string)

Return Value

String

Description

Removes any trailing spaces from string

Rules at a Glance

If string contains a Nothing, RTrim returns Nothing.


Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

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

VB.NET Topics