NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Visual Basic Language Reference

Constants

Data Types

Directives

Events

Functions

Keywords

Methods

Miscellaneous

Objects

Operators

Properties

Statements


Visual Basic Constants

Visual Studio for Applications defines constants to simplify your programming. The following constants can be used anywhere in your code in place of the actual values:

CallType Constants

Color Constants

Comparison Constants

Compiler Constants

Date Constants

Date Format Constants

Dir, GetAttr, and SetAttr Constants

DriveType Constants

File Attribute Constants

File Input/Output Constants

Keycode Constants

Miscellaneous Constants

MsgBox Constants

Shell Constants

SpecialFolder Constants

StrConv Constants

System Color Constants

Tristate Constants

Visual Basic Constants

See Also

DateDiff Function | DatePart Function | Dir Function | Filter Function | Format Function | FormatCurrency Function | FormatDateTime Function | FormatNumber Function | FormatPercent Function | GetAttr Function | InStr Function | InStrRev Function | MsgBox Function | Replace Function | SetAttr Statement | Shell Function | Split Function | StrConv Function | Weekday Function | WeekdayName Function


CallType Constants

The following constantscan be used anywhere in your code in place of the actual values:

Constant | Value | Decription
Method | 1 | Indicates that a method has been invoked.

See Also

CallByName Function


Color Constants

The following constants can be used anywhere in your code in place of the actual values:

Constant | Value | Description
Black | 0x0 | Black
Red | 0xFF | Red
Green | 0xFF00 | Green
Yellow | 0xFFFF | Yellow
Blue | 0xFF0000 | Blue
Magenta | 0xFF00FF | Magenta
Cyan | 0xFFFF00 | Cyan
White | 0xFFFFFF | White

See Also

Date Format Constants | DriveType Constants | File Attribute Constants | File Input/Output Constants | SpecialFolder Constants | Tristate Constants | Visual Basic Constants


ColorConstants (Object Browser)

The ColorConstants module contains predefined color constants. These constants can be used anywhere in your code.

To get Help on a particular constant

  1. Select the constant from the Members of 'ColorConstants' list.
  2. Click the button.

See Also


Comparison Constants

When using comparison functions, the following constants are defined in the Visual Studio for Applications type library and can be used in your code in place of the actual values:

Constant | Value | Description
BinaryCompare | 0 | Performs a binary comparison.
TextCompare | 1 | Performs a textual comparison.

See Also

Date Format Constants | DriveType Constants | File Attribute Constants | File Input/Output Constants | Filter Function | InStr Function | InStrRev Function | Replace Function | SpecialFolder Constants | Split Function | StrComp Function | Tristate Constants | Visual Basic Constants


Compiler Constants

Visual Studio for Applications defines constants for exclusive use with the #If...Then...#Else directive. These constants are functionally equivalent to constants defined with the #If...Then...#Else directive except that they are global in scope; that is, they apply everywhere in a project.

On 16-bit development platforms, the compiler constants are defined as follows:

Constant | Value | Description
Win16 | True | Indicates development environment is 16-bit.
Win32 | False | Indicates that the development environment is not 32-bit.

On 32-bit development platforms, the compiler constants are defined as follows:

Constant | Value | Description
Win16 | False | Indicates that the development environment is not 16-bit.
Win32 | True | Indicates that the development environment is 32-bit.

Note These constants are provided by Visual Basic, so you cannot define your own constants with these same names at any level.

See Also

#Const Directive | #If...Then...#Else Directive | Visual Basic Constants


Constants (Object Browser)

The Constants module contains miscellaneous constants. These constants can be used anywhere in your code.

To get Help on a particular constant

  1. Select the constant from the Members of 'Constants' list.
  2. Click the button.

See Also

Dir Function | GetAttr Function | IMEStatus Function | MsgBox Function | SetAttr Statement | StrConv Function | Visual Basic Constants


Date Constants

When using date-related functions, the following constants can be used in your code in place of the actual values:

Argument Values

Some date-related functions will take a firstdayofweek argument, while others will take a firstdayofyear argument. The constants specify the valid values for these arguments, as well as the possible return values from the functions

The firstdayofweek argument has the following values:

Constant | Value | Description
UseSystem DayOfWeek | 0 | Use the day of the week specified in your system settings for the first day of the week.
Sunday | 1 | Sunday (default)
Monday | 2 | Monday
Tuesday | 3 | Tuesday
Wednesday | 4 | Wednesday
Thursday | 5 | Thursday
Friday | 6 | Friday
Saturday | 7 | Saturday

The firstdayofyear argument has the following values:

Constant | Value | Description
System | 0 | Use the day of the week specified in your system settings for the first day of the week.
Jan1 | 1 | Start with week in which January 1 occurs (default).
FirstFourDays | 2 | Start with the first week that has at least four days in the new year.
FirstFullWeek | 3 | Start with the first full week of the year.

Return Values

Constant | Value | Description
Sunday | 1 | Sunday
Monday | 2 | Monday
Tuesday | 3 | Tuesday
Wednesday | 4 | Wednesday
Thursday | 5 | Thursday
Friday | 6 | Friday
Saturday | 7 | Saturday

See Also

Date Format Constants | DateDiff Function | DatePart Function | DriveType Constants | File Attribute Constants | File Input/Output Constants | Format Function | Tristate Constants | Visual Basic Constants | Weekday Function


Date Format Constants

These constants are only available when your project has an explicit reference to the appropriate type library containing these constant definitions.

Constant | Value | Description
GeneralDate | 0 | Display a date and/or time. For real numbers, display a data and time. If there is no fractional part, display only a date. If there is no integer part, display time only. Date and time display is determined by your system settings.
LongDate | 1 | Display a date using the long date format specified in your computer's regional settings.
ShortDate | 2 | Display a date using the short date format specified in your computer's regional settings.
LongTime | 3 | Display a time using the long time format specified in your computer's regional settings.
ShortTime | 4 | Display a time using the short time format specified in your computer's regional settings.

See Also

DriveType Constants | File Attribute Constants | File Input/Output Constants | SpecialFolder Constants | Tristate Constants


Dir, GetAttr, and SetAttr Constants

When using the Dir or GetAttr function or the SetAttr Statement, the following constants can be used in your code in place of the actual values:

Constant | Value | Description
Normal | 0 | Normal (default for Dir and SetAttr)
ReadOnly | 1 | Read-only
Hidden | 2 | Hidden
System | 4 | System file
Volume | 8 | Volume label
Directory | 16 | Directory or folder
Archive | 32 | File has changed since last backup

See Also

Dir Function | GetAttr Function | SetAttr Statement | Visual Basic Constants


DriveType Constants

These constants are only available when your project has an explicit reference to the appropriate type library containing these constant definitions.

Constant | Value | Description
Unknown | 0 | Drive type can't be determined.
Removable | 1 | Drive has removable media. This includes all floppy drives and many other varieties of storage devices.
Fixed | 2 | Drive has fixed (nonremovable) media. This includes all hard drives, including hard drives that are removable.
Remote | 3 | Network drives. This includes drives shared anywhere on a network.
CDROM | 4 | Drive is a CD-ROM. No distinction is made between read-only and read/write CD-ROM drives.
RAMDisk | 5 | Drive is a block of Random Access Memory (RAM) on the local computer that behaves like a disk drive.

See Also

Date Format Constants | File Attribute Constants | File Input/Output Constants | SpecialFolder Constants | Tristate Constants


File Attribute Constants

These constants are only available when your project has an explicit reference to the appropriate type library containing these constant definitions.

Constant | Value | Description
Normal | 0 | Normal file. No attributes are set.
ReadOnly | 1 | Read-only file. Attribute is read/write.
Hidden | 2 | Hidden file. Attribute is read/write.
System | 4 | System file. Attribute is read/write.
Volume | 8 | Disk drive volume label. Attribute is read-only.
Directory | 16 | Folder or directory. Attribute is read-only.
Archive | 32 | File has changed since last backup. Attribute is read/write.
Alias | 64 | Link or shortcut. Attribute is read-only.

See Also

Date Format Constants | DriveType Constants | File Input/Output Constants | SpecialFolder Constants | Tristate Constants


File Input/Output Constants

These constants are only available when your project has an explicit reference to the appropriate type library containing these constant definitions.

Constant | Value | Description
ForReading | 1 | Open a file for reading only. You can't write to this file.
ForWriting | 2 | Open a file for writing. If a file with the same name exists, its previous contents are overwritten.
ForAppending | 8 | Open a file and write to the end of the file.

See Also

Date Format Constants | DriveType Constants | File Attribute Constants | SpecialFolder Constants | Tristate Constants


FormShowConstants (Object Browser)

The FormShowConstants module contains predefined UserForm constants. These constants can be used anywhere in your code.

To get Help on a particular constant

  1. Select the constant from the Members of 'FormShowConstants' list.
  2. Click the button.

See Also


Keycode Constants

The following constants can be used anywhere in your code in place of the actual values:

Constant | Value | Description
KeyLButton | 0x1 | Left mouse button
KeyRButton | 0x2 | Right mouse button
KeyCancel | 0x3 | CANCEL key
KeyMButton | 0x4 | Middle mouse button
KeyBack | 0x8 | BACKSPACE key
KeyTab | 0x9 | TAB key
KeyClear | 0xC | CLEAR key
KeyReturn | 0xD | ENTER key
KeyShift | 0x10 | SHIFT key
KeyControl | 0x11 | CTRL key
KeyMenu | 0x12 | MENU key
KeyPause | 0x13 | PAUSE key
KeyCapital | 0x14 | CAPS LOCK key
KeyEscape | 0x1B | ESC key
KeySpace | 0x20 | SPACEBAR key
KeyPageUp | 0x21 | PAGE UP key
KeyPageDown | 0x22 | PAGE DOWN key
KeyEnd | 0x23 | END key
KeyHome | 0x24 | HOME key
KeyLeft | 0x25 | LEFT ARROW key
KeyUp | 0x26 | UP ARROW key
KeyRight | 0x27 | RIGHT ARROW key
KeyDown | 0x28 | DOWN ARROW key
KeySelect | 0x29 | SELECT key
KeyPrint | 0x2A | PRINT SCREEN key
KeyExecute | 0x2B | EXECUTE key
KeySnapshot | 0x2C | SNAPSHOT key
KeyInsert | 0x2D | INSERT key
KeyDelete | 0x2E | DELETE key
KeyHelp | 0x2F | HELP key
KeyNumlock | 0x90 | NUM LOCK key

The A key through the Z key are the same as the ASCII equivalents A – Z:

Constant | Value | Description
KeyA | 65 | A key
KeyB | 66 | B key
KeyC | 67 | C key
KeyD | 68 | D key
KeyE | 69 | E key
KeyF | 70 | F key
KeyG | 71 | G key
KeyH | 72 | H key
KeyI | 73 | I key
KeyJ | 74 | J key
KeyK | 75 | K key
KeyL | 76 | L key
KeyM | 77 | M key
KeyN | 78 | N key
KeyO | 79 | O key
KeyP | 80 | P key
KeyQ | 81 | Q key
KeyR | 82 | R key
KeyS | 83 | S key
KeyT | 84 | T key
KeyU | 85 | U key
KeyV | 86 | V key
KeyW | 87 | W key
KeyX | 88 | X key
KeyY | 89 | Y key
KeyZ | 90 | Z key

The 0 key through 9 key are the same as their ASCII equivalents 0 – 9:

Constant | Value | Description
Key0 | 48 | 0 key
Key1 | 49 | 1 key
Key2 | 50 | 2 key
Key3 | 51 | 3 key
Key4 | 52 | 4 key
Key5 | 53 | 5 key
Key6 | 54 | 6 key
Key7 | 55 | 7 key
Key8 | 56 | 8 key
Key9 | 57 | 9 key

The following constants represent keys on the numeric keypad:

Constant | Value | Description
KeyNumpad0 | 0x60 | 0 key
KeyNumpad1 | 0x61 | 1 key
KeyNumpad2 | 0x62 | 2 key
KeyNumpad3 | 0x63 | 3 key
KeyNumpad4 | 0x64 | 4 key
KeyNumpad5 | 0x65 | 5 key
KeyNumpad6 | 0x66 | 6 key
KeyNumpad7 | 0x67 | 7 key
KeyNumpad8 | 0x68 | 8 key
KeyNumpad9 | 0x69 | 9 key
KeyMultiply | 0x6A | MULTIPLICATION SIGN (*) key
KeyAdd | 0x6B | PLUS SIGN (+) key
KeySeparator | 0x6C | ENTER key
KeySubtract | 0x6D | MINUS SIGN (–) key
KeyDecimal | 0x6E | DECIMAL POINT (.) key
KeyDivide | 0x6F | DIVISION SIGN (/) key

The following constants represent function keys:

Constant | Value | Description
KeyF1 | 0x70 | F1 key
KeyF2 | 0x71 | F2 key
KeyF3 | 0x72 | F3 key
KeyF4 | 0x73 | F4 key
KeyF5 | 0x74 | F5 key
KeyF6 | 0x75 | F6 key
KeyF7 | 0x76 | F7 key
KeyF8 | 0x77 | F8 key
KeyF9 | 0x78 | F9 key
KeyF10 | 0x79 | F10 key
KeyF11 | 0x7A | F11 key
KeyF12 | 0x7B | F12 key
KeyF13 | 0x7C | F13 key
KeyF14 | 0x7D | F14 key
KeyF15 | 0x7E | F15 key
KeyF16 | 0x7F | F16 key


KeycodeConstants (Object Browser)

The KeyCodeConstants module contains predefined keycode constants that can be used anywhere in your code.

To get Help on a particular constant

  1. Select the constant from the Members of 'KeyCodeConstants' list.
  2. Click the button.

See Also


Miscellaneous Constants

The following constants are defined in the Visual Studio for Applications type library and can be used in your code in place of the actual values:

Constant | Equivalent | Description
CrLf | Chr(13) + Chr(10) | Carriage return–linefeed combination
Cr | Chr(13) | Carriage return character
Lf | Chr(10) | Linefeed character
NewLine | Chr(13) + Chr(10) | Platform-specific new line character; whichever is appropriate for current platform
NullChar | Chr(0) | Character having value 0
NullString | String having value 0 | Not the same as a zero-length string (""); used for calling external procedures
ObjectError | -2147221504 | User-defined error numbers should be greater than this value. For example: Err.Raise Number = vbObjectError + 1000
Tab | Chr(9) | Tab character
Back | Chr(8) | Backspace character
FormFeed | Chr(12) | Not useful in Microsoft Windows
VerticalTab | Chr(11) | Not useful in Microsoft Windows

See Also

Date Format Constants | DriveType Constants | File Attribute Constants | File Input/Output Constants | SpecialFolder Constants | Tristate Constants | Visual Basic Constants


MsgBox Constants

While working with a MsgBox, the following constants can be used in your code in place of the actual values:

MsgBox Arguments

Constant | Value | Description
OKOnly | 0 | OK button only (default)
OKCancel | 1 | OK and Cancel buttons
AbortRetryIgnore | 2 | Abort, Retry, and Ignore buttons
YesNoCancel | 3 | Yes, No, and Cancel buttons
YesNo | 4 | Yes and No buttons
RetryCancel | 5 | Retry and Cancel buttons
Critical | 16 | Critical message
Question | 32 | Warning query
Exclamation | 48 | Warning message
Information | 64 | Information message
DefaultButton1 | 0 | First button is default (default)
DefaultButton2 | 256 | Second button is default
DefaultButton3 | 512 | Third button is default
ApplicationModal | 0 | Application modal message box (default)
SystemModal | 4096 | System modal 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

MsgBox Return Values

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

See Also

Date Format Constants | DriveType Constants | File Attribute Constants | File Input/Output Constants | MsgBox Function | SpecialFolder Constants | Tristate Constants | Visual Basic Constants


Shell Constants

When using the Shell commands, the following constants can be used in your code in place of the actual values:

Constant | Value | Description
Hide | 0 | Window is hidden and focus is passed to the hidden window.
NormalFocus | 1 | Window has focus and is restored to its original size and position.
MinimizedFocus | 2 | Window is displayed as an icon with focus.
MaximizedFocus | 3 | Window is maximized with focus.
NormalNoFocus | 4 | Window is restored to its most recent size and position. The currently active window remains active.
MinimizedNoFocus | 6 | Window is displayed as an icon. The currently active window remains active.

See Also

Shell Function | Visual Basic Constants


SpecialFolder Constants

These constants are only available when your project has an explicit reference to the appropriate type library containing these constant definitions.

Constant | Value | Description
WindowsFolder | 0 | The Windows folder contains files installed by the Windows operating system.
SystemFolder | 1 | The System folder contains libraries, fonts, and device drivers.
TemporaryFolder | 2 | The Temp folder is used to store temporary files. Its path is found in the TMP environment variable.

See Also

Date Format Constants | DriveType Constants | File Attribute Constants | File Input/Output Constants | Tristate Constants


StrConv Constants

When using the StrConv function, the following constants can be used in your code in place of the actual values:

Constant | Value | Description
UpperCase | 1 | Converts the string to uppercase characters.
LowerCase | 2 | Converts the string to lowercase characters.
ProperCase | 3 | Converts the first letter of every word in string to uppercase.
Wide | 4 | Converts narrow (single-byte) characters in string to wide (double-byte) characters. Applies to Asian locales.
Narrow | 8 | Converts wide (double-byte) characters in string to narrow (single-byte) characters. Applies to Asian locales.
Katakana | 16 | Converts Hiragana characters in string to Katakana characters. Applies to Japan only.
Hiragana | 32 | Converts Katakana characters in string to Hiragana characters. Applies to Japan only.
Unicode | 64 | Converts the string to Unicode using the default code page of the system.
FromUnicode | 128 | Converts the string from Unicode to the default code page of the system.

See Also

StrConv Function | Visual Basic Constants


System Color Constants

The following constants can be used anywhere in your code in place of the actual values:

Constant | Value | Description
ScrollBars | 0x80000000 | Scroll bar color
Desktop | 0x80000001 | Desktop color
ActiveTitleBar | 0x80000002 | Color of the title bar for the active window
InactiveTitleBar | 0x80000003 | Color of the title bar for the inactive window
MenuBar | 0x80000004 | Menu background color
WindowBackground | 0x80000005 | Window background color
WindowFrame | 0x80000006 | Window frame color
MenuText | 0x80000007 | Color of text on menus
WindowText | 0x80000008 | Color of text in windows
TitleBarText | 0x80000009 | Color of text in caption, size box, and scroll arrow
ActiveBorder | 0x8000000A | Border color of active window
InactiveBorder | 0x8000000B | Border color of inactive window
ApplicationWorkspace | 0x8000000C | Background color of multiple-document interface (MDI) applications
Highlight | 0x8000000D | Background color of items selected in a control
HighlightText | 0x8000000E | Text color of items selected in a control
ButtonFace | 0x8000000F | Color of shading on the face of command buttons
ButtonShadow | 0x80000010 | Color of shading on the edge of command buttons
GrayText | 0x80000011 | Grayed (disabled) text
ButtonText | 0x80000012 | Text color on push buttons
InactiveCaptionText | 0x80000013 | Color of text in an inactive caption
3DHighlight | 0x80000014 | Highlight color for 3-D display elements
3DDKShadow | 0x80000015 | Darkest shadow color for 3-D display elements
3DLight | 0x80000016 | Second lightest 3-D color after 3DHighlight
InfoText | 0x80000017 | Color of text in ToolTips
InfoBackground | 0x80000018 | Background color of ToolTips

See Also


SystemColorConstants (Object Browser)

The SystemColorConstants module contains constants that identify various parts of the graphical user interface. These constants can be used anywhere in your code.

To get Help on a particular constant

  1. Select the constant from the Members of 'SystemColorConstants' list.
  2. Click the button.

See Also


Tristate Constants

These constants are only available when your project has an explicit reference to the appropriate type library containing these constant definitions.

Constant | Value | Description
True | –1 | True
False | 0 | False
Default | –1 | Use default setting

See Also

Date Format Constants | DriveType Constants | File Attribute Constants | File Input/Output Constants | SpecialFolder Constants


Data Types (Visual Basic for Applications)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Data Types (Visual Basic Language Reference)

Data Type Summary

Boolean Data Type

Byte Data Type

Currency Data Type

Date Data Type

Decimal Data Type

Double Data Type

Integer Data Type

Long Data Type

Object Data Type

Single Data Type

String Data Type

User-Defined Data Type

Variant Data Type


Data Type Summary

The following table shows the supported data types, including NGWS runtime types, storage sizes and ranges.

VB Type | NGWS runtime Type | Storage size | Range
Byte | System.Byte | 1 byte | 0 to 255
Boolean | System.Bool | 2 bytes | True or False
Char | System.Char | 2 bytes | 0 to 65535
Short | System.Short | 2 bytes | -32,768 to 32,767
Integer | System.Int32 | 4 bytes | -2,147,483,648 to 2,147,483,647
Long (long integer) | System.Int64 | 8 bytes | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Decimal | System.Decimal | 12 bytes | +/-79,228,162,514,264,337,593,543,950,335 with no decimal point; +/-7.9228162514264337593543950335 with 28 places to the right of the decimal; smallest non-zero number is +/-0.0000000000000000000000000001
Single (single-precision floating-point) | System.Single | 4 bytes | -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values
Double (double-precision floating-point) | System.Double | 8 bytes | -1.79769313486231E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values
Date | System.DateTime | 8 bytes | January 1, 100 to December 31, 9999
Object | System.Object | 4 bytes | Any type may be contained in a variable of type Object
String (variable-length) | System.String | 10 bytes + string length | 0 to approximately 2 billion Unicode characters.

Note Arrays of any data type require 20 bytes of memory plus 4 bytes for each array dimension plus the number of bytes occupied by the data itself. The memory occupied by the data can be calculated by multiplying the number of data elements by the size of each element. For example, the data in a single-dimension array consisting of 4 Integer data elements of 4 bytes each occupies 16 bytes. The 16 bytes required for the data plus the 24 bytes of overhead brings the total memory requirement for the array to 40 bytes.
An Object containing an array requires 4 bytes more than the array alone.
Note Use the StrConv function to convert one type of string data to another.

See Also

Boolean Data Type | Byte Data Type | Char Data Type | Date Data Type | Decimal Data Type | Double Data Type | Int, Fix Functions | Integer Data Type | Long Data Type | Object Data Type | Short Data Type | Single Data Type | StrConv Function | String Data Type | Type Conversion Functions |Using Data Types Efficiently


Boolean Data Type

Boolean variables are stored as 16-bit (2-byte) numbers, but they can only be True or False. Boolean variables display as either True or False (when Print is used) or #TRUE# or #FALSE# (when Write is used). Use the keywords True and False to assign one of the two states to Boolean variables.

When other numeric types are converted to Boolean values, 0 becomes False and all other values become True. When Boolean values are converted to other data types, False becomes 0 and True becomes 1.

The equivalent NGWS runtime data type is System.Bool.

See Also

Conversion Keyword Summary | Data Type Summary | Integer Data Type | Type Conversion Functions | Using Data Types Efficiently


Byte Data Type

Byte variables are store an unsigned, 8-bit (1-byte) numbers ranging in value from 0–255.

The Byte data type is used for containing binary data.

Note The Byte data type can be converted to the Short, Integer, Long, Single, Double or Decimal data type, without encountering an OverflowException error.

The equivalent NGWS runtime data type is System.Byte.

See Also

Conversion Keyword Summary | Data Type Summary | Integer Data Type | Short Data Type | Type Conversion Functions | Using Data Types Efficiently


Char Data Type

Char variables are stored as 16-bit (2-byte) numbers ranging in value from 0-65535. Each 2-byte number stores a single Unicode character. Implicit conversions between the char data type and numeric types are not possible, but explicit conversion between the char data type and numeric types is supported.

The equivalent NGWS runtime data type is System.Char.

See Also

Data Type Summary | Integer Data Type


Date Data Type

Date variables are stored as IEEE 64-bit (8-byte) long integers that represent dates ranging from 1 January 1A.D. to 31 December 9999 and times from 0:00:00 to 23:59:59.

Depending on location, any recognizable literal date values can be assigned to Date variables. Date literals must be enclosed within number signs (#), for example, #January 1, 1993# or #1 Jan 93#. Also, Date variables display dates according to the short date format recognized by your computer. Times display according to the time format (either 12-hour or 24-hour) recognized by your computer.

The equivalent NGWS runtime data type is System.DateTime.

See Also

Conversion Keyword Summary | Data Type Summary | Double Data Type | Type Conversion Functions | Using Data Types Efficiently


Decimal Data Type

Decimal variables are stored as 96-bit (12-byte) signed integers scaled by a variable power of 10. The power of 10 scaling factor specifies the number of digits to the right of the decimal point, and ranges from 0 to 28. With a scale of 0 (no decimal places), the largest possible value is +/-79,228,162,514,264,337,593,543,950,335. With a 28 decimal places, the largest value is +/-7.9228162514264337593543950335 and the smallest, non-zero value is +/-0.0000000000000000000000000001.

The equivalent NGWS runtime data type is System.Decimal.

See Also

Conversion Keyword Summary | Data Type Summary | Type Conversion Functions | Using Data Types Efficiently


Double Data Type

Double (double-precision floating-point) variables are stored as IEEE 64-bit (8-byte) floating-point numbers ranging in value from -1.79769313486231E308 to -4.94065645841247E-324 for negative values and from 4.94065645841247E-324 to 1.79769313486232E308 for positive values.

Note The Double data type can be converted to the Decimal data type, without encountering an OverflowException error.

The equivalent NGWS runtime data type is System.Double.

See Also

Conversion Keyword Summary | Data Type Summary | Single Data Type | Type Conversion Functions | Using Data Types Efficiently


Integer Data Type

The Integer data type stores a numeric integer value. An Integer variable is stored as a 32-bit (4-byte) number ranging in value from-2,147,483,648 to 2,147,483,647.

The Integer data type provides optimal performance on a 32-bit processor, as the smaller integral types are slower to load and store from and to memory.

Note The Integer data type can be converted to Long, Single, Double or Decimal data type, without encountering an OverflowException error.

The equivalent NGWS runtime data type is System.Int32.

See Also

Conversion Keyword Summary | Data Type Summary | Integer Data Type | Long Data Type | Short Data Type | Type Conversion Functions | Using Data Types Efficiently


Long Data Type

Long (long integer) variables are stored as signed 64-bit (8-byte) numbers ranging in value from-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

Note The Long data type can be converted to the Single, Double or Decimal data type, without encountering an OverflowException error.

The equivalent NGWS runtime data type is System.Int64.

See Also

Conversion Keyword Summary | Data Type Summary | Integer Data Type | Short Data Type | Type Conversion Functions | Using Data Types Efficiently


Object Data Type

Object variables are stored as 32-bit (4-byte) addresses that refer to objects.You can assign any reference type (class or interface) to a variable declared as an Object.

The equivalent NGWS runtime data type is System.Object.

Note Although a variable declared with Object type is flexible enough to contain a reference to any object, the invocation of a method of an instance using an Object variable is always late (run-time binding). To force early binding (compile-time binding), assign the object reference to a variable declared with a specific class name or cast to the specific type.

See Also

Conversion Keyword Summary | Data Type Summary | IsObject Function | Type Conversion Functions | Using Data Types Efficiently


Short Data Type

Short (short integer) variables are stored as signed 16-bit (2-byte) numbers ranging in value from -32,678 to 32.767.

Note The Short data type can be converted to the Integer, Long, Single, Double or Decimal data type, without encountering an OverflowException error.

The equivalent NGWS runtime data type is System.Int16.

See Also

Data Type Summary | Conversion Keyword Summary | Byte Data Type | Integer Data Type | Long Data Type


Single Data Type

Single (single-precision floating-point) variables are stored as IEEE 32-bit (4-byte) floating-point numbers, ranging in value from -3.402823E38 to -1.401298E-45 for negative values and from 1.401298E-45 to 3.402823E38 for positive values. Single precision numbers store an approximation of a real number. Any other numeric type can be implicitly converted to the Single Data type without error even though for the decimal type, this conversion result in a loss of precision.

Note The Single data type can be converted to the Double or Decimal data type, without encountering an OverflowException error.

The equivalent NGWS runtime data type is System.Single.

See Also

Conversion Keyword Summary | Data Type Summary | Double Data Type | Type Conversion Functions | Using Data Types Efficiently


String Data Type

A string can contain up to approximately 2 billion (2^31) characters.

The codes for String characters range from 0–255. The first 128 characters (0–127) of the character set correspond to the letters and symbols on a standard U.S. keyboard. These first 128 characters are the same as those defined by the Unicodecharacter set. The second 128 characters (128–255) represent special characters, such as letters in international alphabets, accents, currency symbols, and fractions.

The equivalent NGWS runtime data type is System.String.

See Also

Conversion Keyword Summary | Data Type Summary | String Function | Type Conversion Functions | Using Data Types Efficiently


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

User-Defined Data Type

[Topic intentionally blank - content coming in later builds]

See Also


Directives (Visual Basic for Applications)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Directives (Visual Basic Language Reference)

#Const Directive

#If...Then...#Else Directive


#Const Directive

Used to define conditional compiler constants for Visual Basic.

#Const constname = expression

Arguments

constname
Required. String; name of the constant Follows standard variable naming conventions.
expression
Required. Literal, other conditional compiler constant, or any combination that includes any or all arithmetic or logical operators except Is.

Remarks

Conditional compiler constants are always Private to the file in which they appear. You cannot create Public compiler constants using the #Const directive. Public compiler constants can only be created in the user interface.

Only conditional compiler constants and literals can be used in expression. Using a standard constant defined with Const will cause an error. Conversely, constants defined using the #Const keyword can only be used for conditional compilation. Constants can also be undefined, in which case they have a value of Nothing.

See Also

Example

#If...Then...#Else Directive | Compiler Constants | Const Statement | Understanding Conditional Compilation | Using Constants | Using If...Then...Else Statements


#Const Directive Example

This example uses the #Const directive to declare conditional compiler constants for use in #If...#Else...#End If constructs.

#Const DebugVersion = 1   ' Will evaluate true in #If block.


#If...Then...#Else Directive

Conditionally compiles selected blocks of Visual Basic code.

#If expression Then
   statements
[#ElseIf expression-n Then
   [elseifstatements]]
[#Else
   [elsestatements]]
#End If

Arguments

expression
Required. Any expression, consisting exclusively of one or more conditional compiler constants, literals, and operators, that evaluates to True or False.
statements
Required. Visual Basic program lines or compiler directives that are compiled if the associated expression is True.
expression-n
Optional. Any expression, consisting exclusively of one or more conditional compiler constants, literals, and operators, that evaluates to True or False.
elseifstatements
Optional. One or more program lines or compiler directives that are compiled if expression-n is True.
elsestatements
Optional. One or more program lines or compiler directives that are compiled if no previous expression or expression-n is True.

Remarks

On the surface, the behavior of the #If...Then...#Else directive appears the same as the If...Then...Else statement. However, the #If…Then…#Else directive evaluates what is compiled by the compiler, whereas the If…Then…Else statement evaluates conditions at run time.

Conditional compilation is typically used to compile the same program for different platforms. It is also used to prevent debugging code from appearing in an executable file. Code excluded during conditional compilation is completely omitted from the final executable file, so it has no effect on size or performance.

Regardless of the outcome of any evaluation, all expressions are evaluated using Option Compare Text. The Option Compare statement does not affect expressions in #If and #ElseIf statements.

Note No single-line form of the #If, #Else, #ElseIf, and #End If directives exists; that is, no other code can appear on the same line as any of the directives.

See Also

Example


#If...Then...#Else Example

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

#If...Then...#Else Directive Example

This example references conditional compiler constants in an #If...Then...#Else construct to determine whether to compile certain statements.

' If Mac evaluates as true, do the statements following the #If.
#If Mac Then
   '. Place exclusively Mac  statements here.
   '.
   '.
' Otherwise, if it is a 32-bit Windows program, do this:
#ElseIf Win32 Then
   '. Place exclusively 32-bit Windows statements here.
   '.
   '.
' Otherwise, if it is neither, do this:
#Else
   '. Place other platform statements here.
   '.
   '.
#End If


Functions (Visual Basic for Applications)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Functions (Visual Basic Language Reference)

Linked list of the subsections:

A-C Functions

D-G Functions

H-L Functions

M-P Functions

Q-Z Functions


A-C Functions

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

A-C Functions (Visual Basic Language Reference)

Abs Function

Array Function

Asc Function

Atn Function

CallByName Function

Choose Function

Chr Function

Command Function

Cos Function

CreateObject Function

CurDir Function

CVErr Function


Abs Function

Returns a value of the same type that is passed to it specifying the absolute value of a number.

Abs(number)

The required number argument can be any valid numeric expression. If number containsNothing, Nothing is returned; if it is an uninitialized variable, zero is returned.

Remarks

The absolute value of a number is its unsigned magnitude. For example, ABS(-1) and ABS(1) both return 1.

See Also

Example


Abs Function Example

This example uses the Abs function to compute the absolute value of a number.

Dim MyNumber
MyNumber = Abs(50.3)   ' Returns 50.3.
MyNumber = Abs(-50.3)   ' Returns 50.3.


Array Function

Returns an Object containing an array.

Array(arglist)

The required arglist argument is a comma-delimited list of values that are assigned to the elements of the array contained within the Object. If no arguments are specified, an array of zero length is created.

Remarks

The notation used to refer to an element of an array consists of the variable name followed by parentheses containing an index number indicating the desired element. In the following example, the first statement creates a variable named A as an Object. The second statement assigns an array to variable A. The last statement assigns the value contained in the second array element to another variable.

Dim A As Object
A = Array(10,20,30)
B = A(2)
Note An Object variable can contain an array of any type.. Although an Object containing an array is conceptually different from an array whose elements are of typeObject, the array elements are accessed in the same way.

See Also

Example

Dim Statement


Array Function Example

This example uses the Array function to return a Variant containing an array.

Dim MyWeek, MyDay
MyWeek = Array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
' Return values assume lower bound set to 1 (using Option Base
' statement).
MyDay = MyWeek(2)   ' MyDay contains "Tue".
MyDay = MyWeek(4)   ' MyDay contains "Thu".


Asc Function

Returns an Integer representing the character code corresponding to the first letter in a string.

Asc(string)

The required string argument is any valid string expression. If the string contains no characters, a run-time error occurs.

Remarks

The range for returns is 0 – 255 on non-DBCS systems, but –32768 – 32767 on DBCS systems.

Note The AscB function is used with byte data contained in a string. Instead of returning the character code for the first character, AscB returns the first byte. The AscW function returns the Unicode character code except on platforms where Unicode is not supported, in which case, the behavior is identical to the Asc function.

See Also

Example


Asc Function Example

This example uses the Asc function to return a character code corresponding to the first letter in the string.

Dim MyNumber
MyNumber = Asc("A")   ' Returns 65.
MyNumber = Asc("a")   ' Returns 97.
MyNumber = Asc("Apple")   ' Returns 65.


Atn Function

Returns a Double specifying the arctangent of a number.

Atn(number)

The required number argument is a Double or any valid numeric expression.

Remarks

The Atn function takes the ratio of two sides of a right triangle (number) and returns the corresponding angle in radians. The ratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle.

The range of the result is - pi/2 to pi/2 radians.

To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi.

Note Atn is the inverse trigonometric function of Tan, which takes an angle as its argument and returns the ratio of two sides of a right triangle. Do not confuse Atn with the cotangent, which is the simple inverse of a tangent (1/tangent).

See Also

Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Atn Function Example

This example uses the Atn function to calculate the value of pi.

Dim pi
pi = 4 * Atn(1)   ' Calculate the value of pi.


CallByName Function

Executes a method of an object, or sets or returns a property of an object.

CallByName(object, procname, calltype,[args()])

The CallByName function syntax has these named arguments:

Part | Description
object | Required; Object. The name of the object on which the function will be executed.
procname | Required; String. A string expression containing the name of a property or method of the object.
calltype | Required; Constant. A constant of type vbCallType representing the type of procedure being called.
args() | Optional: Array.

Remarks

The CallByName function is used to get or set a property, or invoke a method at run time using a string name.

In the following example, the first line uses CallByName to set the MousePointer property of a text box, the second line gets the value of the MousePointer property, and the third line invokes the Move method to move the text box:

CallByName (Text1, "MousePointer", vbLet, vbCrosshair)
Result = CallByName (Text1, "MousePointer", vbGet)
CallByName (Text1, "Move", vbMethod, 100, 100)

See Also

Example


CallByName Function Example

This example uses the CallByName function to invoke the Move method of a Command button.

The example also uses a form (Form1) with a button (Command1), and a label (Label1). When the form is loaded, the Caption property of the label is set to "Move", the name of the method to invoke. When you click the button, the CallByName function invokes the method to change the location of the button.

Option Explicit

Private Sub Form_Load()
   Label1.Caption = "Move"      ' Name of Move method.
End Sub

Private Sub Command1_Click()
   If Command1.Left <> 0 Then
      CallByName Command1, Label1.Caption, vbMethod, 0, 0
   Else
      CallByName Command1, Label1.Caption, vbMethod, 500, 500
   End If


Type Conversion Functions

Each function coerces an expression to a specific data type.

CBool(expression)
CByte(expression)
CChar(expression)
CDate(expression)
CDbl(expression)
CDec(expression)
CInt(expression)
CLng(expression)
CSng(expression)
CStr(expression)

The required expression argument is any string expression or numeric expression.

Return Types

The function name determines the return type as shown in the following:

Function | Return Type | Range for expression argument
CBool | Boolean | Any valid string or numeric expression.
CByte | Byte | 0 to 255.
CChar | Char | 0 to 65535. When expression is a string, only the first character is converted to a Char.
CDate | Date | Any valid date expression.
CDbl | Double | -1.79769313486231E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
CDec | Decimal | +/-79,228,162,514,264,337,593,543,950,335 for zero-scaled numbers, that is, numbers with no decimal places. For numbers with 28 decimal places, the range is +/-7.9228162514264337593543950335. The smallest possible non-zero number is 0.0000000000000000000000000001.
CInt | Integer | -2,147,483,648 to 2,147,483,647; fractions are rounded.
CLng | Long | -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807; fractions are rounded.
CSng | Single | -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.
CStr | String | Returns for CStr depend on the expression argument.

Remarks

If the expression passed to the function is outside the range of the data type being converted to, an error occurs.

In general, you can document your code using the data-type conversion functions to show that the result of some operation should be expressed as a particular data type rather than the default data type. For example, use CCur to force currency arithmetic in cases where single-precision, double-precision, or integer arithmetic normally would occur.

You should use the data-type conversion functions instead of Val to provide internationally aware conversions from one data type to another. For example, when you use CCur, different decimal separators, different thousand separators, and various currency options are properly recognized depending on the locale setting of your computer.

When the fractional part is exactly 0.5, Cint and CLng always round it to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2. Cint, CLngdiffer from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. Also, Fix and Int always return a value of the same type as is passed in.

Use the IsDate function to determine if date can be converted to a date or time. CDate recognizes date literals and time literals as well as some numbers that fall within the range of acceptable dates. When converting a number to a date, the whole number portion is converted to a date. Any fractional part of the number is converted to a time of day, starting at midnight.

CDate recognizes date formats according to the locale setting of your system. The correct order of day, month, and year may not be determined if it is provided in a format other than one of the recognized date settings. In addition, a long date format is not recognized if it also contains the day-of-the-week string.

A CVDate function is also provided for compatibility with previous versions of Visual Basic. The syntax of the CVDate function is identical to the CDate function, however, CVDate returns a Variant whose subtype is Date instead of an actual Date type. Since there is now an intrinsic Date type, there is no further need for CVDate. The same effect can be achieved by converting an expression to a Date, and then assigning it to a Variant. This technique is consistent with the conversion of all other intrinsic types to their equivalent Variant subtypes.

Note The CDec function does not return a discrete data type; instead, it always returns a Variant whose value has been converted to a Decimal subtype.

See Also

Cbool Function Example | Cbyte Function Example | CChar Function Example | Date Function Example | CDbl Function Example | CDec Function Example | CInt Function Example | CLng Function Example | CSng Function Example | CStr Function Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CChr Function

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CChr Function Example

[Topic intentionally blank - content coming in later builds]


Choose Function

Selects and returns a value from a list of arguments.

Choose(index, choice-1[, choice-2, ... [, choice-n]])

Parameters

index
Required. Numeric expression or field that results in a value between 1 and the number of available choices.
choice
Required. Object expressioncontaining one of the possible choices.

Remarks

Choose returns a value from the list of choices based on the value of index. If index is 1, Choose returns the first choice in the list; if index is 2, it returns the second choice, and so on.

You can use Choose to look up a value in a list of possibilities. For example, if index evaluates to 3 and choice-1 = "one", choice-2 = "two", and choice-3 = "three", Choose returns "three". This capability is particularly useful if index represents the value in an option group.

Choose evaluates every choice in the list, even though it returns only one. For this reason, you should watch for undesirable side effects. For example, if you use the MsgBox function as part of an expression in all the choices, a message box will be displayed for each choice as it is evaluated, even though Choose returns the value of only one of them.

The Choose function throws an exception if index is less than 1 or greater than the number of choices listed.

If index is not a whole number, it is rounded to the nearest whole number before being evaluated.

See Also

Example


Choose Function Example

This example uses the Choose function to display a name in response to an index passed into the procedure in the Ind parameter.

Function GetChoice(Ind As Integer)
   GetChoice = Choose(Ind, "Speedy", "United", "Federal")
End Function


Chr Function

Returns a String containing the character associated with the specified character code.

Chr(charcode)

The required charcode argument is an Integer that identifies a character.

Remarks

Numbers from 0 – 31 are the same as standard, nonprintable ASCII codes. For example, Chr(10) returns a linefeed character. The normal range for charcode is 0 – 255. However, on DBCS systems, the actual range for charcode is -32768 to 65535.

See Also

Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

ChrB Function

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

ChrW Function

[Topic intentionally blank - content coming in later builds]


Chr Function Example

This example uses the Chr function to return the character associated with the specified character code.

Dim MyChar
MyChar = Chr(65)   ' Returns A.
MyChar = Chr(97)   ' Returns a.
MyChar = Chr(62)   ' Returns >.
MyChar = Chr(37)   ' Returns %.


Close Function

Concludes input/output (I/O) to a file opened using the Open statement.

Close (filenumberlist)

The optional filenumberlist argument can be one or more file numbers using the following syntax, where filenumber is any valid file number:

[filenumber] [,filenumber] . . .

Remarks

If you omit filenumberlist, all active files opened by the Open statement are closed.

When you close files that were opened for Output or Append, the final buffer of output is written to the operating system buffer for that file. All buffer space associated with the closed file is released.

When the Close function is executed, the association of a file with its file number ends.

See Also

Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CObj Function

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CObj Function Example

[Topic intentionally blank - content coming in later builds]


Command Function

Returns the argument portion of the command line used to launch Microsoft Visual Basic or an executable program developed with Visual Basic

Command

Remarks

When Visual Basic is launched from the command line, any portion of the command line that follows /cmd is passed to the program as the command-line argument. In the following example, cmdlineargs represents the argument information returned by the Command function.

VB /cmd cmdlineargs

For applications developed with Visual Basic and compiled to an .exe file, Command returns any arguments that appear after the name of the application on the command line. For example:

MyApp cmdlineargs

To find how command-line arguments can be changed in the user interface of the application you're using, search Help for "command-line arguments."

See Also

Example

Returning Strings from Functions


Command Function Example

This example uses the Command function to get the command line arguments in a function that returns them in a Variant containing an array.

Function GetCommandLine(Optional MaxArgs)
   'Declare variables.
   Dim C, CmdLine, CmdLnLen, InArg, I, NumArgs
   'See if MaxArgs was provided.
   If IsMissing(MaxArgs) Then MaxArgs = 10
   'Make array of the correct size.
   ReDim ArgArray(MaxArgs)
   NumArgs = 0: InArg = False
   'Get command line arguments.
   CmdLine = Command()
   CmdLnLen = Len(CmdLine)
   'Go thru command line one character
   'at a time.
   For I = 1 To CmdLnLen
      C = Mid(CmdLine, I, 1)
      'Test for space or tab.
      If (C <> " " And C <> vbTab) Then
         'Neither space nor tab.
         'Test if already in argument.
         If Not InArg Then
         'New argument begins.
         'Test for too many arguments.
            If NumArgs = MaxArgs Then Exit For
            NumArgs = NumArgs + 1
            InArg = True
         End If
         'Concatenate character to current argument.
         ArgArray(NumArgs) = ArgArray(NumArgs) & C
      Else
         'Found a space or tab.
         'Set InArg flag to False.
         InArg = False
      End If
   Next I
   'Resize array just enough to hold arguments.
   ReDim Preserve ArgArray(NumArgs)
   'Return Array in Function name.
   GetCommandLine = ArgArray()
End Function


Conversion Functions

Asc Function

CBool Function

CByte Function

CChar Function

CDate Function

CDec Function

CDbl Function

Chr Function

CInt Function

CLng Function

CSng Function

CStr Function

CVErr Function

Format Function

Hex Function

Oct Function

Str Function

Val Function

See Also

Type Conversion Functions


Cos Function

Returns a Double specifying the cosine of an angle.

Cos(number)

The required number argument is a Double or any valid numeric expression that expresses an angle in radians.

Remarks

The Cos function takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side adjacent to the angle divided by the length of the hypotenuse.

The result lies in the range -1 to 1.

To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi.

See Also

Example


Cos Function Example

This example uses the Cos function to return the cosine of an angle.

Dim MyAngle, MySecant
MyAngle = 1.3   ' Define angle in radians.
MySecant = 1 / Cos(MyAngle)   ' Calculate secant.


CreateObject Function

Creates and returns a reference to an ActiveX objectdefActiveXObject@veendf98.chm. CreateObject cannot be used to create instances of classes in Visual Basic unless those classes are explicitly exposed as ActiveX objects.

CreateObject(class,[servername])

The CreateObject function syntax has these parts:

Part | Description
class | Required; String. The application name and class of the object to create.
servername | Optional; String. The name of the network server where the object will be created. If servername is an empty string (""), the local machine is used.

The class argument uses the syntax appname.objecttype and has these parts:

Part | Description
appname | Required; String. The name of the application providing the object.
objecttype | Required; String. The type or class of object to create.

Remarks

To create an ActiveX object, assign the object returned by CreateObject to an object variable:

' Declare an object variable to hold the object
' reference. Dim as Object causes late binding.
Dim ExcelSheet As Object
ExcelSheet = CreateObject("Excel.Sheet")

This code starts the application creating the object, in this case, a Microsoft Excel spreadsheet. Once an object is created, you reference it in code using the object variable you defined. In the following example, you access properties and methods of the new object using the object variable, ExcelSheet, and other Microsoft Excel objects, including the Application object and the Cells collection.

' Make Excel visible through the Application object.
ExcelSheet.Application.Visible = True
' Place some text in the first cell of the sheet.
ExcelSheet.Application.Cells(1, 1).Value = "This is column A, row 1"
' Save the sheet to C:\test.xls directory.
ExcelSheet.SaveAs "C:\TEST.XLS"
' Close Excel with the Quit method on the Application object.
ExcelSheet.Application.Quit
' Release the object variable.
ExcelSheet = Nothing

Declaring an object variable with the As Object clause creates a variable that can contain a reference to any type of object. However, access to the object through that variable is late bound; that is, the binding occurs when your program is run. To create an object variable that results in early binding, that is, binding when the program is compiled, declare the object variable with a specific class ID. For example, you can declare and create the following Microsoft Excel references:

Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.WorkSheet
xlApp = CreateObject("Excel.Application")
xlBook = xlApp.Workbooks.Add
xlSheet = xlBook.Worksheets(1)

The reference through an early-bound variable can give better performance, but can only contain a reference to the class specified in the declaration.

You can pass an object returned by the CreateObject function to a function expecting an object as an argument. For example, the following code creates and passes a reference to a Excel.Application object:

Call MySub (CreateObject("Excel.Application"))

You can create an object on a remote networked computer by passing the name of the computer to the servername argument of CreateObject. That name is the same as the Machine Name portion of a share name: for a share named "\\MyServer\Public," servername is "MyServer."

Note Refer to COM documentation (see Microsoft Developer Network) for additional information on making an application visible on a remote networked computer. You may have to add a registry key for your application.

The following code returns the version number of an instance of Excel running on a remote computer named MyServer:

Dim xlApp As Object
xlApp = CreateObject("Excel.Application", "MyServer")
Debug.Print xlApp.Version

If the remote server doesn’t exist or is unavailable, a run-time error occurs.

Note Use CreateObject when there is no current instance of the object. If an instance of the object is already running, a new instance is started, and an object of the specified type is created. To use the current instance, or to start the application and have it load a file, use the GetObject function.
If an object has registered itself as a single-instance object, only one instance of the object is created, no matter how many times CreateObject is executed.

See Also

Example


CreateObject Function Example

This example uses the CreateObject function to set a reference (xlApp) to Microsoft Excel. It uses the reference to access the Visible property of Microsoft Excel, and then uses the Microsoft Excel Quit method to close it. Finally, the reference itself is released.

Dim xlApp As Object   ' Declare variable to hold the reference.

Set xlApp = CreateObject("excel.application")
   ' You may have to set Visible property to True
   ' if you want to see the application.
xlApp.Visible = True
   ' Use xlApp to access Microsoft Excel's
   ' other objects.
xlApp.Quit   ' When you finish, use the Quit method to close
Set xlApp = Nothing   ' the application, then release the reference.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CShort Function

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CShort Function Example

[Topic intentionally blank - content coming in later builds]


CurDir Function

Returns a String representing the current path.

CurDir(drive)

The optional drive argument is a string expression that specifies an existing drive. If no drive is specified, or if drive is a zero-length string (""), CurDir returns the path for the current drive.

See Also

Example


CurDir Function Example

This example uses the CurDir function to return the current path.

' Assume current path on C drive is "C:\WINDOWS\SYSTEM"
' Assume current path on D drive is "D:\EXCEL".
' Assume C is the current drive.
Dim MyPath
MyPath = CurDir   ' Returns "C:\WINDOWS\SYSTEM".
MyPath = CurDir("C")   ' Returns "C:\WINDOWS\SYSTEM".
MyPath = CurDir("D")   ' Returns "D:\EXCEL".


CType Function

Returns the result of explicitly casting an expression to a specified date type, object, class, or interface.

CType(expression, typename)

Arguments

expression
Any valid expression.
typename
Any expression that is legal within an As clause in a Dim statement, that is the name of any data type, object, class or interface.

See Also

Example


CVErr Function

Returns a Variant of subtype Error containing an error number specified by the user.

CVErr(errornumber)

The required errornumber argument is any valid error number.

Remarks

Use the CVErr function to create user-defined errors in user-created procedures. For example, if you create a function that accepts several arguments and normally returns a string, you can have your function evaluate the input arguments to ensure they are within acceptable range. If they are not, it is likely your function will not return what you expect. In this event, CVErr allows you to return an error number that tells you what action to take.

Note that implicit conversion of an Error is not allowed. For example, you can't directly assign the return value of CVErr to a variable that is not a Variant. However, you can perform an explicit conversion (using CInt, CDbl, and so on) of the value returned by CVErr and assign that to a variable of the appropriate data type.

See Also

Example


CVErr Function Example

This example uses the CVErr function to return a Variant whose VarType is vbError (10). The user-defined function CalculateDouble returns an error if the argument passed to it isn't a number. You can use CVErr to return user-defined errors from user-defined procedures or to defer handling of a run-time error. Use the IsError function to test if the value represents an error.

' Call CalculateDouble with an error-producing argument.
Sub Test()
   Debug.Print CalculateDouble("345.45robert")
End Sub
' Define CalculateDouble Function procedure.
Function CalculateDouble(Number)
   If IsNumeric(Number) Then
      CalculateDouble = Number * 2   ' Return result.
   Else
      CalculateDouble = CVErr(2001)   ' Return a user-defined error
   End If   ' number.
End Function


D-G Functions

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

D-G Functions (Visual Basic Language Reference)

Date Function

DateAdd Function

DateDiff Function

DatePart Function

DateSerial Function

DateValue Function

Day Function

DDB Function

Dir Function

DoEvents Function

Environ Function

EOF Function

Exp Function

FileAttr Function

FileDateTime Function

FileLen Function

Filter Function

Fix Function

Format Function

FormatCurrency Function

FormatDateTime Function

FormatNumber Function

FormatPercent Function

FreeFile Function

FV Function

GetAllSettings Function

GetAttr Function

GetObject Function

GetSetting Function


DateAdd Function

Returns a DateTime containing a date to which a specified time interval has been added.

DateAdd(dateinterval, number, datetime)

Arguments

dateinterval
Required. String expression that is the interval of time you want to add.
number
Required. Numeric expression that is the number of intervals you want to add. It can be positive (to get dates in the future) or negative (to get dates in the past).
datetime
Required. DateTime or literal representing date to which the interval is added.

Settings

The dateinterval argument has these settings:

Setting | Description
yyyy | Year
q | Quarter
m | Month
y | Day of year
d | Day
w | Weekday
ww | Week
h | Hour
n | Minute
s | Second

Remarks

You can use the DateAdd function to add or subtract a specified time interval from a date. For example, you can use DateAdd to calculate a date 30 days from today or a time 45 minutes from now.

To add days to datetime, you can use Day of Year ("y"), Day ("d"), or Weekday ("w").

The DateAdd function won't return an invalid date. The following example adds one month to January 31:

DateAdd("m", 1, "31-Jan-95")

In this case, DateAdd returns 28-Feb-95, not 31-Feb-95. If datetime is 31-Jan-96, it returns 29-Feb-96 because 1996 is a leap year.

If the calculated date would precede the year 100 (that is, you subtract more years than are in datetime), an error occurs.

If number isn't a Long value, it is rounded to the nearest whole number before being evaluated.

Note The format of the return value for DateAdd is determined by Control Panel settings, not by the format that is passed in datetime argument.
Note For datetime, if the Calendar property setting is Gregorian, the supplied date must be Gregorian. If the calendar is Hijri, the supplied date must be Hijri. If month values are names, the name must be consistent with the current Calendar property setting. To minimize the possibility of month names conflicting with the current Calendar property setting, enter numeric month values (Short Date format).

See Also

Example


DateAdd Function Example

This example takes a date and, using the DateAdd function, displays a corresponding date a specified number of months in the future.

Dim FirstDate As Date   ' Declare variables.
Dim IntervalType As String
Dim Number As Integer
Dim Msg
IntervalType = "m"   ' "m" specifies months as interval.
FirstDate = InputBox("Enter a date")
Number = InputBox("Enter number of months to add")
Msg = "New date: " & DateAdd(IntervalType, Number, FirstDate)
MsgBox Msg


DateDiff Function

Returns a Double specifying the number of time intervals between two specified dates.

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

Arguments

dateinterval
Required. String expression that is the interval of time you use to calculate the difference between date1 and date2.
date1, date2
Required; DateTime. 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 dateinterval argument has these settings:

Setting | Description
yyyy | Year
q | Quarter
m | Month
y | Day of year
d | Day
w | Weekday
ww | Week
h | Hour
n | Minute
s | Second

The firstdayofweek argument has these settings:

Constant | Value | Description
System | 0 | Use the day of the week specified in your system settings for the first day of the week.
Sunday | 1 | Sunday (default)
Monday | 2 | Monday
Tuesday | 3 | Tuesday
Wednesday | 4 | Wednesday
Thursday | 5 | Thursday
Friday | 6 | Friday
Saturday | 7 | Saturday

Constant | Value | Description
UseSystemDayOfWeek | 0 | Use the day of the week specified in your system settings for the first day of the week.
FirstJan1 | 1 | Start with week in which January 1 occurs (default).
FirstFourDays | 2 | Start with the first week that has at least four days in the new year.
FirstFullWeek | 3 | Start with first full week of the 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 dateinterval 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 dateinterval 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.

Note For date1 and date2, if the Calendar property setting is Gregorian, the supplied date must be Gregorian. If the calendar is Hijri, the supplied date must be Hijri.

See Also

Example


DateDiff Function Example

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

Dim TheDate As Date   ' Declare variables.
Dim Msg
TheDate = InputBox("Enter a date")
Msg = "Days from today: " & DateDiff("d", Now, TheDate)
MsgBox Msg


DatePart Function

Returns an Integer containing the specified part of a given date.

DatePart(dateinterval, date[,firstdayofweek[, firstweekofyear]])

The DatePart function syntax has these named arguments:

Arguments

dateinterval
Required. String expression that is the interval of time you want to return.
date
Required. DateTime value that you want to evaluate.
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 dateinterval argument has these settings:

Setting | Description
yyyy | Year
q | Quarter
m | Month
y | Day of year
d | Day
w | Weekday
ww | Week
h | Hour
n | Minute
s | Second

The firstdayofweek argument has these settings:

Constant | Value | Description
UseSystemDayofWeek | 0 | Use the day of the week specified in your system settings for the first day of the week
Sunday | 1 | Sunday (default)
Monday | 2 | Monday
Tuesday | 3 | Tuesday
Wednesday | 4 | Wednesday
Thursday | 5 | Thursday
Friday | 6 | Friday
Saturday | 7 | Saturday

The firstweekofyear argument has these settings:

Constant | Value | Description
UseSystemDayOfWeek | 0 | Use the day of the week specified in your system settings for the first day of the week
FirstJan1 | 1 | Start with week in which January 1 occurs (default).
FirstFourDays | 2 | Start with the first week that has at least four days in the new year.
FirstFullWeek | 3 | Start with first full week of the year.

Remarks

You can use the DatePart function to evaluate a date and return a specific interval of time. For example, you might use DatePart to calculate the day of the week or the current hour.

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

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

Note For date, if the Calendar property setting is Gregorian, the supplied date must be Gregorian. If the calendar is Hijri, the supplied date must be Hijri.
The returned date part is in the time period units of the current Arabic calendar. For example, if the current calendar is Hijri and the date part to be returned is the year, the year value is a Hijri year.

See Also

Example


DatePart Function Example

This example takes a date and, using the DatePart function, displays the quarter of the year in which it occurs.

Dim TheDate As Date   ' Declare variables.
Dim Msg
TheDate = InputBox("Enter a date:")
Msg = "Quarter: " & DatePart("q", TheDate)
MsgBox Msg


DateSerial Function

Returns an DateTime for a specified year, month, and day.

DateSerial(year, month, day)

Arguments

year
Required; Integer. Number between 100 and 9999, inclusive, or a numeric expression.
month
Required; Integer. Any numeric expression.
day
Required; Integer. Any numeric expression.

Remarks

To specify a date, such as December 31, 1991, the range of numbers for each DateSerial argument should be in the accepted range for the unit; that is, 1–31 for days and 1–12 for months. However, you can also specify relative dates for each argument using any numeric expression that represents some number of days, months, or years before or after a certain date.

The following example uses numeric expressions instead of absolute date numbers. Here the DateSerial function returns a date that is the day before the first day (1 - 1), two months before August (8 - 2), 10 years before 1990 (1990 - 10); in other words, May 31, 1980.

DateSerial(1990 - 10, 8 - 2, 1 - 1)

Under Windows 98 or Windows 2000, two digit years for the year argument are interpreted based on user-defined machine settings. The default settings are that values between 0 and 29, inclusive, are interpreted as the years 2000–2029. The default values between 30 and 99 are interpreted as the years 1930–1999. For all other year arguments, use a four-digit year (for example, 1800).

Earlier versions of Windows interpret two-digit years based on the defaults described above. To be sure the function returns the proper value, use a four-digit year.

When any argument exceeds the accepted range for that argument, it increments to the next larger unit as appropriate. For example, if you specify 35 days, it is evaluated as one month and some number of days, depending on where in the year it is applied. If any single argument is outside the range-2,147,483,648 to 2,147,483,647, an error occurs. If the date specified by the three arguments falls outside the acceptable range of dates, an error occurs.

Note For year, month, and day, if the Calendar property setting is Gregorian, the supplied value is assumed to be Gregorian. If the Calendar property setting is Hijri, the supplied value is assumed to be Hijri.
The returned date part is in the time period units of the current Visual Basic calendar. For example, if the current calendar is Hijri and the date part to be returned is the year, the year value is a Hijri year. For the argument year, values between 0 and 99, inclusive, are interpreted as the years 1400-1499. For all other year values, use the complete four-digit year (for example, 1520).

See Also

Example

Calendar Property | Date Function | Date Statement | DateValue Function | Day Function | Month Function | Now Function | TimeSerial Function | TimeValue Function | Weekday Function | Year Function


DateSerial Function Example

This example uses the DateSerial function to return the date for the specified year, month, and day.

Dim MyDate
' MyDate contains the date for February 12, 1969.
MyDate = DateSerial(1969, 2, 12)   ' Return a date.


DateValue Function

Returns a DateTime.

DateValue(datetime)

The required datetime argument is normally a string expression representing a date from January 1, 100 through December 31, 9999. However, datetime can also be any expression that can represent a date, a time, or both a date and a time, in that range.

Remarks

If datetime is a string that includes only numbers separated by valid date separators, DateValue recognizes the order for month, day, and year according to the Short Date format you specified for your system. DateValue also recognizes unambiguous dates that contain month names, either in long or abbreviated form. For example, in addition to recognizing 12/30/1991 and 12/30/91, DateValue also recognizes December 30, 1991 and Dec 30, 1991.

If the year part of datetime is omitted, DateValue uses the current year from your computer's system date.

If the datetime argument includes time information, DateValue doesn't return it. However, if datetime includes invalid time information (such as "89:98"), an error occurs.

Note For datetime, if the Calendar property setting is Gregorian, the supplied date must be Gregorian. If the calendar is Hijri, the supplied date must be Hijri. If the supplied date is Hijri, the argument datetime is a String representing a date from 1/1/100 (Gregorian Aug 2, 718) through 4/3/9666 (Gregorian Dec 31, 9999).

See Also

Example

Calendar Property | Date Function | Date Statement | DateSerial Function | Day Function | Month Function | Now Function | TimeSerial Function | TimeValue Function | Weekday Function | Year Function


DateValue Function Example

This example uses the DateValue function to convert a string to a date. You can also use date literals to directly assign a date to a Variant or Date variable, for example, MyDate = #2/12/69#.

Dim MyDate
MyDate = DateValue("February 12, 1969")   ' Return a date.


Day Function

Returns an Integer specifying a whole number between 1 and 31, inclusive, representing the day of the month.

Day(datetime)

The required datetime argument is anyObject, numeric expression, string expression, or any combination, that can represent a date.

Note If the Calendar property setting is Gregorian, the returned integer represents the Gregorian day of the month for the date argument. If the calendar is Hijri, the returned integer represents the Hijri day of the month for the date argument.

See Also

Example

Calendar Property | Date Function | Date Statement | Hour Function | Minute Function | Month Function | Now Function | Second Function | Weekday Function | Year Function


Day Function Example

This example uses the Day function to obtain the day of the month from a specified date. In the development environment, the date literal is displayed in short format using the locale settings of your code.

Dim MyDate, MyDay
MyDate = #February 12, 1969#   ' Assign a date.
MyDay = Day(MyDate)   ' MyDay contains 12.


DDB Function

Returns a Double specifying the depreciation of an asset for a specific time period using the double-declining balance method or some other method you specify.

DDB(cost, salvage, life, period[, factor])

Arguments

cost
Required. Double specifying initial cost of the asset.
salvage
Required. Double specifying value of the asset at the end of its useful life.
life
Required. Double specifying length of useful life of the asset.
period
Required. Double specifying period for which asset depreciation is calculated.
factor
Optional. Objectspecifying rate at which the balance declines. If omitted, 2 (double-declining method) is assumed.

Remarks

The double-declining balance method computes depreciation at an accelerated rate. Depreciation is highest in the first period and decreases in successive periods.

The life and period arguments must be expressed in the same units. For example, if life is given in months, period must also be given in months. All arguments must be positive numbers.

The DDB function uses the following formula to calculate depreciation for a given period:

Depreciation / period = ((cost – salvage) * factor) / life

See Also

Example

FV Function | IPmt Function | IRR Function | MIRR Function | NPer Function | NPV Function | Pmt Function | PPmt Function | PV Function | Rate Function | SLN Function | SYD Function


DDB Function Example

This example uses the DDB function to return the depreciation of an asset for a specified period given the initial cost (InitCost), the salvage value at the end of the asset's useful life (SalvageVal), the total life of the asset in years (LifeTime), and the period in years for which the depreciation is calculated (Depr).

Dim Fmt, InitCost, SalvageVal, MonthLife, LifeTime, DepYear, Depr
Const YRMOS = 12   ' Number of months in a year.
Fmt = "###,##0.00"
InitCost = InputBox("What's the initial cost of the asset?")
SalvageVal = InputBox("Enter the asset's value at end of its life.")
MonthLife = InputBox("What's the asset's useful life in months?")
Do While MonthLife < YRMOS   ' Ensure period is >= 1 year.
   MsgBox "Asset life must be a year or more."
   MonthLife = InputBox("What's the asset's useful life in months?")
Loop
LifeTime = MonthLife / YRMOS   ' Convert months to years.
If LifeTime <> Int(MonthLife / YRMOS) Then
   LifeTime = Int(LifeTime + 1)   ' Round up to nearest year.
End If
DepYear = CInt(InputBox("Enter year for depreciation calculation."))
Do While DepYear < 1 Or DepYear > LifeTime
   MsgBox "You must enter at least 1 but not more than " & LifeTime
   DepYear = InputBox("Enter year for depreciation calculation.")
Loop
Depr = DDB(InitCost, SalvageVal, LifeTime, DepYear)
MsgBox "The depreciation for year " & DepYear & " is " & _
Format(Depr, Fmt) & "."


Derived Math Functions

The following is a list of nonintrinsic math functions that can be derived from the intrinsic math functions:

Function | Derived equivalents
Secant | Sec(X) = 1 / Cos(X)
Cosecant | Cosec(X) = 1 / Sin(X)
Cotangent | Cotan(X) = 1 / Tan(X)
Inverse Sine | Arcsin(X) = Atn(X / Sqr(-X * X + 1))
Inverse Cosine | Arccos(X) = Atn(-X / Sqr(-X * X + 1)) + 2 * Atn(1)
Inverse Secant | Arcsec(X) = 2 * Atn(1) – Atn(Sgn(X) / Sqr(X * X – 1))
Inverse Cosecant | Arccosec(X) = Atn(Sgn(X) / Sqr(X * X – 1))
Inverse Cotangent | Arccotan(X) = 2 * Atn(1) - Atn(X)
Hyperbolic Sine | HSin(X) = (Exp(X) – Exp(-X)) / 2
Hyperbolic Cosine | HCos(X) = (Exp(X) + Exp(-X)) / 2
Hyperbolic Tangent | HTan(X) = (Exp(X) – Exp(-X)) / (Exp(X) + Exp(-X))
Hyperbolic Secant | HSec(X) = 2 / (Exp(X) + Exp(-X))
Hyperbolic Cosecant | HCosec(X) = 2 / (Exp(X) – Exp(-X))
Hyperbolic Cotangent | HCotan(X) = (Exp(X) + Exp(-X)) / (Exp(X) – Exp(-X))
Inverse Hyperbolic Sine | HArcsin(X) = Log(X + Sqr(X * X + 1))
Inverse Hyperbolic Cosine | HArccos(X) = Log(X + Sqr(X * X – 1))
Inverse Hyperbolic Tangent | HArctan(X) = Log((1 + X) / (1 – X)) / 2
Inverse Hyperbolic Secant | HArcsec(X) = Log((Sqr(-X * X + 1) + 1) / X)
Inverse Hyperbolic Cosecant | HArccosec(X) = Log((Sgn(X) * Sqr(X * X + 1) + 1) / X)
Inverse Hyperbolic Cotangent | HArccotan(X) = Log((X + 1) / (X – 1)) / 2
Logarithm to base N | LogN(X) = Log(X) / Log(N)

See Also

Atn Function | Cos Function | Exp Function | Log Function | Sin Function | Sqr Function | Tan Function


Dir Function

Returns a String representing the name of a file, directory, or folder that matches a specified pattern or file attribute, or the volume label of a drive.

Dir (pathname[, fileattributes])

Arguments

pathname
Optional. String expression that specifies a file name — may include directory or folder, and drive. A zero-length string ("") is returned if pathname is not found.
attributes
Optional. Constant or numeric expression, whose sum specifies file attributes. If omitted, returns files that match pathname, but have no attributes.

Settings

The attributes argument settings are:

Constant | Value | Description
Normal | 0 | (Default) Specifies files with no attributes.
ReadOnly | 1 | Specifies read-only files in addition to files with no attributes.
Hidden | 2 | Specifies hidden files in addition to files with no attributes.
System | 4 | Specifies system files in addition to files with no attributes.
Volume | 8 | Specifies volume label if any other attributed is specified; vbVolume is ignored.
Directory | 16 | Specifies directories or folders in addition to files with no attributes.

Note These constants are specified by Visual Basic for Applications and can be used anywhere in your code in place of the actual values.

Remarks

Dir supports the use of multiple character (*) and single character (?) wildcards to specify multiple files.

See Also

Example


Dir Function Example

This example uses the Dir function to check if certain files and directories exist.

Dim MyFile, MyPath, MyName
' Returns "WIN.INI" if it exists.
MyFile = Dir("C:\WINDOWS\WIN.INI")

' Returns filename with specified extension. If more than one *.ini
' file exists, the first file found is returned.
MyFile = Dir("C:\WINDOWS\*.INI")

' Call Dir again without arguments to return the next *.INI file in the
' same directory.
MyFile = Dir

' Return first *.TXT file with a set hidden attribute.
MyFile = Dir("*.TXT", vbHidden)

' Display the names in C:\ that represent directories.
MyPath = "c:\"   ' Set the path.
MyName = Dir(MyPath, vbDirectory)   ' Retrieve the first entry.
Do While MyName <> ""   ' Start the loop.
   ' Ignore the current directory and the encompassing directory.
   If MyName <> "." And MyName <> ".." Then
      ' Use bitwise comparison to make sure MyName is a directory.
      If (GetAttr(MyPath & MyName) And vbDirectory) = vbDirectory Then
         Debug.Print MyName   ' Display entry only if it
      End If   ' it represents a directory.
   End If
   MyName = Dir   ' Get next entry.
Loop


EOF Function

Returns a Boolean value True when the end of a file opened for Random or sequential Input has been reached.

EOF(filenumber)

The required filenumber argument is an Integer containing any valid file number.

Remarks

Use EOF to avoid the error generated by attempting to get input past the end of a file.

The EOF function returns False until the end of the file has been reached. With files opened for Random or Binary access, EOF returns False until the last executed Get statement is unable to read an entire record.

With files opened for Binary access, an attempt to read through the file using the Input function until EOF returns True generates an error. Use the LOF and Loc functions instead of EOF when reading binary files with Input, or use Get when using the EOF function. With files opened for Output, EOF always returns True.

See Also

Example


EOF Function Example

This example uses the EOF function to detect the end of a file. This example assumes that MYFILE is a text file with a few lines of text.

Dim InputData
Open "MYFILE" For Input As #1   ' Open file for input.
Do While Not EOF(1)   ' Check for end of file.
   Line Input #1, InputData   ' Read line of data.
   Debug.Print InputData   ' Print to the Immediate window.
Loop
Close #1   ' Close file.


Error Function

Returns the error message that corresponds to a given error number.

Error[(errornumber)]

Argument

errornumber
Optional. Can be any valid error number.

Remarks

Examine the property settings of the Err object to identify the most recent run-time error. The return value of the Error function corresponds to the Description property of the Err object. If errornumber is a valid error number but is not defined, Error returns the string "Application-defined or object-defined error." If errornumber is not valid, an error occurs. If errornumber is omitted, the message corresponding to the most recent run-time error is returned. If no run-time error has occurred, or errornumber is 0, Error returns a zero-length string ("").

See Also

Example


Error Function Example

This example uses the Error function to print error messages that correspond to the specified error numbers.

Dim ErrorNumber
For ErrorNumber = 61 To 64   ' Loop through values 61 - 64.
   Debug.Print Error(ErrorNumber)   ' Print error to Immediate window.
Next ErrorNumber


Exp Function

Returns a Double specifying e (the base of natural logarithms) raised to a power.

Exp(number)

The required number argument is a Double or any valid numeric expression.

Remarks

If the value of number exceeds 709.782712893, an error occurs. The constant e is approximately 2.718282.

Note The Exp function complements the action of the Log function and is sometimes referred to as the antilogarithm.

See Also

Example


Exp Function Example

This example uses the Exp function to return e raised to a power.

Dim MyAngle, MyHSin
' Define angle in radians.
MyAngle = 1.3
' Calculate hyperbolic sine.
MyHSin = (Exp(MyAngle) - Exp(-1 * MyAngle)) / 2


FileAttr Function

Returns a Long representing the file mode for files opened using the Open statement.

FileAttr(filenumber)

Arguments

filenumber
Required; Integer. Any valid file number.

Return Values

When the returntype argument is 1, the following return values indicate the file access mode:

Question: So, are we using the filenumber instead of the returntype as the argument here?

Mode | Value
Input | 1
Output | 2
Random | 4
Append | 8
Binary | 32

See Also

Example


FileAttr Function Example

This example uses the FileAttr function to return the file mode and file handle of an open file. The file handle is returned only on 16-bit systems; on 32-bit systems, passing 2 as a second argument generates an error.

Dim FileNum, Mode, Handle
FileNum = 1   ' Assign file number.
Open "TESTFILE" For Append As FileNum   ' Open file.
Mode = FileAttr(FileNum, 1)   ' Returns 8 (Append file mode).
Handle = FileAttr(FileNum, 2)   ' Returns file handle.
Close FileNum   ' Close file.


FileCopy Function

Copies a file.

FileCopy (source, destination)

The FileCopy function syntax has these named arguments:

Arguments

source
Required. String expression that specifies the name of the file to be copied. The source may include directory or folder, and drive.
destination
Required. String expression that specifies the target file name. The destination may include directory or folder, and drive.

Remarks

If you try to use the FileCopy function on a currently open file, an error occurs.

See Also

Example

Kill Statement


FileDateTime Function

Returns a DateTime that indicates the date and time when a file was created or last modified.

FileDateTime(pathname)

The required pathname argument is a string expression that specifies a file name. The pathname may include the directory or folder, and the drive.

See Also

Example


FileDateTime Function Example

This example uses the FileDateTime function to determine the date and time a file was created or last modified. The format of the date and time displayed is based on the locale settings of your system.

Dim MyStamp
' Assume TESTFILE was last modified on February 12, 1993 at 4:35:47 PM.
' Assume English/U.S. locale settings.
MyStamp = FileDateTime("TESTFILE")   ' Returns "2/12/93 4:35:47 PM".


FileLen Function

Returns a Long specifying the length of a file in bytes.

FileLen(pathname)

The required pathname argument is a string expression that specifies a file. The pathname may include the directory or folder, and the drive.

Remarks

If the specified file is open when the FileLen function is called, the value returned represents the size of the file immediately before it was opened.

Note To obtain the length of an open file, use the LOF function.

See Also

Example


FileLen Function Example

This example uses the FileLen function to return the length of a file in bytes. For purposes of this example, assume that TESTFILE is a file containing some data.

Dim MySize
MySize = FileLen("TESTFILE")   ' Returns file length (bytes).


Filter Function

Returns a zero-based array containing subset of a string array based on a specified filter criteria.

Filter(sourcearray, match[, include[, compare]])

Arguments

sourcearray
Required. One-dimensional array of strings to be searched.
match
Required. String to search for.
include
Optional. Boolean value indicating whether to return substrings that include or exclude match. If include is True, Filter returns the subset of the array that contains match as a substring. If include is False, Filter returns the subset of the array that does not contain match as a substring.
compare
Optional. Numeric value indicating the kind of string comparison to use. See Settings section for values.

Settings

The compare argument can have the following values:

Constant | Value | Description
BinaryCompare | 0 | Performs a binary comparison.
TextCompare | 1 | Performs a textual comparison.

Remarks

If no matches of match are found within sourcearray, Filter returns an empty array. An error occurs if sourcearray is set to Nothing or is not a one-dimensional array.

The array returned by the Filter function contains only enough elements to contain the number of matched items.

See Also

Replace Function


Int, Fix Functions

Returns the integer portion of a number.

Int(number)
Fix(number)

The required number argument is a Double or any valid numeric expression. If number containsNothing, Nothing is returned.

Remarks

Both Int and Fix remove the fractional part of number and return the resulting integer value.

The difference between Int and Fix is that if number is negative, Int returns the first negative integer less than or equal to number, whereas Fix returns the first negative integer greater than or equal to number. For example, Int converts -8.4 to -9, and Fix converts -8.4 to -8.

Fix(number) is equivalent to:

Sgn(number) * Int(Abs(number))

See Also

Example


Int Function, Fix Function Example

This example illustrates how the Int and Fix functions return integer portions of numbers. In the case of a negative number argument, the Int function returns the first negative integer less than or equal to the number; the Fix function returns the first negative integer greater than or equal to the number.

Dim MyNumber
MyNumber = Int(99.8)   ' Returns 99.
MyNumber = Fix(99.2)   ' Returns 99.

MyNumber = Int(-99.8)   ' Returns -100.
MyNumber = Fix(-99.8)   ' Returns -99.

MyNumber = Int(-99.2)   ' Returns -100.
MyNumber = Fix(-99.2)   ' Returns -99.


Format Function

Returns aString containing an expression formatted according to instructions contained in a format expression.

Format(expression[, style[, firstdayofweek[, firstweekofyear]]])

Arguments

expression
Required. Any valid expression.
style
Optional. A valid named or user-defined format expression.
firstdayofweek
Optional. A constant that specifies the first day of the week.
firstweekofyear
Optional. A constant that specifies the first week of the year.

Settings

The firstdayofweek argument has these settings:

Constant | Value | Description
System | 0 | Use the day of the week specified in your system settings for the first day of the week.
Sunday | 1 | Sunday (default)
Monday | 2 | Monday
Tuesday | 3 | Tuesday
Wednesday | 4 | Wednesday
Thursday | 5 | Thursday
Friday | 6 | Friday
Saturday | 7 | Saturday

The firstweekofyear argument has these settings:

Constant | Value | Description
System | 0 | Use the day of the week specified in your system settings for the first day of the week.
Jan1 | 1 | Start with week in which January 1 occurs (default).
FirstFourDays | 2 | Start with the first week that has at least four days in the year.
FirstFullWeek | 3 | Start with the first full week of the year.

Remarks

To Format | Do This
Numbers | Use predefined named numeric formats or create user-defined numeric formats.
Dates and times | Use predefined named date/time formats or create user-defined date/time formats.
Date and time serial numbers | Use date and time formats or numeric formats.
Strings | Create your own user-defined string formats.

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

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

See Also

Example

Different Formats for Different Numeric Values (Format Function) | Different Formats for Different String Values (Format Function) | Named Date/Time Formats (Format Function) | Named Numeric Formats (Format Function) | Returning Strings from Functions | Str Function | Type Conversion Functions | User-Defined Date/Time Formats (Format Function) | User-Defined Numeric Formats (Format Function) | User-Defined String Formats (Format Function)


FormatCurrency Function

Returns an expression formatted as a currency value using the currency symbol defined in the system control panel.

FormatCurrency(
   Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]]
)

Arguments

Expression
Required. Expression to be formatted.
NumDigitsAfterDecimal
Optional. Numeric value indicating how many places to the right of the decimal are displayed. Default value is –1, which indicates that the computer's regional settings are used.
IncludeLeadingDigit
Optional. Tristate constant that indicates whether or not a leading zero is displayed for fractional values. See Settings section for values.
UseParensForNegativeNumbers
Optional. Tristate constant that indicates whether or not to place negative values within parentheses. See Settings section for values.
GroupDigits
Optional. Tristate constant that indicates whether or not numbers are grouped using the group delimiter specified in the computer's regional settings. See Settings section for values.

Settings

The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings:

Constant | Value | Description
True | –1 | True
False | 0 | False
Default | –2 | Use the setting from the computer's regional settings.

Remarks

When one or more optional arguments are omitted, the values for omitted arguments are provided by the computer's regional settings.

The position of the currency symbol relative to the currency value is determined by the system's regional settings.

Note All settings information comes from the locale of the application. by default, that will be the locale set in the control panel. However, it may be changed programmatically by using NGWS frameworks in System.Globalization.CultureInfo , except leading zero which comes from the Number tab.

See Also

FormatDateTime Function | FormatNumber Function | FormatPercent Function


FormatDateTime Function

Returns an expression formatted as a date or time.

FormatDateTime(Date[,NamedFormat])

Arguments

Date
Required. Date expression to be formatted.
NamedFormat
Optional. Numeric value that indicates the date/time format used. If omitted, GeneralDate is used.

Settings

The NamedFormat argument has the following settings:

Constant | Value | Description
GeneralDate | 0 | Display a date and/or time. If there is a date part, display it as a short date. If there is a time part, display it as a long time. If present, both parts are displayed.
LongDate | 1 | Display a date using the long date format specified in your computer's regional settings.
ShortDate | 2 | Display a date using the short date format specified in your computer's regional settings.
LongTime | 3 | Display a time using the time format specified in your computer's regional settings.
ShortTime | 4 | Display a time using the 24-hour format (hh:mm).

See Also

FormatCurrency Function | FormatNumber Function | FormatPercent Function


FormatNumber Function

Returns an expression formatted as a number.

FormatNumber(
   Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]]
)

Arguments

Expression
Required. Expression to be formatted.
NumDigitsAfterDecimal
Optional. Numeric value indicating how many places to the right of the decimal are displayed. Default value is –1, which indicates that the locale settings are used.
IncludeLeadingDigit
Optional. Tristate constant that indicates whether or not a leading zero is displayed for fractional values. See Settings section for values.
UseParensForNegativeNumbers
Optional. Tristate constant that indicates whether or not to place negative values within parentheses. See Settings section for values.
GroupDigits
Optional. Tristate constant that indicates whether or not numbers are grouped using the group delimiter specified in the locale settings. See Settings section for values.

Settings

The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings:

Constant | Value | Description
True | –1 | True
False | 0 | False
Default | –2 | Use the setting from the computer's regional settings.

Remarks

When one or more optional arguments are omitted, the values for omitted arguments are provided by the locale settings.

Note All settings information comes from the locale of the application. by default, that will be the locale set in the control panel. However, it may be changed programmatically by using NGWS frameworks in System.Globalization.CultureInfo.

See Also

FormatCurrency Function | FormatDateTime Function | FormatPercent Function


FormatPercent Function

Returns an expression formatted as a percentage (multipled by 100) with a trailing % character.

FormatPercent(
   Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]]
)

Arguments

Expression
Required. Expression to be formatted.
NumDigitsAfterDecimal
Optional. Numeric value indicating how many places to the right of the decimal are displayed. Default value is –1, which indicates that the locale settings are used.
IncludeLeadingDigit
Optional. Tristate constant that indicates whether or not a leading zero is displayed for fractional values. See Settings section for values.
UseParensForNegativeNumbers
Optional. Tristate constant that indicates whether or not to place negative values within parentheses. See Settings section for values.
GroupDigits
Optional. Tristate constant that indicates whether or not numbers are grouped using the group delimiter specified in the locale settings. See Settings section for values.

Settings

The IncludeLeadingDigit, UseParensForNegativeNumbers, and GroupDigits arguments have the following settings:

Constant | Value | Description
True | –1 | True
False | 0 | False
Default | –2 | Use the setting from the computer's regional settings.

Remarks

When one or more optional arguments are omitted, the values for omitted arguments are provided by the locale settings.

Note All settings information comes from the locale of the application. by default, that will be the locale set in the control panel. However, it may be changed programmatically by using NGWS frameworks in System.Globalization.CultureInfo.

See Also

FormatCurrency Function | FormatDateTime Function | FormatNumber Function


FreeFile Function

Returns an Integer representing the next file number available for use by the Open statement.

FreeFile()

Remarks

Use FreeFile to supply a file number that is not already in use.

See Also

Example

Open Statement


FreeFile Function Example

This example uses the FreeFile function to return the next available file number. Five files are opened for output within the loop, and some sample data is written to each.

Dim MyIndex, FileNumber
For MyIndex = 1 To 5   ' Loop 5 times.
   FileNumber = FreeFile   ' Get unused file
      ' number.
   Open "TEST" & MyIndex For Output As #FileNumber   ' Create file name.
   Write #FileNumber, "This is a sample."   ' Output text.
   Close #FileNumber   ' Close file.
Next MyIndex


FV Function

Returns a Double specifying the future value of an annuity based on periodic, fixed payments and a fixed interest rate.

FV(rate, nper, pmt[, pv[, type]])

Arguments

rate
Required. Double specifying interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
nper
Required. Integer specifying total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.
pmt
Required. Double specifying payment to be made each period. Payments usually contain principal and interest that doesn't change over the life of the annuity.
pv
Optional. Objectspecifying present value (or lump sum) of a series of future payments. For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make. If omitted, 0 is assumed.
type
Optional. Object specifying when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

Remarks

An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan).

The rate and nper arguments must be calculated using payment periods expressed in the same units. For example, if rate is calculated using months, nper must also be calculated using months.

For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers.

See Also

Example

DDB Function | IPmt Function | IRR Function | MIRR Function | NPer Function | NPV Function | Pmt Function | PPmt Function | PV Function | Rate Function | SLN Function | SYD Function


FV Function Example

This example uses the FV function to return the future value of an investment given the percentage rate that accrues per period (APR / 12), the total number of payments (TotPmts), the payment (Payment), the current value of the investment (PVal), and a number that indicates whether the payment is made at the beginning or end of the payment period (PayType). Note that because Payment represents cash paid out, it's a negative number.

Dim Fmt, Payment, APR, TotPmts, PayType, PVal, FVal
Const ENDPERIOD = 0, BEGINPERIOD = 1   ' When payments are made.
Fmt = "###,###,##0.00"   ' Define money format.
Payment = InputBox("How much do you plan to save each month?")
APR = InputBox("Enter the expected interest annual percentage rate.")
If APR > 1 Then APR = APR / 100   ' Ensure proper form.
TotPmts = InputBox("For how many months do you expect to save?")
PayType = MsgBox("Do you make payments at the end of month?", vbYesNo)
If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD
PVal = InputBox("How much is in this savings account now?")
FVal = FV(APR / 12, TotPmts, -Payment, -PVal, PayType)
MsgBox "Your savings will be worth " & Format(FVal, Fmt) & "."


Get Function

Reads data from an open disk file into a variable.

Get (channel, value, recordnumber)

Arguments

channel
Required. Any valid file number.
value
Required. Valid variable name into which data is read.
recordnumber
Optional. Record number (Random mode files) or byte number (Binary mode files) at which reading begins.

Remarks

Data read with Get is usually written to a file with Put.

The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you omit recordnumber, the next record or byte following the last Get or Put statement (or pointed to by the last Seek function) is read.

Question: How much of the following text remains true?

You must include delimiting commas, for example:

Get #4,,FileBuffer

For files opened in Random mode, the following rules apply:

  • If the length of the data being read is less than the length specified in the Len clause of the Open statement, Get reads subsequent records on record-length boundaries. The space between the end of one record and the beginning of the next record is padded with the existing contents of the file buffer. Because the amount of padding data can't be determined with any certainty, it is generally a good idea to have the record length match the length of the data being read.
  • If the variable being read into is a variable-length string, Get reads a 2-byte descriptor containing the string length and then reads the data that goes into the variable. Therefore, the record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual length of the string.
  • If the variable being read into is a dynamic array, Get reads a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * NumberOfDimensions. The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to read the array data and the array descriptor. For example, the following array declaration requires 118 bytes when the array is written to disk.
    Dim MyArray(1 To 5,1 To 10) As Integer

    The 118 bytes are distributed as follows: 18 bytes for the descriptor (2 + 8 * 2), and 100 bytes for the data (5 * 10 * 2).

  • If the variable being read into is a fixed-size array, Get reads only the data. No descriptor is read.
  • If the variable being read into is any other type of variable (not a variable-length string or an Object), Get reads only the variable data. The record length specified by the Len clause in the Open statement must be greater than or equal to the length of the data being read.
  • Get reads elements of user-defined types as if each were being read individually, except that there is no padding between elements. On disk, a dynamic array in a user-defined type (written with Put) is prefixed by a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * NumberOfDimensions. The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to read the individual elements, including any arrays and their descriptors.

For files opened in Binary mode, all of the Random rules apply, except:

  • The Len clause in the Open statement has no effect. Get reads all variables from disk contiguously; that is, with no padding between records.
  • For any array other than an array in a user-defined type, Get reads only the data. No descriptor is read.
  • Get reads variable-length strings that aren't elements of user-defined types without expecting the 2-byte length descriptor. The number of bytes read equals the number of characters already in the string. For example, the following statements read 10 bytes from file number 1:
    VarString = String(10," ")
Get #1,,VarString

Question: How much of the text above remains true?…in case you forgot my asking this the first time…

See Also

Example


GetAllSettings Function

Returns a list of key settings and their respective values (originally created with SaveSetting) from an application's entry in the Windows registry.

GetAllSettings(appname, section)

Arguments

appname
Required. String expression containing the name of the application or project whose key settings are requested.
section
Required. String expression containing the name of the section whose key settings are requested. GetAllSettings returns an object that contains a two-dimensional array of strings. The strings contain all the key settings in the specified section, plus their corresponding values.

Remarks

GetAllSettings returns an uninitialized Object if either appname or section does not exist.

See Also

Example


GetAllSettings Function Example

This example first uses the SaveSetting statement to make entries in the WindowsMacintosh registry (or .ini file on 16-bit Windows platforms) for the application specified as appname, then uses the GetAllSettings function to display the settings. Note that application names and section names can't be retrieved with GetAllSettings. Finally, the DeleteSetting statement removes the application's entries.

' Variant to hold 2-dimensional array returned by GetAllSettings
' Integer to hold counter.
Dim MySettings As Variant, intSettings As Integer
' Place some settings in the registry.
SaveSetting appname := "MyApp", section := "Startup", _
key := "Top", setting := 75
SaveSetting "MyApp","Startup", "Left", 50
' Retrieve the settings.
MySettings = GetAllSettings(appname := "MyApp", section := "Startup")
   For intSettings = LBound(MySettings, 1) To UBound(MySettings, 1)
      Debug.Print MySettings(intSettings, 0), MySettings(intSettings, 1)
   Next intSettings
DeleteSetting "MyApp", "Startup"


GetAttr Function

Returns a FileAttribute representing the attributes of a file, directory, or folder.

GetAttr(pathname)

The required pathname argument is a string expression that specifies a file name. The pathname may include the directory or folder, and the drive.

Return Values

The value returned by GetAttr is the sum of the following attribute values:

Constant | Value | Description
Normal | 0 | Normal.
ReadOnly | 1 | Read-only.
Hidden | 2 | Hidden.
System | 4 | System file.
Directory | 16 | Directory or folder.
Archive | 32 | File has changed since last backup.

Note These constants are specified by Visual Basic for Applications. The names can be used anywhere in your code in place of the actual values.

Remarks

To determine which attributes are set, use the And operator to perform a bitwise comparison of the value returned by the GetAttr function and the value of the individual file attribute you want. If the result is not zero, that attribute is set for the named file. For example, the return value of the following And expression is zero if the Archive attribute is not set:

Result = GetAttr(FName) And vbArchive

A nonzero value is returned if the Archive attribute is set.

See Also

Example


GetAttr Function Example

This example uses the GetAttr function to determine the attributes of a file and directory or folder.

Dim MyAttr
' Assume file TESTFILE has hidden attribute set.
MyAttr = GetAttr("TESTFILE")   ' Returns 2.

' Returns nonzero if hidden attribute is set on TESTFILE.
Debug.Print MyAttr And vbHidden

' Assume file TESTFILE has hidden and read-only attributes set.
MyAttr = GetAttr("TESTFILE")   ' Returns 3.

' Returns nonzero if hidden attribute is set on TESTFILE.
Debug.Print MyAttr And (vbHidden + vbReadOnly)

' Assume MYDIR is a directory or folder.
MyAttr = GetAttr("MYDIR")   ' Returns 16.


GetObject Function

Returns a reference to an object provided by a COM component.

GetObject([pathname] [, class])

The GetObject function syntax has these named arguments:

Part | Description
pathname | Optional; String. The full path and name of the file containing the object to retrieve. If pathname is omitted, class is required.
class | Optional; String. A string representing the class of the object.

The class argument uses the syntax appname.objecttype and has these parts:

Part | Description
appname | Required; String. The name of the application providing the object.
objecttype | Required; String. The type or class of object to create.

Remarks

Use the GetObject function to load an ActiveX object from a file. For example:

Dim CADObject As Object
CADObject = GetObject("C:\CAD\SCHEMA.CAD")

When this code is executed, the application associated with the specified pathname is started and the object in the specified file is activated.

If pathname is a zero-length string (""), GetObject returns a new object instance of the specified type. If the pathname argument is omitted, GetObject returns a currently active object of the specified type. If no object of the specified type exists, an error occurs.

Some applications allow you to activate a subobject associated with a file. Add an exclamation point (!) to the end of the file name and follow it with a string that identifies the part of the file you want to activate. For information on how to create this string, see the documentation for the application that created the object.

For example, in a drawing application you might have multiple layers to a drawing stored in a file. You could use the following code to activate a layer within a drawing called SCHEMA.CAD:

LayerObject = GetObject("C:\CAD\SCHEMA.CAD!Layer3")

If you don't specify the object's class, Automation determines the application to start and the object to activate, based on the file name you provide. Some files, however, may support more than one class of object. For example, a drawing might support three different types of objects: an Application object, a Drawing object, and a Toolbar object, all of which are part of the same file. To specify which object in a file you want to activate, use the optional class argument. For example:

Dim MyObject As Object
MyObject = GetObject("C:\DRAWINGS\SAMPLE.DRW", "FIGMENT.DRAWING")

In the example, FIGMENT is the name of a drawing application and DRAWING is one of the object types it supports.

Once an object is activated, you reference it in code using the object variable you defined. In the preceding example, you access properties and methods of the new object using the object variable MyObject. For example:

MyObject.Line (9, 90)
MyObject.InsertText (9, 100, "Hello, world.")
MyObject.SaveAs ("C:\DRAWINGS\SAMPLE.DRW")
Note Use the GetObject function when there is a current instance of the object or if you want to create the object with a file already loaded. If there is no current instance, and you don't want the object started with a file loaded, use the CreateObject function.
If an object has registered itself as an Active-X single-instance object, only one instance of the object is created, no matter how many times CreateObject is executed. With a single-instance object, GetObject always returns the same instance when called with the zero-length string ("") syntax, and it causes an error if the pathname argument is omitted. You can't use GetObject to obtain a reference to a class created with Visual Basic.

See Also

Example

CreateObject Function


GetObject Function Example

This example uses the GetObject function to get a reference to a specific Microsoft Excel worksheet (MyXL). It uses the worksheet's Application property to make Microsoft Excel visible, to close it, and so on. Using two API calls, the DetectExcel Sub procedure looks for Microsoft Excel, and if it is running, enters it in the Running Object Table. The first call to GetObject causes an error if Microsoft Excel isn't already running. In the example, the error causes the ExcelWasNotRunning flag to be set to True. The second call to GetObject specifies a file to open. If Microsoft Excel isn't already running, the second call starts it and returns a reference to the worksheet represented by the specified file, mytest.xls. The file must exist in the specified location; otherwise, the Visual Basic error Automation error is generated. Next the example code makes both Microsoft Excel and the window containing the specified worksheet visible. Finally, if there was no previous version of Microsoft Excel running, the code uses the Application object's Quit method to close Microsoft Excel. If the application was already running, no attempt is made to close it. The reference itself is released by setting it to Nothing.

' Declare necessary API routines:
Declare Function FindWindow Lib "user32" Alias _
"FindWindowA" (ByVal lpClassName as String, _
               ByVal lpWindowName As Long) As Long

Declare Function SendMessage Lib "user32" Alias _
"SendMessageA" (ByVal hWnd as Long,ByVal wMsg as Long, _
               ByVal wParam as Long, _
               ByVal lParam As Long) As Long

Sub GetExcel()
   Dim MyXL As Object   ' Variable to hold reference
                        ' to Microsoft Excel.
   Dim ExcelWasNotRunning As Boolean   ' Flag for final release.

' Test to see if there is a copy of Microsoft Excel already running.
   On Error Resume Next   ' Defer error trapping.
' Getobject function called without the first argument returns a
' reference to an instance of the application. If the application isn't
' running, an error occurs.
   Set MyXL = Getobject(, "Excel.Application")
   If Err.Number <> 0 Then ExcelWasNotRunning = True
   Err.Clear   ' Clear Err object in case error occurred.

' Check for Microsoft Excel. If Microsoft Excel is running,
' enter it into the Running Object table.
   DetectExcel

' Set the object variable to reference the file you want to see.
   Set MyXL = Getobject("c:\vb4\MYTEST.XLS")

' Show Microsoft Excel through its Application property. Then
' show the actual window containing the file using the Windows
' collection of the MyXL object reference.
   MyXL.Application.Visible = True
   MyXL.Parent.Windows(1).Visible = True
    Do manipulations of your  file here.
   ' ...
' If this copy of Microsoft Excel was not running when you
' started, close it using the Application property's Quit method.
' Note that when you try to quit Microsoft Excel, the
' title bar blinks and a message is displayed asking if you
' want to save any loaded files.
   If ExcelWasNotRunning = True Then
      MyXL.Application.Quit
   End IF

   Set MyXL = Nothing   ' Release reference to the
                        ' application and spreadsheet.
End Sub

Sub DetectExcel()
' Procedure dectects a running Excel and registers it.
   Const WM_USER = 1024
   Dim hWnd As Long
' If Excel is running this API call returns its handle.
   hWnd = FindWindow("XLMAIN", 0)
   If hWnd = 0 Then   ' 0 means Excel not running.
      Exit Sub
   Else
   ' Excel is running so use the SendMessage API
   ' function to enter it in the Running Object Table.
      SendMessage hWnd, WM_USER + 18, 0, 0
   End If
End Sub


GetSetting Function

Returns a key setting value from an application's entry in the Windows registry.

GetSetting(appname, section, key[, default])

Arguments

appname
Required. String expression containing the name of the application or project whose key setting is requested.
section
Required. String expression containing the name of the section in which the key setting is found.
key
Required. String expression containing the name of the key setting to return.
default
Optional. Expression containing the value to return if no value is set in the key setting. If omitted, default is assumed to be a zero-length string ("").

Remarks

If any of the items named in the GetSetting arguments do not exist, GetSetting returns a value of default.

See Also

Example


GetSetting Function Example

This example first uses the SaveSetting statement to make entries in the WindowsMacintosh registry (or .ini file on 16-bit Windows platforms) for the application specified as appname, and then uses the GetSetting function to display one of the settings. Because the default argument is specified, some value is guaranteed to be returned. Note that section names can't be retrieved with GetSetting. Finally, the DeleteSetting statement removes all the application's entries.

' Variant to hold 2-dimensional array returned by GetSetting.
Dim MySettings As Variant
' Place some settings in the registry.
SaveSetting "MyApp","Startup", "Top", 75
SaveSetting "MyApp","Startup", "Left", 50

Debug.Print GetSetting(appname := "MyApp", section := "Startup", _
                       key := "Left", default := "25")

DeleteSetting "MyApp", "Startup"


H-L Functions

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

H-L Functions (Visual Basic for Applications)

Hex Function

Hour Function

IIf Function

IMEStatus Function

Input Function

InputBox Function

InStr Function

InStrRev Function

Int Function

IPmt Function

IRR Function

IsArray Function

IsDate Function

IsEmpty Function

IsError Function

IsMissing Function

IsNull Function

IsNumeric Function

IsObject Function

Join Function

LBound Function

LCase Function

Left Function

Len Function

Loc Function

LOF Function

Log Function

LTrim Function


Hex Function

Returns a String representing the hexadecimal value of a number.

Hex(number)

The required number argument is any valid numeric expression or string expression .

Remarks

If number is not already a whole number, it is rounded to the nearest whole number before being evaluated.

If number is | Hex returns
Empty | Zero (0)
Any other number | Up to eight hexadecimal characters

You can represent hexadecimal numbers directly by preceding numbers in the proper range with &H. For example, &H10 represents decimal 16 in hexadecimal notation.

See Also

Example


Hex Function Example

This example uses the Hex function to return the hexadecimal value of a number.

Dim MyHex
MyHex = Hex(5)   ' Returns 5.
MyHex = Hex(10)   ' Returns A.
MyHex = Hex(459)   ' Returns 1CB.


Hour Function

Returns an Integer specifying a whole number between 0 and 23, inclusive, representing the hour of the day.

Hour(time)

The required time argument is any Object, numeric expression, string expression, or any combination, that can represent a time.

See Also

Example


Hour Function Example

This example uses the Hour function to obtain the hour from a specified time. In the development environment, the time literal is displayed in short time format using the locale settings of your code.

Dim MyTime, MyHour
MyTime = #4:35:17 PM#   ' Assign a time.
MyHour = Hour(MyTime)   ' MyHour contains 16.


IIf Function

Returns one of two parts, depending on the evaluation of an expression.

IIf(expr, truepart, falsepart)

The IIf function syntax has these named arguments:

Parameters

expr
Required. A Boolean expression you want to evaluate.
truepart
Required. Value or expression returned if expr is True.
falsepart
Required. Value or expression returned if expr is False.

Remarks

IIf always evaluates both truepart and falsepart, even though it returns only one of them. Because of this, you should watch for undesirable side effects. For example, if evaluating falsepart results in a division by zero error, an error occurs even if expr is True.

See Also

Example


IIf Function Example

This example uses the IIf function to evaluate the TestMe parameter of the CheckIt procedure and returns the word "Large" if the amount is greater than 1000; otherwise, it returns the word "Small".

Function CheckIt (TestMe As Integer)
   CheckIt = IIf(TestMe > 1000, "Large", "Small")
End Function


IMEStatus Function

Returns an Integer specifying the current Input Method Editor (IME) mode of Microsoft Windows; available in East Asian versions only.

IMEStatus

Return Values

The return values for the Japanese locale are as follows:

Constant | Value | Description
vbIMEModeNoControl | 0 | Don't control IME (default)
vbIMEModeOn | 1 | IME on
vbIMEModeOff | 2 | IME off
vbIMEModeDisable | 3 | IME disabled
vbIMEModeHiragana | 4 | Full-width Hiragana mode
vbIMEModeKatakana | 5 | Full-width Katakana mode
vbIMEModeKatakanaHalf | 6 | Half-width Katakana mode
vbIMEModeAlphaFull | 7 | Full-width Alphanumeric mode
vbIMEModeAlpha | 8 | Half-width Alphanumeric mode

The return values for the Korean locale are as follows:

Constant | Value | Description
vbIMEModeNoControl | 0 | Don't control IME(default)
vbIMEModeAlphaFull | 7 | Full-width Alphanumeric mode
vbIMEModeAlpha | 8 | Half-width Alphanumeric mode
vbIMEModeHangulFull | 9 | Full-width Hangul mode
vbIMEModeHangul | 10 | Half-width Hangul mode

The return values for the Chinese locale are as follows:

Constant | Value | Description
vbIMEModeNoControl | 0 | Don't control IME (default)
vbIMEModeOn | 1 | IME on
vbIMEModeOff | 2 | IME off

See Also

IMEStatus Constants


Input Function

Returns String containing characters from a file opened in Input or Binary mode.

Input(channel, number)

Arguments

channel
Required. Any valid file number.
number
Required. Any valid numeric expression specifying the number of characters to return.

Remarks

Data read with the Input function is usually written to a file with Print # or Put. Use this function only with files opened in Input or Binary mode.

Unlike the Input #function, the Input function returns all of the characters it reads including commas, carriage returns, linefeeds, quotation marks, and leading spaces.

With files opened for Binary access, an attempt to read through the file using the Input function until EOF returns True generates an error. Use the LOF and Loc functions instead of EOF when reading binary files with Input, or use Get when using the EOF function.

See Also

Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

InputB Function

[Topic intentionally blank - content coming in later builds]


Input # Function

Reads data from an open sequential file and assigns the data to variables.

Input (channel, value)

Arguments

channel
Required. Any valid file number.
value
Required. Comma-delimited list of variables that are assigned values read from the file — can't be an array or object variable

Remarks

Data read with Input # is usually written to a file with Write #. Use this function only with files opened in Input or Binary mode.

When read, standard string or numeric data is assigned to variables without modification. The following table illustrates how other input data is treated:

Data | Value assigned to variable
Delimiting comma or blank line | Empty
#NULL# | Null
#TRUE# or #FALSE# | True or False
#yyyy-mm-dd hh:mm:ss# | The date and/or time represented by the expression
#ERROR errornumber# | errornumber (variable is an Objecttagged as an error)

If you reach the end of the file while you are inputting a data item, the input is terminated and an error occurs.

See Also

Example


InputBox Function

Displays a prompt in a dialog box, waits for the user to input text or click a button, and returns a String containing the contents of the text box.

InputBox(
   prompt[,
   title] [,
   default] [,
   xpos] [,
   ypos]
)

Arguments

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 carriage return–linefeed character combination (Chr(13) & Chr(10)) between each line.
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.
default
Optional. String expression displayed in the text box as the default response if no other input is provided. If you omit default, the text box is displayed empty.
xpos
Optional. Numeric expression that specifies, in twips, the horizontal distance of the left edge of the dialog box from the left edge of the screen. If xpos is omitted, the dialog box is horizontally centered.
ypos
Optional. Numeric expression that specifies, in twips, the vertical distance of the upper edge of the dialog box from the top of the screen. If ypos is omitted, the dialog box is vertically positioned approximately one-third of the way down the screen.

Remarks

To specify more than the first-named argument, you must use InputBox in an expression. To omit some positional arguments, you must include the corresponding comma delimiter.

See Also

Example


InputBox Function Example

This example shows various ways to use the InputBox function to prompt the user to enter a value. If the x and y positions are omitted, the dialog box is automatically centered for the respective axes. The variable MyValue contains the value entered by the user if the user clicks OK or presses the ENTERkey . If the user clicks Cancel, a zero-length string is returned.

Dim Message, Title, Default, MyValue
Message = "Enter a value between 1 and 3"   ' Set prompt.
Title = "InputBox Demo"   ' Set title.
Default = "1"   ' Set default.
' Display message, title, and default value.
MyValue = InputBox(Message, Title, Default)

' Use Helpfile and context. The Help button is added automatically.
MyValue = InputBox(Message, Title, , , , "DEMO.HLP", 10)

' Display dialog box at position 100, 100.
MyValue = InputBox(Message, Title, Default, 100, 100)


InStr Function

Returns aLong specifying the position of the first occurrence of one string within another.

InStr([start, ]string1, string2[, compare])

Arguments

start
Optional. Numeric expression that sets the starting position for each search. If omitted, search begins at the first character position. The start argument is required if compare is specified.
string1
Required. String expression being searched.
string2
Required. String expression sought.
compare
Optional. Specifies the type of string comparison. If compare is omitted, the Option Compare setting determines the type of comparison. Specify a valid LCID (LocaleID) to use locale-specific rules in the comparison.

Settings

The compare argument settings are:

Constant | Value | Description
BinaryCompare | 0 | Performs a binary comparison.
TextCompare | 1 | Performs a textual comparison.

Return Values

If | InStr returns
string1 is zero-length | 0
string2 is zero-length | start
string2 is not found | 0
string2 is found within string1 | Position at which match is found
start > string2 | 0

See Also

Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

InStrB Function

[Topic intentionally blank - content coming in later builds]


InStrRev Function

Returns the position of an occurrence of one string within another, from the end of string.

InstrRev(stringcheck, stringmatch[, start[, compare]])

Arguments

stringcheck
Required. String expression being searched.
stringmatch
Required. String expression being searched for.
start
Optional. Numeric expression that sets the starting position for each search. If omitted, –1 is used, which means that the search begins at the last character position.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. If omitted, a binary comparison is performed. See Settings section for values.

Settings

The compare argument can have the following values:

Constant | Value | Description
BinaryCompare | 0 | Performs a binary comparison.
TextCompare | 1 | Performs a textual comparison.

Return Values

InStrRev returns the following values:

If | InStrRev returns
stringcheck is zero-length | 0
stringmatch is zero-length | start
stringmatch is not found | 0
stringmatch is found within stringcheck | Position at which match is found
start > Len(stringmatch) | 0

Remarks

Note that the syntax for the InstrRev function is not the same as the syntax for the Instr function.

See Also


IPmt Function

Returns a Double specifying the interest payment for a given period of an annuity based on periodic, fixed payments and a fixed interest rate.

IPmt(rate, per, nper, pv[, fv[, type]])

Arguments

rate
Required. Double specifying interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
per
Required. Double specifying payment period in the range 1 through nper.
nper
Required. Double specifying total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.
pv
Required. Double specifying present value, or value today, of a series of future payments or receipts. For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.
fv
Optional. Objectspecifying future value or cash balance you want after you've made the final payment. For example, the future value of a loan is $0 because that's its value after the final payment. However, if you want to save $50,000 over 18 years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.
type
Optional. Object specifying when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

Remarks

An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan).

The rate and nper arguments must be calculated using payment periods expressed in the same units. For example, if rate is calculated using months, nper must also be calculated using months.

For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers.

See Also

Example

DDB Function | IRR Function | MIRR Function | NPer Function | NPV Function | Pmt Function | PPmt Function | PV Function | Rate Function | SLN Function | SYD Function


IPmt Function Example

This example uses the IPmt function to calculate how much of a payment is interest when all the payments are of equal value. Given are the interest percentage rate per period (APR / 12), the payment period for which the interest portion is desired (Period), the total number of payments (TotPmts), the present value or principal of the loan (PVal), the future value of the loan (FVal), and a number that indicates whether the payment is due at the beginning or end of the payment period (PayType).

Dim FVal, Fmt, PVal, APR, TotPmts, PayType, Period, IntPmt, TotInt, Msg
Const ENDPERIOD = 0, BEGINPERIOD = 1   ' When payments are made.
FVal = 0   ' Usually 0 for a loan.
Fmt = "###,###,##0.00"   ' Define money format.
PVal = InputBox("How much do you want to borrow?")
APR = InputBox("What is the annual percentage rate of your loan?")
If APR > 1 Then APR = APR / 100   ' Ensure proper form.
TotPmts = InputBox("How many monthly payments?")
PayType = MsgBox("Do you make payments at end of the month?", vbYesNo)
If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD
For Period = 1 To TotPmts   ' Total all interest.
   IntPmt = IPmt(APR / 12, Period, TotPmts, -PVal, FVal, PayType)
   TotInt = TotInt + IntPmt
Next Period
Msg = "You'll pay a total of " & Format(TotInt, Fmt)
Msg = Msg & " in interest for this loan."
MsgBox Msg   ' Display results.


IRR Function

Returns a Double specifying the internal rate of return for a series of periodic cash flows (payments and receipts).

IRR(values()[, guess])

Arguments

values()
Required. Array of Double specifying cash flow values. The array must contain at least one negative value (a payment) and one positive value (a receipt).
guess
Optional. Objectspecifying value you estimate will be returned by IRR. If omitted, guess is 0.1 (10 percent).

Remarks

The internal rate of return is the interest rate received for an investment consisting of payments and receipts that occur at regular intervals.

The IRR function uses the order of values within the array to interpret the order of payments and receipts. Be sure to enter your payment and receipt values in the correct sequence. The cash flow for each period doesn't have to be fixed, as it is for an annuity.

IRR is calculated by iteration. Starting with the value of guess, IRR cycles through the calculation until the result is accurate to within 0.00001 percent. If IRR can't find a result after 20 tries, it fails.

See Also

Example

DDB Function | FV Function | IPmt Function | MIRR Function | NPer Function | NPV Function | Pmt Function | PPmt Function | PV Function | Rate Function | SLN Function | SYD Function


IRR Function Example

In this example, the IRR function returns the internal rate of return for a series of 5 cash flows contained in the array Values(). The first array element is a negative cash flow representing business start-up costs. The remaining 4 cash flows represent positive cash flows for the subsequent 4 years. Guess is the estimated internal rate of return.

Dim Guess, Fmt, RetRate, Msg
Static Values(5) As Double   ' Set up array.
Guess = .1   ' Guess starts at 10 percent.
Fmt = "#0.00"   ' Define percentage format.
Values(0) = -70000   ' Business start-up costs.
' Positive cash flows reflecting income for four successive years.
Values(1) = 22000 : Values(2) = 25000
Values(3) = 28000 : Values(4) = 31000
RetRate = IRR(Values(), Guess) * 100   ' Calculate internal rate.
Msg = "The internal rate of return for these five cash flows is "
Msg = Msg & Format(RetRate, Fmt) & " percent."
MsgBox Msg   ' Display internal return rate.


IsArray Function

Returns a Boolean value indicating whether a variable is an array.

IsArray(varname)

The required varname argument is an identifier specifying a variable.

Remarks

IsArray returns True if the variable is an array; otherwise, it returns False. IsArray is especially useful with objects containing arrays.

See Also

Example

Array Function | Declaring Arrays | IsDate Function | IsEmpty Function | IsError Function | IsNull Function | IsNumeric Function | IsObject Function | TypeName Function


IsArray Function Example

This example uses the IsArray function to check if a variable is an array.

Dim MyArray(1 To 5) As Integer, YourArray, MyCheck   ' Declare array variables.
YourArray = Array(1, 2, 3)   ' Use Array function.
MyCheck = IsArray(MyArray)   ' Returns True.
MyCheck = IsArray(YourArray)   ' Returns True.


IsDate Function

Returns a Boolean value indicating whether an expression can be converted to a date.

IsDate(expression)

The required expression argument is an Object containing a date expression or string expression recognizable as a date or time.

Remarks

IsDate returns True if the expression is a date or is recognizable as a valid date; otherwise, it returns False. In Microsoft Windows, the range of valid dates is January 1, 100 A.D. through December 31, 9999 A.D.; the ranges vary among operating systems.

See Also

Example


IsDate Function Example

This example uses the IsDate function to determine if an expression can be converted to a date.

Dim MyDate, YourDate, NoDate, MyCheck
MyDate = "February 12, 1969": YourDate = #2/12/69#: NoDate = "Hello"
MyCheck = IsDate(MyDate)   ' Returns True.
MyCheck = IsDate(YourDate)   ' Returns True.
MyCheck = IsDate(NoDate)   ' Returns False.


IsEmpty Function

Returns a Boolean value indicating whether a variable has been initialized.

IsEmpty(expression)

The required expression argument is an Object containing a numeric or string expression. However, because IsEmpty is used to determine if individual variables are initialized, the expression argument is most often a single variable name.

Remarks

IsEmpty returns True if the variable is uninitialized, or is explicitly set to Empty; otherwise, it returns False. False is always returned if expression contains more than one variable. IsEmpty only returns meaningful information for objects.

See Also

Example


IsEmpty Function Example

This example uses the IsEmpty function to determine whether a variable has been initialized.

Dim MyVar, MyCheck
MyCheck = IsEmpty(MyVar)   ' Returns True.

MyVar = Null   ' Assign Null.
MyCheck = IsEmpty(MyVar)   ' Returns False.

MyVar = Empty   ' Assign Empty.
MyCheck = IsEmpty(MyVar)   ' Returns True.


IsError Function

Returns a Boolean value indicating whether an expression is an error value.

IsError(expression)

The required expression argument can be any valid expression.

Remarks

Error values are created by converting real numbers to error values using the CVErr function. The IsError function is used to determine if a numeric expression represents an error. IsError returns True if the expression argument indicates an error; otherwise, it returns False.

See Also

Example


IsError Function Example

This example uses the IsError function to check if a numeric expression is an error value. The CVErr function is used to return an Error Variant from a user-defined function. Assume UserFunction is a user-defined function procedure that returns an error value; for example, a return value assigned with the statement UserFunction = CVErr(32767), where 32767 is a user-defined number.

Dim ReturnVal, MyCheck
ReturnVal = UserFunction()
MyCheck = IsError(ReturnVal)   ' Returns True.


IsNull Function

Returns a Boolean value that indicates whether an expression contains no valid data (Null).

IsNull(expression)

The required expression argument is a Variant containing a numeric expression or string expression.

Remarks

IsNull returns True if expression is Null; otherwise, IsNull returns False. If expression consists of more than one variable, Null in any constituent variable causes True to be returned for the entire expression.

The Null value indicates that the Variant contains no valid data. Null is not the same as Empty, which indicates that a variable has not yet been initialized. It is also not the same as a zero-length string (""), which is sometimes referred to as a null string.

Important Use the IsNull function to determine whether an expression contains a Null value. Expressions that you might expect to evaluate to True under some circumstances, such as If Var = Null and If Var <> Null, are always False. This is because any expression containing a Null is itself Null and, therefore, False.

See Also

Example

IsArray Function | IsDate Function | IsEmpty Function | IsError Function | IsMissing Function | IsNumeric Function | IsObject Function | TypeName Function | Variant Data Type | VarType Function


IsNull Function Example

This example uses the IsNull function to determine if a variable contains a Null.

Dim MyVar, MyCheck
MyCheck = IsNull(MyVar)   ' Returns False.

MyVar = ""
MyCheck = IsNull(MyVar)   ' Returns False.

MyVar = Null
MyCheck = IsNull(MyVar)   ' Returns True.


IsNumeric Function

Returns a Boolean value indicating whether an expression can be evaluated as a number.

IsNumeric(expression)

The required expression argument is an ObjectdefObjectDataType@veendf98.chmcontaining a numeric expression or string expression.

Remarks

IsNumeric returns True if the entire expression is recognized as a number; otherwise, it returns False.

IsNumeric returns False if expression is a date expression.

See Also

Example


IsNumeric Function Example

This example uses the IsNumeric function to determine if a variable can be evaluated as a number.

Dim MyVar, MyCheck
MyVar = "53"   ' Assign value.
MyCheck = IsNumeric(MyVar)   ' Returns True.

MyVar = "459.95"   ' Assign value.
MyCheck = IsNumeric(MyVar)   ' Returns True.

MyVar = "45 Help"   ' Assign value.
MyCheck = IsNumeric(MyVar)   ' Returns False.


IsObject Function

Returns a Boolean value indicating whether an identifier represents an object variable.

IsObject(identifier)

The required identifier argument is a variable name.

Remarks

IsObject is useful only in determining whether a Variant is of VarType vbObject. This could occur if the Variant actually references (or once referenced) an object, or if it contains Nothing.

IsObject returns True if identifier is a variable declared with Object type or any valid class type, or if identifier is a Variant of VarType vbObject, or a user-defined object; otherwise, it returns False. IsObject returns True even if the variable has been set to Nothing.

Use error trapping to be sure that an object reference is valid.

See Also

Example

IsArray Function | IsDate Function | IsEmpty Function | IsError Function | IsMissing Function | IsNull Function | IsNumeric Function | Object Data Type | Set Statement | TypeName Function | Variant Data Type | VarType Function


IsObject Function Example

This example uses the IsObject function to determine if an identifier represents an object variable. MyObject and YourObject are object variables of the same type. They are generic names used for illustration purposes only.

Dim MyInt As Integer, YourObject, MyCheck   ' Declare variables.
Dim MyObject As Object
Set YourObject = MyObject   ' Assign an object reference.
MyCheck = IsObject(YourObject)   ' Returns True.
MyCheck = IsObject(MyInt)   ' Returns False.


Join Function

Returns a string created by joining a number of substrings contained in an array.

Join(sourcearray[, delimiter])

Arguments

sourcearray
Required. One-dimensional array containing substrings to be joined.
delimiter
Optional. String character used to separate the substrings in the returned string. If omitted, the space character (" ") is used. If delimiter is a zero-length string (""), all items in the list are concatenated with no delimiters.

See Also

Split Function


LBound Function

Returns a Long containing the smallest available subscript for the indicated dimension of an array.

LBound(arrayname[, dimension])

The LBound function syntax has these parts:

Part | Description
arrayname | Required. Name of the array variable; follows standard variable naming conventions.
dimension | Optional; Long. Whole number indicating which dimension's lower bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If dimension is omitted, 1 is assumed.

Remarks

The LBound function is used with the UBound function to determine the size of an array. Use the UBound function to find the upper limit of an array dimension.

LBound returns the values in the following table for an array with the following dimensions:

Dim A(1 To 100, 0 To 3, -3 To 4)

Statement | Return Value
LBound(A, 1) | 1
LBound(A, 2) | 0
LBound(A, 3) | -3

The base of an array created with the Array function is zero.

See Also

Example


LBound Function Example

This example uses the LBound function to determine the smallest available subscript for the indicated dimension of an array. Use the Option Base statement to override the default base array subscript value of 0.

Dim Lower
Dim MyArray(1 To 10, 5 To 15, 10 To 20)    ' Declare array variables.
Dim AnyArray(10)
Lower = Lbound(MyArray, 1)    ' Returns 1.
Lower = Lbound(MyArray, 3)   ' Returns 10.
Lower = Lbound(AnyArray)   ' Returns 0 or 1, depending on
   ' setting of Option Base.


LCase Function

Returns a String that has been converted to lowercase.

LCase(string)

The required string argument is any valid string expression.

Remarks

Only uppercase letters are converted to lowercase; all lowercase letters and nonletter characters remain unchanged.

See Also

Example


LCase Function Example

This example uses the LCase function to return a lowercase version of a string.

Dim UpperCase, LowerCase
Uppercase = "Hello World 1234"   ' String to convert.
Lowercase = Lcase(UpperCase)   ' Returns "hello world 1234".


Left Function

Returns aString containing a specified number of characters from the left side of a string.

Left(string, length)

Arguments

string
Required. String expression from which the leftmost characters are returned.
length
Required; Long. Numeric expression indicating how many characters to return. If 0, a zero-length string ("") is returned. If greater than or equal to the number of characters in string, the entire string is returned.

Remarks

To determine the number of characters in string, use the Len function.

See Also

Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

LeftB Function

[Topic intentionally blank - content coming in later builds]


Left Function Example

This example uses the Left function to return a specified number of characters from the left side of a string.

Dim AnyString, MyStr
AnyString = "Hello World"   ' Define string.
MyStr = Left(AnyString, 1)   ' Returns "H".
MyStr = Left(AnyString, 7)   ' Returns "Hello W".
MyStr = Left(AnyString, 20)   ' Returns "Hello World".


Len Function

Returns a Long containing the number of characters in a string or the number of bytes required to store a variable.

Len(string | varname)

Arguments

string
Any valid string expression.
Varname
Any valid variable name. If varname is an Object, Len treats it the same as a String and always returns the number of characters it contains.

Remarks

One (and only one) of the two possible arguments must be specified. With user-defined types, Len returns the size as it will be written to the file.

Note Len may not be able to determine the actual number of storage bytes required when used with variable-length strings in user-defined data types.

See Also

Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

LenB Function

[Topic intentionally blank - content coming in later builds]


Len Function Example

The first example uses Len to return the number of characters in a string or the number of bytes required to store a variable. The Type...End Type block defining CustomerRecord must be preceded by the keyword Private if it appears in a class module. In a standard module, a Type statement can be Public.

Type CustomerRecord   ' Define user-defined type.
   ID As Integer   ' Place this definition in a
   Name As String * 10   ' standard module.
   Address As String * 30
End Type

Dim Customer As CustomerRecord   ' Declare variables.
Dim MyInt As Integer, MyCur As Currency
Dim MyString, MyLen
MyString = "Hello World"   ' Initialize variable.
MyLen = Len(MyInt)   ' Returns 2.
MyLen = Len(Customer)   ' Returns 42.
MyLen = Len(MyString)   ' Returns 11.
MyLen = Len(MyCur)   ' Returns 8.

The second example uses LenB and a user-defined function (LenMbcs) to return the number of byte characters in a string if ANSI is used to represent the string.

Function LenMbcs (ByVal str as String)
   LenMbcs = LenB(StrConv(str, vbFromUnicode))
End Function

Dim MyString, MyLen
MyString = "ABc"
' Where "A" and "B" are DBCS and "c" is SBCS.
MyLen = Len(MyString)
' Returns 3 - 3 characters in the string.
MyLen = LenB(MyString)
' Returns 6 - 6 bytes used for Unicode.
MyLen = LenMbcs(MyString)
' Returns 5 - 5 bytes used for ANSI.


LineInput # Function

Reads a single line from an open sequential file and assigns it to a String variable.

LineInput (channel, value)

Arguments

channel
Required. Any valid file number.
value
Required. Valid String variable name.

Remarks

Data read with LineInput # is usually written from a file with Print #.

The LineInput # function reads from a file one character at a time until it encounters a carriage return (Chr(13)) or carriage return–linefeed (Chr(13) + Chr(10)) sequence. Carriage return–linefeed sequences are skipped rather than appended to the character string.

See Also

Example


Loc Function

Returns a Long specifying the current read/write position within an open file.

Loc(filenumber)

The required filenumber argument is any valid Integer file number.

Remarks

The following describes the return value for each file access mode:

Mode | Return Value
Random | Number of the last record read from or written to the file.
Sequential | Current byte position in the file divided by 128. However, information returned by Loc for sequential files is neither used nor required.
Binary | Position of the last byte read or written.

See Also

Example


Loc Function Example

This example uses the Loc function to return the current read/write position within an open file. This example assumes that TESTFILE is a text file with a few lines of sample data.

Dim MyLocation, MyLine
Open "TESTFILE" For Binary As #1   ' Open file just created.
Do While MyLocation < LOF(1)   ' Loop until end of file.
   MyLine = MyLine & Input(1, #1)   ' Read character into variable.
   MyLocation = Loc(1)   ' Get current position within file.
' Print to the Immediate window.
   Debug.Print MyLine; Tab; MyLocation
Loop
Close #1   ' Close file.


LOF Function

Returns a Long representing the size, in bytes, of a file opened using the Open statement.

LOF(filenumber)

The required filenumber argument is an Integer containing a valid file number.

Note Use the FileLen function to obtain the length of a file that is not open.

See Also

Example


LOF Function Example

This example uses the LOF function to determine the size of an open file. This example assumes that TESTFILE is a text file containing sample data.

Dim FileLength
Open "TESTFILE" For Input As #1   ' Open file.
FileLength = LOF(1)   ' Get length of file.
Close #1   ' Close file.


Log Function

Returns a Double specifying the natural logarithm of a number.

Log(number)

The required number argument is a Double or any valid numeric expression greater than zero.

Remarks

The natural logarithm is the logarithm to the base e. The constant e is approximately 2.718282.

You can calculate base-n logarithms for any number x by dividing the natural logarithm of x by the natural logarithm of n as follows:

Logn(x) = Log(x) / Log(n)

The following example illustrates a custom Function that calculates base-10 logarithms:

Function Log10(X)
   Log10 = Log(X) / Log(10#)
End Function

See Also

Example


Log Function Example

This example uses the Log function to return the natural logarithm of a number.

Dim MyAngle, MyLog
' Define angle in radians.
MyAngle = 1.3
' Calculate inverse hyperbolic sine.
MyLog = Log(MyAngle + Sqr(MyAngle * MyAngle + 1))


LTrim, RTrim, and Trim Functions

Returns a String containing a copy of a specified string without leading spaces (LTrim), trailing spaces (RTrim), or both leading and trailing spaces (Trim).

LTrim(string)
RTrim(string)
Trim(string)

The required string argument is any valid string expression.

See Also

Example


LTrim, RTrim, and Trim Functions Example

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.

Dim MyString, TrimString
MyString = "  <-Trim->  "   ' Initialize string.
TrimString = LTrim(MyString)   ' TrimString = "<-Trim->  ".
TrimString = RTrim(MyString)   ' TrimString = "  <-Trim->".
TrimString = LTrim(RTrim(MyString))   ' TrimString = "<-Trim->".
' Using the Trim function alone achieves the same result.
TrimString = Trim(MyString)   ' TrimString = "<-Trim->".


M-P Functions

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

M-P Functions (Visual Basic Language Reference)

Mid Function

Minute Function

MIRR Function

Month Function

MonthName Function

MsgBox Function

Now Function

NPer Function

NPV Function

Oct Function

Partition Function

Pmt Function

PPmt Function

PV Function


Math Functions

Abs Function

Atn Function

Cos Function

Exp Function

Fix Function

Int Function

Log Function

Rnd Function

Sgn Function

Sin Function

Sqr Function

Tan Function

Derived Math Functions

See Also


Mid Function

Returns a String containing a specified number of characters from a string.

Mid(string, start[, length])

Arguments

string
Required. String expression from which characters are returned.
start
Required; Long. Character position in string at which the part to be taken begins. If start is greater than the number of characters in string, Mid returns a zero-length string ("").
length
Optional; Long. Number of characters to return. If omitted or if there are fewer than length characters in the text (including the character at start), all characters from the start position to the end of the string are returned.

Remarks

To determine the number of characters in string, use the Len function.

See Also

Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

MidB Function

[Topic intentionally blank - content coming in later builds]


Mid Function Example

The first example uses the Mid function to return a specified number of characters from a string.

Dim MyString, FirstWord, LastWord, MidWords
MyString = "Mid Function Demo"   ' Create text string.
FirstWord = Mid(MyString, 1, 3)   ' Returns "Mid".
LastWord = Mid(MyString, 14, 4)   ' Returns "Demo".
MidWords = Mid(MyString, 5)   ' Returns "Function Demo".

The second example use MidB and a user-defined function (MidMbcs) to also return characters from string. The difference here is that the input string is ANSI and the length is in bytes.

Function MidMbcs(ByVal str as String, start, length)
   MidMbcs = StrConv(MidB(StrConv(str, vbFromUnicode), start, length), vbUnicode)
End Function

Dim MyString
MyString = "AbCdEfG"
' Where "A", "C", "E", and "G" are DBCS and "b", "d",
' and "f" are SBCS.
MyNewString = Mid(MyString, 3, 4)
' Returns ""CdEf"
MyNewString = MidB(MyString, 3, 4)
' Returns ""bC"
MyNewString = MidMbcs(MyString, 3, 4)
' Returns "bCd"


Minute Function

Returns an Integer specifying a whole number between 0 and 59, inclusive, representing the minute of the hour.

Minute(time)

The required time argument is any Object, numeric expression, string expression, or any combination, that can represent a time.

See Also

Example


Minute Function Example

This example uses the Minute function to obtain the minute of the hour from a specified time. In the development environment, the time literal is displayed in short time format using the locale settings of your code.

Dim MyTime, MyMinute
MyTime = #4:35:17 PM#   ' Assign a time.
MyMinute = Minute(MyTime)   ' MyMinute contains 35.


MIRR Function

Returns a Double specifying the modified internal rate of return for a series of periodic cash flows (payments and receipts).

MIRR(values(), finance_rate, reinvest_rate)

The MIRR function has these named arguments:

Arguments

values()
Required. Array of Double specifying cash flow values. The array must contain at least one negative value (a payment) and one positive value (a receipt).
finance_rate
Required. Double specifying interest rate paid as the cost of financing.
reinvest_rate
Required. Double specifying interest rate received on gains from cash reinvestment.

Remarks

The modified internal rate of return is the internal rate of return when payments and receipts are financed at different rates. The MIRR function takes into account both the cost of the investment (finance_rate) and the interest rate received on reinvestment of cash (reinvest_rate).

The finance_rate and reinvest_rate arguments are percentages expressed as decimal values. For example, 12 percent is expressed as 0.12.

The MIRR function uses the order of values within the array to interpret the order of payments and receipts. Be sure to enter your payment and receipt values in the correct sequence.

See Also

Example

DDB Function | FV Function | IPmt Function | IRR Function | NPer Function | NPV Function | Pmt Function | PPmt Function | PV Function | Rate Function | SLN Function | SYD Function


MIRR Function Example

This example uses the MIRR function to return the modified internal rate of return for a series of cash flows contained in the array Values(). LoanAPR represents the financing interest, and InvAPR represents the interest rate received on reinvestment.

Dim LoanAPR, InvAPR, Fmt, RetRate, Msg
Static Values(5) As Double   ' Set up array.
LoanAPR = .1   ' Loan rate.
InvAPR = .12   ' Reinvestment rate.
Fmt = "#0.00"   ' Define money format.
Values(0) = -70000   ' Business start-up costs.
' Positive cash flows reflecting income for four successive years.
Values(1) = 22000 : Values(2) = 25000
Values(3) = 28000 : Values(4) = 31000
RetRate = MIRR(Values(), LoanAPR, InvAPR)   ' Calculate internal rate.
Msg = "The modified internal rate of return for these five cash flows is"
Msg = Msg & Format(Abs(RetRate) * 100, Fmt) & "%."
MsgBox Msg   ' Display internal return
      ' rate.


MkDir Function

Creates a new directory or folder.

MkDir (path)

The required path argument is a string expression that identifies the directory or folder to be created. The path may include the drive. If no drive is specified, MkDir creates the new directory or folder on the current drive.

See Also

Example


Month Function

Returns an Integer specifying a whole number between 1 and 12, inclusive, representing the month of the year.

Month(date)

The required date argument is any Object, numeric expression, string expression, or any combination, that can represent a date.

Note If the Calendar property setting is Gregorian, the returned integer represents the Gregorian day of the week for the date argument. If the calendar is Hijri, the returned integer represents the Hijri day of the week for the date argument. For Hijri dates, the argument number is any numeric expression that can represent a date and/or time from 1/1/100 (Gregorian Aug 2, 718) through 4/3/9666 (Gregorian Dec 31, 9999).

See Also

Example


MonthName Function

Returns a string indicating the specified month.

MonthName(month[, abbreviate])

Arguments

month
Required. The numeric designation of the month. For example, January is 1, February is 2, and so on.
abbreviate
Optional. Boolean value that indicates if the month name is to be abbreviated. If omitted, the default is False, which means that the month name is not abbreviated.

See Also

WeekdayName Function


MsgBox Function

Displays a message in a dialog box, waits for the user to click a button, and returns an Integer indicating which button the user clicked.

MsgBox(prompt[, buttons] [, title])

Arguments

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 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 omitted, the default value for buttons is 0.
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 buttons argument settings are:

Constant | Value | Description
OKOnly | 0 | Display OK button only.
OKCancel | 1 | Display OK and Cancel buttons.
AbortRetryIgnore | 2 | Display Abort, Retry, and Ignore buttons.
YesNoCancel | 3 | Display Yes, No, and Cancel buttons.
YesNo | 4 | Display Yes and No buttons.
RetryCancel | 5 | Display Retry and Cancel buttons.
Critical | 16 | Display Critical Message icon.
Question | 32 | Display Warning Query icon.
Exclamation | 48 | Display Warning Message icon.
Information | 64 | Display Information Message icon.
DefaultButton1 | 0 | First button is default.
DefaultButton2 | 256 | Second button is default.
DefaultButton3 | 512 | Third button is default.
ApplicationModal | 0 | Application modal; the user must respond to the message box before continuing work in the current application.
SystemModal | 4096 | System 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 (0–5) 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; and the fourth group (0, 4096) determines the modality of the message box. When adding numbers to create a final value for the buttons argument, use only one number from each group.

Note These constants are specified by Visual Basic for Applications. As a result, the names can be used anywhere in your code in place of the actual values.

Return Values

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

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-named argument, you must use MsgBox in an expression. To omit some positional arguments, you must include the corresponding comma delimiter.

See Also

Example


MsgBox Function 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. The value returned by the MsgBox function depends on the button chosen by the user. This example assumes that DEMO.HLP is a Help file that contains a topic with a Help context number equal to 1000.

Dim Msg, Style, Title, Help, Ctxt, Response, MyString
Msg = "Do you want to continue ?"   ' Define message.
Style = vbYesNo + vbCritical + vbDefaultButton2   ' Define buttons.
Title = "MsgBox Demonstration"   ' Define title.
Help = "DEMO.HLP"   ' Define Help file.
Ctxt = 1000   ' Define topic
      ' context.
      ' Display message.
Response = MsgBox(Msg, Style, Title, Help, Ctxt)
If Response = vbYes Then   ' User chose Yes.
   MyString = "Yes"   ' Perform some action.
Else   ' User chose No.
   MyString = "No"   ' Perform some action.
End If


Now Function

Returns a DateTime specifying the current date and time according your computer's system date and time.

Now

See Also

Example

Date Function | Date Statement | Day Function | Hour Function | Minute Function | Month Function | Second Function | Time Function | Time Statement | Weekday Function | Year Function


Now Function Example

This example uses the Now function to return the current system date and time.

Dim Today
Today = Now   ' Assign current system date and time.


NPer Function

Returns a Double specifying the number of periods for an annuity based on periodic, fixed payments and a fixed interest rate.

NPer(rate, pmt, pv[, fv[, type]])

Arguments

rate
Required. Double specifying interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
pmt
Required. Double specifying payment to be made each period. Payments usually contain principal and interest that doesn't change over the life of the annuity.
pv
Required. Double specifying present value, or value today, of a series of future payments or receipts. For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.
fv
Optional. Objectspecifying future value or cash balance you want after you've made the final payment. For example, the future value of a loan is $0 because that's its value after the final payment. However, if you want to save $50,000 over 18 years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.
type
Optional. Object specifying when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

Remarks

An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan).

For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers.

See Also

Example

DDB Function | FV Function | IPmt Function | IRR Function | MIRR Function | NPV Function | Pmt Function | PPmt Function | PV Function | Rate Function | SLN Function | SYD Function


NPer Function Example

This example uses the NPer function to return the number of periods during which payments must be made to pay off a loan whose value is contained in PVal. Also provided are the interest percentage rate per period (APR / 12), the payment (Payment), the future value of the loan (FVal), and a number that indicates whether the payment is due at the beginning or end of the payment period (PayType).

Dim FVal, PVal, APR, Payment, PayType, TotPmts
Const ENDPERIOD = 0, BEGINPERIOD = 1   ' When payments are made.
FVal = 0   ' Usually 0 for a loan.
PVal = InputBox("How much do you want to borrow?")
APR = InputBox("What is the annual percentage rate of your loan?")
If APR > 1 Then APR = APR / 100   ' Ensure proper form.
Payment = InputBox("How much do you want to pay each month?")
PayType = MsgBox("Do you make payments at the end of month?", vbYesNo)
If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD
TotPmts = NPer(APR / 12, -Payment, PVal, FVal, PayType)
If Int(TotPmts) <> TotPmts Then TotPmts = Int(TotPmts) + 1
MsgBox "It will take you " & TotPmts & " months to pay off your loan."


NPV Function

Returns a Double specifying the net present value of an investment based on a series of periodic cash flows (payments and receipts) and a discount rate.

NPV(rate, values())

Arguments

rate
Required. Double specifying discount rate over the length of the period, expressed as a decimal.
values()
Required. Array of Double specifying cash flow values. The array must contain at least one negative value (a payment) and one positive value (a receipt).

Remarks

The net present value of an investment is the current value of a future series of payments and receipts.

The NPV function uses the order of values within the array to interpret the order of payments and receipts. Be sure to enter your payment and receipt values in the correct sequence.

The NPV investment begins one period before the date of the first cash flow value and ends with the last cash flow value in the array.

The net present value calculation is based on future cash flows. If your first cash flow occurs at the beginning of the first period, the first value must be added to the value returned by NPV and must not be included in the cash flow values of values( ).

The NPV function is similar to the PV function (present value) except that the PV function allows cash flows to begin either at the end or the beginning of a period. Unlike the variable NPV cash flow values, PV cash flows must be fixed throughout the investment.

See Also

Example

DDB Function | FV Function | IPmt Function | IRR Function | MIRR Function | NPer Function | Pmt Function | PPmt Function | PV Function | Rate Function | SLN Function | SYD Function


NPV Function Example

This example uses the NPV function to return the net present value for a series of cash flows contained in the array Values(). RetRate represents the fixed internal rate of return.

Dim Fmt, Guess, RetRate, NetPVal, Msg
Static Values(5) As Double   ' Set up array.
Fmt = "###,##0.00"   ' Define money format.
Guess = .1   ' Guess starts at 10 percent.
RetRate = .0625   ' Set fixed internal rate.
Values(0) = -70000   ' Business start-up costs.
' Positive cash flows reflecting income for four successive years.
Values(1) = 22000 : Values(2) = 25000
Values(3) = 28000 : Values(4) = 31000
NetPVal = NPV(RetRate, Values())   ' Calculate net present value.
Msg = "The net present value of these cash flows is "
Msg = Msg & Format(NetPVal, Fmt) & "."
MsgBox Msg   ' Display net present value.


Oct Function

Returns an String representing the octal value of a number.

Oct(number)

The required number argument is any valid numeric expression or string expression.

Remarks

If number is not already a whole number, it is rounded to the nearest whole number before being evaluated.

If number is | Oct returns
Empty | Zero (0)
Any other number | Up to 11 octal characters

You can represent octal numbers directly by preceding numbers in the proper range with &O. For example, &O10 is the octal notation for decimal 8.

See Also

Example


Oct Function Example

This example uses the Oct function to return the octal value of a number.

Dim MyOct
MyOct = Oct(4)    ' Returns 4.
MyOct = Oct(8)   ' Returns 10.
MyOct = Oct(459)   ' Returns 713.


Partition Function

Returns a String indicating where a number occurs within a calculated series of ranges.

Partition(number, start, stop, interval)

The Partition function syntax has these named arguments:

Parameters

number
Required. Whole number that you want to evaluate against the ranges.
start
Required. Whole number that is the start of the overall range of numbers. The number can't be less than 0.
stop
Required. Whole number that is the end of the overall range of numbers. The number can't be equal to or less than start.

Remarks

The Partition function identifies the particular range in which number falls and returns aString describing that range. The Partition function is most useful in queries. You can create a select query that shows how many orders fall within various ranges, for example, order values from 1 to 1000, 1001 to 2000, and so on.

The following table shows how the ranges are determined using three sets of start, stop, and interval parts. The First Range and Last Range columns show what Partition returns. The ranges are represented by lowervalue:uppervalue, where the low end (lowervalue) of the range is separated from the high end (uppervalue) of the range with a colon (:).

start | stop | interval | Before First | First Range | Last Range | After Last
0 | 99 | 5 | " :-1" | " 0: 4" | " 95: 99" | " 100: "
20 | 199 | 10 | " : 19" | " 20: 29" | " 190: 199" | " 200: "
100 | 1010 | 20 | " : 99" | " 100: 119" | " 1000: 1010" | " 1011: "

In the table shown above, the third line shows the result when start and stop define a set of numbers that can't be evenly divided by interval. The last range extends to stop (11 numbers) even though interval is 20.

If necessary, Partition returns a range with enough leading spaces so that there are the same number of characters to the left and right of the colon as there are characters in stop, plus one. This ensures that if you use Partition with other numbers, the resulting text will be handled properly during any subsequent sort operation.

If interval is 1, the range is number:number, regardless of the start and stop arguments. For example, if interval is 1, number is 100 and stop is 1000, Partition returns " 100: 100".

If any of the parts is Null, Partition returns a Null.

See Also

Example


Partition Function Example

This example assumes you have an Orders table that contains a Freight field. It creates a select procedure that counts the number of orders for which freight cost falls into each of several ranges. The Partition function is used first to establish these ranges, then the SQL Count function counts the number of orders in each range. In this example, the arguments to the Partition function are start = 0, stop = 500, interval = 50. The first range would therefore be 0:49, and so on up to 500.

SELECT DISTINCTROW Partition([freight],0, 500, 50) AS Range,
Count(Orders.Freight) AS Count
FROM Orders
GROUP BY Partition([freight],0,500,50);


Pmt Function

Returns a Double specifying the payment for an annuity based on periodic, fixed payments and a fixed interest rate.

Pmt(rate, nper, pv[, fv[, type]])

Arguments

rate
Required. Double specifying interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
nper
Required. Integer specifying total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.
pv
Required. Double specifying present value (or lump sum) that a series of payments to be paid in the future is worth now. For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.
fv
Optional. Objectspecifying future value or cash balance you want after you've made the final payment. For example, the future value of a loan is $0 because that's its value after the final payment. However, if you want to save $50,000 over 18 years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.
type
Optional. Object specifying when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

Remarks

An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan).

The rate and nper arguments must be calculated using payment periods expressed in the same units. For example, if rate is calculated using months, nper must also be calculated using months.

For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers.

See Also

Example

DDB Function | FV Function | IPmt Function | IRR Function | MIRR Function | NPer Function | NPV Function | PPmt Function | PV Function | Rate Function | SLN Function | SYD Function


Pmt Function Example

This example uses the Pmt function to return the monthly payment for a loan over a fixed period. Given are the interest percentage rate per period (APR / 12), the total number of payments (TotPmts), the present value or principal of the loan (PVal), the future value of the loan (FVal), and a number that indicates whether the payment is due at the beginning or end of the payment period (PayType).

Dim Fmt, FVal, PVal, APR, TotPmts, PayType, Payment
Const ENDPERIOD = 0, BEGINPERIOD = 1   ' When payments are made.
Fmt = "###,###,##0.00"   ' Define money format.
FVal = 0   ' Usually 0 for a loan.
PVal = InputBox("How much do you want to borrow?")
APR = InputBox("What is the annual percentage rate of your loan?")
If APR > 1 Then APR = APR / 100   ' Ensure proper form.
TotPmts = InputBox("How many monthly payments will you make?")
PayType = MsgBox("Do you make payments at the end of month?", vbYesNo)
If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD
Payment = Pmt(APR / 12, TotPmts, -PVal, FVal, PayType)
MsgBox "Your payment will be " & Format(Payment, Fmt) & " per month."


PPmt Function

Returns a Double specifying the principal payment for a given period of an annuity based on periodic, fixed payments and a fixed interest rate.

PPmt(rate, per, nper, pv[, fv[, type]])

Arguments

rate
Required. Double specifying interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
per
Required. Integer specifying payment period in the range 1 through nper.
nper
Required. Integer specifying total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.
pv
Required. Double specifying present value, or value today, of a series of future payments or receipts. For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.
fv
Optional. Objectspecifying future value or cash balance you want after you've made the final payment. For example, the future value of a loan is $0 because that's its value after the final payment. However, if you want to save $50,000 over 18 years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.
type
Optional. Object specifying when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

Remarks

An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan).

The rate and nper arguments must be calculated using payment periods expressed in the same units. For example, if rate is calculated using months, nper must also be calculated using months.

For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers.

See Also

Example

DDB Function | FV Function | IPmt Function | IRR Function | MIRR Function | NPer Function | NPV Function | Pmt Function | PV Function | Rate Function | SLN Function | SYD Function


PPmt Function Example

This example uses the PPmt function to calculate how much of a payment for a specific period is principal when all the payments are of equal value. Given are the interest percentage rate per period (APR / 12), the payment period for which the principal portion is desired (Period), the total number of payments (TotPmts), the present value or principal of the loan (PVal), the future value of the loan (FVal), and a number that indicates whether the payment is due at the beginning or end of the payment period (PayType).

Dim NL, TB, Fmt, FVal, PVal, APR, TotPmts, PayType, Payment, Msg, MakeChart, Period, P, I
Const ENDPERIOD = 0, BEGINPERIOD = 1   ' When payments are made.
NL = Chr(13) & Chr(10)   ' Define newline.
TB = Chr(9)   ' Define tab.
Fmt = "###,###,##0.00"   ' Define money format.
FVal = 0   ' Usually 0 for a loan.
PVal = InputBox("How much do you want to borrow?")
APR = InputBox("What is the annual percentage rate of your loan?")
If APR > 1 Then APR = APR / 100   ' Ensure proper form.
TotPmts = InputBox("How many monthly payments do you have to make?")
PayType = MsgBox("Do you make payments at the end of month?", vbYesNo)
If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD
Payment = Abs(-Pmt(APR / 12, TotPmts, PVal, FVal, PayType))
Msg = "Your monthly payment is " & Format(Payment, Fmt) & ". "
Msg = Msg & "Would you like a breakdown of your principal and "
Msg = Msg & "interest per period?"
MakeChart = MsgBox(Msg, vbYesNo)   ' See if chart is desired.
If MakeChart <> vbNo Then
   If TotPmts > 12 Then MsgBox "Only first year will be shown."
   Msg = "Month  Payment  Principal  Interest" & NL
   For Period = 1 To TotPmts
      If Period > 12 Then Exit For   ' Show only first 12.
      P = PPmt(APR / 12, Period, TotPmts, -PVal, FVal, PayType)
      P = (Int((P + .005) * 100) / 100)   ' Round principal.
      I = Payment - P
      I = (Int((I + .005) * 100) / 100)   ' Round interest.
      Msg = Msg & Period & TB & Format(Payment, Fmt)
      Msg = Msg & TB & Format(P, Fmt) & TB & Format(I, Fmt) & NL
   Next Period
   MsgBox Msg   ' Display amortization table.
End If


PV Function

Returns a Double specifying the present value of an annuity based on periodic, fixed payments to be paid in the future and a fixed interest rate.

PV(rate, nper, pmt[, fv[, type]])

Arguments

rate
Required. Double specifying interest rate per period. For example, if you get a car loan at an annual percentage rate (APR) of 10 percent and make monthly payments, the rate per period is 0.1/12, or 0.0083.
nper
Required. Integer specifying total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.
pmt
Required. Double specifying payment to be made each period. Payments usually contain principal and interest that doesn't change over the life of the annuity.
fv
Optional. Objectspecifying future value or cash balance you want after you've made the final payment. For example, the future value of a loan is $0 because that's its value after the final payment. However, if you want to save $50,000 over 18 years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.
type
Optional. Object specifying when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.

Remarks

An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan).

The rate and nper arguments must be calculated using payment periods expressed in the same units. For example, if rate is calculated using months, nper must also be calculated using months.

For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers.

See Also

Example

DDB Function | FV Function | IPmt Function | IRR Function | MIRR Function | NPer Function | NPV Function | Pmt Function | PPmt Function | Rate Function | SLN Function | SYD Function


PV Function Example

In this example, the PV function returns the present value of an $1,000,000 annuity that will provide $50,000 a year for the next 20 years. Provided are the expected annual percentage rate (APR), the total number of payments (TotPmts), the amount of each payment (YrIncome), the total future value of the investment (FVal), and a number that indicates whether each payment is made at the beginning or end of the payment period (PayType). Note that YrIncome is a negative number because it represents cash paid out from the annuity each year.

Dim Fmt, APR, TotPmts, YrIncome, FVal, PayType, PVal
Const ENDPERIOD = 0, BEGINPERIOD = 1   ' When payments are made.
Fmt = "###,##0.00"   ' Define money format.
APR = .0825   ' Annual percentage rate.
TotPmts = 20   ' Total number of payments.
YrIncome = 50000   ' Yearly income.
FVal = 1000000   ' Future value.
PayType = BEGINPERIOD   ' Payment at beginning of month.
PVal = PV(APR, TotPmts, -YrIncome, FVal, PayType)
MsgBox "The present value is " & Format(PVal, Fmt) & "."


Q-Z Functions

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Q-Z Functions (Visual Basic Language Reference)

QBColor Function

Rate Function

Replace Function

RGB Function

Right Function

Rnd Function

Round Function

RTrim Function

Second Function

Seek Function

Sgn Function

Shell Function

Sin Function

SLN Function

Space Function

Spc Function

Split Function

Sqr Function

Str Function

StrComp Function

StrConv Function

String Function

StrReverse Function

Switch Function

SYD Function

Tab Function

Tan Function

Time Function

Timer Function

TimeSerial Function

TimeValue Function

Trim Function

TypeName Function

UBound Function

UCase Function

Val Function

VarType Function

Weekday Function

WeekdayName Function

Year Function


Rate Function

Returns a Double specifying the interest rate per period for an annuity.

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

Arguments

nper
Required. Double specifying total number of payment periods in the annuity. For example, if you make monthly payments on a four-year car loan, your loan has a total of 4 * 12 (or 48) payment periods.
pmt
Required. Double specifying payment to be made each period. Payments usually contain principal and interest that doesn't change over the life of the annuity.
pv
Required. Double specifying present value, or value today, of a series of future payments or receipts. For example, when you borrow money to buy a car, the loan amount is the present value to the lender of the monthly car payments you will make.
fv
Optional. Objectspecifying future value or cash balance you want after you make the final payment. For example, the future value of a loan is $0 because that's its value after the final payment. However, if you want to save $50,000 over 18 years for your child's education, then $50,000 is the future value. If omitted, 0 is assumed.
type
Optional. Object specifying a number indicating when payments are due. Use 0 if payments are due at the end of the payment period, or use 1 if payments are due at the beginning of the period. If omitted, 0 is assumed.
guess
Optional. Object specifying value you estimate will be returned by Rate. If omitted, guess is 0.1 (10 percent).

Remarks

An annuity is a series of fixed cash payments made over a period of time. An annuity can be a loan (such as a home mortgage) or an investment (such as a monthly savings plan).

For all arguments, cash paid out (such as deposits to savings) is represented by negative numbers; cash received (such as dividend checks) is represented by positive numbers.

Rate is calculated by iteration. Starting with the value of guess, Rate cycles through the calculation until the result is accurate to within 0.00001 percent. If Rate can't find a result after 20 tries, it fails. If your guess is 10 percent and Rate fails, try a different value for guess.

See Also

Example

DDB Function | FV Function | IPmt Function | IRR Function | MIRR Function | NPer Function | NPV Function | Pmt Function | PPmt Function | PV Function | SLN Function | SYD Function


Rate Function Example

This example uses the Rate function to calculate the interest rate of a loan given the total number of payments (TotPmts), the amount of the loan payment (Payment), the present value or principal of the loan (PVal), the future value of the loan (FVal), a number that indicates whether the payment is due at the beginning or end of the payment period (PayType), and an approximation of the expected interest rate (Guess).

Dim Fmt, FVal, Guess, PVal, Payment, TotPmts, PayType, APR
Const ENDPERIOD = 0, BEGINPERIOD = 1   ' When payments are made.
Fmt = "##0.00"   ' Define percentage format.
FVal = 0   ' Usually 0 for a loan.
Guess = .1   ' Guess of 10 percent.
PVal = InputBox("How much did you borrow?")
Payment = InputBox("What's your monthly payment?")
TotPmts = InputBox("How many monthly payments do you have to make?")
PayType = MsgBox("Do you make payments at the end of the month?", _
vbYesNo)
If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD
APR = (Rate(TotPmts, -Payment, PVal, FVal, PayType, Guess) * 12) * 100
MsgBox "Your interest rate is " & Format(CInt(APR), Fmt) & " percent."


Replace Function

Returns a string in which a specified substring has been replaced with another substring a specified number of times.

Replace(expression, find, replace[, start[, count[, compare]]])

Arguments

expression
Required. String expression containing substring to replace.
find
Required. Substring being searched for.
replace
Required. Replacement substring.
start
Optional. Position within expression where substring search is to begin. If omitted, 1 is assumed.
count
Optional. Number of substring substitutions to perform. If omitted, the default value is –1, which means make all possible substitutions.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values.

Settings

The compare argument can have the following values:

Constant | Value | Description
BinaryCompare | 0 | Performs a binary comparison.
TextCompare | 1 | Performs a textual comparison.

Return Values

Replace returns the following values:

If | Replace returns
expression is zero-length | Zero-length string ("")
find is zero-length | Copy of expression.
replace is zero-length | Copy of expression with all occurences of find removed.
start > Len(expression) | Zero-length string.
count is 0 | Copy of expression.

Remarks

The return value of the Replace function is a string that begins at the position specified by start and concludes at the end of the expression string, with the substitutions made as specified by the find and replace values. It is not a copy of the original string from start to finish.

See Also

Filter Function


Right Function

Returns aString containing a specified number of characters from the right side of a string.

Right(string, length)

Arguments

string
Required. String expression from which the rightmost characters are returned.
length
Required; Integer. Numeric expression indicating how many characters to return. If 0, a zero-length string ("") is returned. If greater than or equal to the number of characters in string, the entire string is returned.

Remarks

To determine the number of characters in string, use the Len function.

See Also

Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

RightB Function

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

RightB$ Function

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Right$ Function

[Topic intentionally blank - content coming in later builds]


Right Function Example

This example uses the Right function to return a specified number of characters from the right side of a string.

Dim AnyString, MyStr
AnyString = "Hello World"   ' Define string.
MyStr = Right(AnyString, 1)   ' Returns "d".
MyStr = Right(AnyString, 6)   ' Returns " World".
MyStr = Right(AnyString, 20)   ' Returns "Hello World".


RmDir Function

Removes an existing directory or folder.

RmDir (path)

The required path argument is a string expression that identifies the directory or folder to be removed. The path may include the drive. If no drive is specified, RmDir removes the directory or folder on the current drive.

Remarks

An error occurs if you try to use RmDir on a directory or folder containing files. Use the Kill statement to delete all files before attempting to remove a directory or folder.

See Also

Example


Rnd Function

Returns a Single containing a random number.

Rnd[(number)]

The optional number argument is a Single or any valid numeric expression.

Return Values

If number is | Rnd generates
Less than zero | The same number every time, using number as the seed.
Greater than zero | The next random number in the sequence.
Equal to zero | The most recently generated number.
Not supplied | The next random number in the sequence.

Remarks

The Rnd function returns a value less than 1, but greater than or equal to zero.

The value of number determines how Rnd generates a random number:

For any given initial seed, the same number sequence is generated because each successive call to the Rnd function uses the previous number as a seed for the next number in the sequence.

Before calling Rnd, use the Randomize statement without an argument to initialize the random-number generator with a seed based on the system timer.

To produce random integers in a given range, use this formula:

Int((upperbound - lowerbound + 1) * Rnd + lowerbound)

Here, upperbound is the highest number in the range, and lowerbound is the lowest number in the range.

Note To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for number does not repeat the previous sequence.

See Also

Example


Rnd Function Example

This example uses the Rnd function to generate a random integer value from 1 to 6.

Dim MyValue
MyValue = Int((6 * Rnd) + 1)   ' Generate random value between 1 and 6.


Second Function

Returns an Integer specifying a whole number between 0 and 59, inclusive, representing the second of the minute.

Second(time)

The required time argument is any Object, numeric expression, string expression, or any combination, that can represent a time.

See Also

Example


Second Function Example

This example uses the Second function to obtain the second of the minute from a specified time. In the development environment, the time literal is displayed in short time format using the locale settings of your code.

Dim MyTime, MySecond
MyTime = #4:35:17 PM#   ' Assign a time.
MySecond = Second(MyTime)   ' MySecond contains 17.


Seek Function

Returns a Long specifying the current read/write position within a file opened using the Open statement.

Seek(filenumber)

The required filenumber argument is an Integer containing a valid file number.

Remarks

Seek returns a value between 1 and 2,147,483,647 (equivalent to 2^31 – 1), inclusive.

The following describes the return values for each file access mode.

Mode | Return Value
Random | Number of the next record read or written
Binary, Output, Append, Input | Byte position at which the next operation takes place. The first byte in a file is at position 1, the second byte is at position 2, and so on.

See Also

Example


Seek Function Example

This example uses the Seek function to return the current file position. The example assumes TESTFILE is a file containing records of the user-defined type Record.

Type Record   ' Define user-defined type.
   ID As Integer
   Name As String * 20
End Type

For files opened in Random mode, Seek returns number of next record.

Dim MyRecord As Record   ' Declare variable.
Open "TESTFILE" For Random As #1 Len = Len(MyRecord)
Do While Not EOF(1)   ' Loop until end of file.
   Get #1, , MyRecord   ' Read next record.
   Debug.Print Seek(1)   ' Print record number to the
         ' Immediate window.
Loop
Close #1   ' Close file.

For files opened in modes other than Random mode, Seek returns the byte position at which the next operation takes place. Assume TESTFILE is a file containing a few lines of text.

Dim MyChar
Open "TESTFILE" For Input As #1   ' Open file for reading.
Do While Not EOF(1)   ' Loop until end of file.
   MyChar = Input(1, #1)   ' Read next character of data.
   Debug.Print Seek(1)   ' Print byte position to the
         ' Immediate window.
Loop
Close #1   ' Close file.


Sgn Function

Returns a Object (Integer) indicating the sign of a number.

Sgn(number)

The required number argument can be any valid numeric expression.

Return Values

If number is | Sgn returns
Greater than zero | 1
Equal to zero | 0
Less than zero | -1

Remarks

The sign of the number argument determines the return value of the Sgn function.

See Also

Example


Sgn Function Example

This example uses the Sgn function to determine the sign of a number.

Dim MyVar1, MyVar2, MyVar3, MySign
MyVar1 = 12: MyVar2 = -2.4: MyVar3 = 0
MySign = Sgn(MyVar1)   ' Returns 1.
MySign = Sgn(MyVar2)   ' Returns -1.
MySign = Sgn(MyVar3)   ' Returns 0.


Shell Function

Runs an executable program and returns a Variant (Double) representing the program's task ID if successful, otherwise it returns zero.

Shell(pathname[,windowstyle])

Arguments

pathname
Required; String. Name of the program to execute and any required arguments or command-line switches; may include directory or folder and drive.
windowstyle
Optional. Integer corresponding to the style of the window in which the program is to be run. If windowstyle is omitted, the program is started minimized with focus.

The windowstyle named argument has these values:

Constant | Value | Description
Hide | 0 | Window is hidden and focus is passed to the hidden window.
NormalFocus | 1 | Window has focus and is restored to its original size and position.
MinimizedFocus | 2 | Window is displayed as an icon with focus.
MaximizedFocus | 3 | Window is maximized with focus.
NormalNoFocus | 4 | Window is restored to its most recent size and position. The currently active window remains active.
MinimizedNoFocus | 6 | Window is displayed as an icon. The currently active window remains active.

Remarks

If the Shell function successfully executes the named file, it returns the task ID of the started program. The task ID is a unique number that identifies the running program. If the Shell function can't start the named program, an error occurs.

Note By default, the Shell function runs other programs asynchronously. This means that a program started with Shell might not finish executing before the statements following the Shell function are executed.

See Also

Example

AppActivate Statement


Shell Function Example

This example uses the Shell function to run an application specified by the user.

' Specifying 1 as the second argument opens the application in
' normal size and gives it the focus.
Dim RetVal
RetVal = Shell("C:\WINDOWS\CALC.EXE", 1)   ' Run Calculator.


Sin Function

Returns a Double specifying the sine of an angle.

Sin(number)

The required number argument is a Double or any valid numeric expression that expresses an angle in radians.

Remarks

The Sin function takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side opposite the angle divided by the length of the hypotenuse.

The result lies in the range -1 to 1.

To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi.

See Also

Example


Sin Function Example

This example uses the Sin function to return the sine of an angle.

Dim MyAngle, MyCosecant
MyAngle = 1.3   ' Define angle in radians.
MyCosecant = 1 / Sin(MyAngle)   ' Calculate cosecant.


SLN Function

Returns a Double specifying the straight-line depreciation of an asset for a single period.

SLN(cost, salvage, life)

Arguments

cost
Required. Double specifying initial cost of the asset.
salvage
Required. Double specifying value of the asset at the end of its useful life.
life
Required. Double specifying length of the useful life of the asset.

Remarks

The depreciation period must be expressed in the same unit as the life argument. All arguments must be positive numbers.

See Also

Example

DDB Function | FV Function | IPmt Function | IRR Function | MIRR Function | NPer Function | NPV Function | Pmt Function | PPmt Function | PV Function | Rate Function | SYD Function


SLN Function Example

This example uses the SLN function to return the straight-line depreciation of an asset for a single period given the asset's initial cost (InitCost), the salvage value at the end of the asset's useful life (SalvageVal), and the total life of the asset in years (LifeTime).

Dim Fmt, InitCost, SalvageVal, MonthLife, LifeTime, PDepr
Const YEARMONTHS = 12   ' Number of months in a year.
Fmt = "###,##0.00"   ' Define money format.
InitCost = InputBox("What's the initial cost of the asset?")
SalvageVal = InputBox("What's the asset's value at the end of its useful life?")
MonthLife = InputBox("What's the asset's useful life in months?")
Do While MonthLife < YEARMONTHS   ' Ensure period is >= 1 year.
   MsgBox "Asset life must be a year or more."
   MonthLife = InputBox("What's the asset's useful life in months?")
Loop
LifeTime = MonthLife / YEARMONTHS   ' Convert months to years.
If LifeTime <> Int(MonthLife / YEARMONTHS) Then
   LifeTime = Int(LifeTime + 1)   ' Round up to nearest year.
End If
PDepr = SLN(InitCost, SalvageVal, LifeTime)
MsgBox "The depreciation is " & Format(PDepr, Fmt) & " per year."


Space Function

Returns aString consisting of the specified number of spaces.

Space(number)

The required number argument is the number of spaces you want in the string.

Remarks

The Space function is useful for formatting output and clearing data in fixed-length strings.

See Also

Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Space$ Function

[Topic intentionally blank - content coming in later builds]


Space Function Example

This example uses the Space function to return a string consisting of a specified number of spaces.

Dim MyString
' Returns a string with 10 spaces.
MyString = Space(10)

' Insert 10 spaces between two strings.
MyString = "Hello" & Space(10) & "World"


Spc Function

Used with the Print # statement or the Print method to position output.

Spc(n)

The required n argument is the number of spaces to insert before displaying or printing the next expression in a list.

Remarks

If n is less than the output line width, the next print position immediately follows the number of spaces printed. If n is greater than the output line width, Spc calculates the next print position using the formula:

currentprintposition + (n Mod width)

For example, if the current print position is 24, the output line width is 80, and you specify Spc(90), the next print will start at position 34 (current print position + the remainder of 90/80). If the difference between the current print position and the output line width is less than n (or n Mod width), the Spc function skips to the beginning of the next line and generates spaces equal to n – (width – currentprintposition).

Note Make sure your tabular columns are wide enough to accommodate wide letters.

When you use the Print method with a proportionally spaced font, the width of space characters printed using the Spc function is always an average of the width of all characters in the point size for the chosen font. However, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy. For example, the uppercase letter W occupies more than one fixed-width column, and the lowercase letter i occupies less than one fixed-width column.

See Also

Example


Spc Function Example

This example uses the Spc function to position output in a file and in the Immediate window.

' The Spc function can be used with the Print # statement.
Open "TESTFILE" For Output As #1   ' Open file for output.
Print #1, "10 spaces between here"; Spc(10); "and here."
Close #1   ' Close file.

The following statement causes the text to be printed in the Immediate window (using the Print method), preceded by 30 spaces.

Debug.Print Spc(30); "Thirty spaces later..."


Split Function

Returns a zero-based, one-dimensional array containing a specified number of substrings.

Split(expression[, delimiter[, limit[, compare]]])

Arguments

expression
Required. String expression containing substrings and delimiters. If expression is a zero-length string(""), Split returns an empty array, that is, an array with no elements and no data.
delimiter
Optional. Single character used to identify substring limits. If omitted, the space character (" ") is assumed to be the delimiter. If delimiter is a zero-length string, a single-element array containing the entire expression string is returned.
limit
Optional. Number of substrings to be returned; –1 indicates that all substrings are returned.
compare
Optional. Numeric value indicating the kind of comparison to use when evaluating substrings. See Settings section for values.

Settings

The compare argument can have the following values:

Constant | Value | Description
BinaryCompare | 0 | Performs a binary comparison.
TextCompare | 1 | Performs a textual comparison.

See Also

Join Function


Sqr Function

Returns a Double specifying the square root of a number.

Sqr(number)

The required number argument is a Double or any valid numeric expression greater than or equal to zero.

See Also

Example


Sqr Function Example

This example uses the Sqr function to calculate the square root of a number.

Dim MySqr
MySqr = Sqr(4)   ' Returns 2.
MySqr = Sqr(23)   ' Returns 4.79583152331272.
MySqr = Sqr(0)   ' Returns 0.
MySqr = Sqr(-4)   ' Generates a run-time error.


Str Function

Returns aString representation of a number.

Str(number)

The required number argument is an Object containing any valid numeric expression.

Remarks

When numbers are converted to strings, a leading space is always reserved for the sign of number. If number is positive, the returned string contains a leading space and the plus sign is implied.

Use the Format function to convert numeric values you want formatted as dates, times, or currency or in other user-defined formats. Unlike Str, the Format function doesn't include a leading space for the sign of number.

Note The Str function recognizes only the period (.) as a valid decimal separator. When different decimal separators may be used (for example, in international applications), use CStr to convert a number to a string.

See Also

Example


StrComp Function

Returns an Integer indicating the result of a string comparison.

StrComp(string1, string2[, compare])

Arguments

string1
Required. Any valid string expression.
string2
Required. Any valid string expression.
compare
Optional. Specifies the type of string comparison. If the compare argument is Null, an error occurs. If compare is omitted, the Option Compare setting determines the type of comparison.

Settings

The compare argument settings are:

Constant | Value | Description
BinaryCompare | 0 | Performs a binary comparison, based on a sort order derived from the internal binary representations of the characters.
TextCompare | 1 | Performs a textual comparison, based on a case-insensitive text sort order.

Return Values

The StrComp function has the following return values:

If | StrComp returns
string1 is less than string2 | -1
string1 is equal to string2 | 0
string1 is greater than string2 | 1

See Also

Example


StrComp Function Example

This example uses the StrComp function to return the results of a string comparison. If the third argument is 1, a textual comparison is performed; if the third argument is 0 or omitted, a binary comparison is performed.

Dim MyStr1, MyStr2, MyComp
MyStr1 = "ABCD": MyStr2 = "abcd"   ' Define variables.
MyComp = StrComp(MyStr1, MyStr2, 1)   ' Returns 0.
MyComp = StrComp(MyStr1, MyStr2, 0)   ' Returns -1.
MyComp = StrComp(MyStr2, MyStr1)   ' Returns 1.


StrConv Function

Returns aString converted as specified.

StrConv(string, conversion, LCID)

Arguments

string
Required. String expression to be converted.
conversion
Required. Integer. The sum of values specifying the type of conversion to perform.
LCID
Optional. The LocaleID, if different than the system LocaleID. (The system LocaleID is the default.)

Settings

The conversion argument settings are:

Constant | Value | Description
UpperCase | 1 | Converts the string to uppercase characters.
LowerCase | 2 | Converts the string to lowercase characters.
ProperCase | 3 | Converts the first letter of every word in string to uppercase.
Wide* | 4* | Converts narrow (single-byte) characters in string to wide (double-byte) characters.
Narrow* | 8* | Converts wide (double-byte) characters in string to narrow (single-byte) characters.
Katakana** | 16** | Converts Hiragana characters in string to Katakana characters.
Hiragana** | 32** | Converts Katakana characters in string to Hiragana characters.
Unicode | 64 | Converts the string to Unicode using the default code page of the system.
FromUnicode | 128 | Converts the string from Unicode to the default code page of the system.

*Applies to Asian locales.

**Applies to Japan only.

Note These constants are specified in the basic runtime.. As a result, they may be used anywhere in your code in place of the actual values. Most can be combined, for example, UpperCase + Wide, except when they are mutually exclusive, for example, Unicode + FromUnicode. The constants Wide, Narrow, Katakana, and Hiragana cause run-time errors when used in locales where they do not apply.

The following are valid word separators for proper casing: Null (Chr$(0)), horizontal tab (Chr$(9)), linefeed (Chr$(10)), vertical tab (Chr$(11)), form feed (Chr$(12)), carriage return (Chr$(13)), space (SBCS) (Chr$(32)). The actual value for a space varies by country/region for DBCS.

Remarks

When you're converting from a Byte array in ANSI format to a string, you should use the StrConv function. When you're converting from such an array in Unicode format, use an assignment statement.

See Also

Example


StrConv Function Example

The first example converts text data stored in a byte array to a Unicode string:

Dim baBuffer(1 to 255) as Byte
Dim sText as String
sText = StrConv(baBuffer, vbUnicode)

The second example uses the StrConv function to convert a Unicode string to an ANSI string.

Dim i As Long
Dim x() As Byte
x = StrConv("ABCDEFG", vbFromUnicode)   ' Convert string.
For i = 0 To UBound(x)
   Debug.Print x(i)
Next


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

String$ Function

[Topic intentionally blank - content coming in later builds]


StrReverse Function

Returns a string in which the character order of a specified string is reversed.

StrReverse(expression)

The expression argument is the string whose characters are to be reversed. If expression is a zero-length string (""), a zero-length string is returned.

See Also


Switch Function

Evaluates a list of expressions and returns an Object value or an expression associated with the first expression in the list that is True.

Switch(expr-1, value-1[, expr-2, value-2 … [, expr-n,value-n]])

Parameters

expr
Required. Object expressiondefObjectExpression@veendf98.chm you want to evaluate.
value
Required. Value or expression to be returned if the corresponding expression is True.

Remarks

The Switch function argument list consists of pairs of expressions and values. The expressions are evaluated from left to right, and the value associated with the first expression to evaluate to True is returned. If the parts aren't properly paired, a run-time error occurs. For example, if expr-1 is True, Switch returns value-1. If expr-1 is False, but expr-2 is True, Switch returns value-2, and so on.

Switch returns a Null value if:

  • None of the expressions is True.
  • The first True expression has a corresponding value that is Null.

Switch evaluates all of the expressions, even though it returns only one of them. For this reason, you should watch for undesirable side effects. For example, if the evaluation of any expression results in a division by zero error, an error occurs.

See Also

Example


Switch Function Example

This example uses the Switch function to return the name of a language that matches the name of a city.

Function MatchUp (CityName As String)
   Matchup = Switch(CityName = "London", "English", CityName _
               = "Rome", "Italian", CityName = "Paris", "French")
End Function


SYD Function

Returns a Double specifying the sum-of-years' digits depreciation of an asset for a specified period.

SYD(cost, salvage, life, period)

Arguments

cost
Required. Double specifying initial cost of the asset.
salvage
Required. Double specifying value of the asset at the end of its useful life.
life
Required. Double specifying length of the useful life of the asset.
period
Required. Double specifying period for which asset depreciation is calculated.

Remarks

The life and period arguments must be expressed in the same units. For example, if life is given in months, period must also be given in months. All arguments must be positive numbers.

See Also

Example

DDB Function | FV Function | IPmt Function | IRR Function | MIRR Function | NPer Function | NPV Function | Pmt Function | PPmt Function | PV Function | Rate Function | SLN Function


SYD Function Example

This example uses the SYD function to return the depreciation of an asset for a specified period given the asset's initial cost (InitCost), the salvage value at the end of the asset's useful life (SalvageVal), and the total life of the asset in years (LifeTime). The period in years for which the depreciation is calculated is PDepr.

Dim Fmt, InitCost, SalvageVal, MonthLife, LifeTime, DepYear, PDepr
Const YEARMONTHS = 12   ' Number of months in a year.
Fmt = "###,##0.00"   ' Define money format.
InitCost = InputBox("What's the initial cost of the asset?")
SalvageVal = InputBox("What's the asset's value at the end of its life?")
MonthLife = InputBox("What's the asset's useful life in months?")
Do While MonthLife < YEARMONTHS   ' Ensure period is >= 1 year.
   MsgBox "Asset life must be a year or more."
   MonthLife = InputBox("What's the asset's useful life in months?")
Loop
LifeTime = MonthLife / YEARMONTHS   ' Convert months to years.
If LifeTime <> Int(MonthLife / YEARMONTHS) Then
   LifeTime = Int(LifeTime + 1)   ' Round up to nearest year.
End If
DepYear = CInt(InputBox("For which year do you want depreciation?"))
Do While DepYear < 1 Or DepYear > LifeTime
   MsgBox "You must enter at least 1 but not more than " & LifeTime
   DepYear = CInt(InputBox("For what year do you want depreciation?"))
Loop
PDepr = SYD(InitCost, SalvageVal, LifeTime, DepYear)
MsgBox "The depreciation for year " & DepYear & " is " & Format(PDepr, Fmt) & "."


Tab Function

Used with the Print # statement or the Print method to position output.

Tab[(n)]

The optional n argument is the column number moved to before displaying or printing the next expression in a list. If omitted, Tab moves the insertion point to the beginning of the next print zone. This allows Tab to be used instead of a comma in locales where the comma is used as a decimal separator.

Remarks

If the current print position on the current line is greater than n, Tab skips to the nth column on the next output line. If n is less than 1, Tab moves the print position to column 1. If n is greater than the output line width, Tab calculates the next print position using the formula:

n Mod width

For example, if width is 80 and you specify Tab(90), the next print will start at column 10 (the remainder of 90/80). If n is less than the current print position, printing begins on the next line at the calculated print position. If the calculated print position is greater than the current print position, printing begins at the calculated print position on the same line.

The leftmost print position on an output line is always 1. When you use the Print # statement to print to files, the rightmost print position is the current width of the output file, which you can set using the Width # statement.

Note Make sure your tabular columns are wide enough to accommodate wide letters.

When you use the Tab function with the Print method, the print surface is divided into uniform, fixed-width columns. The width of each column is an average of the width of all characters in the point size for the chosen font. However, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy. For example, the uppercase letter W occupies more than one fixed-width column, and the lowercase letter i occupies less than one fixed-width column.

See Also

Example


Tab Function Example

This example uses the Tab function to position output in a file and in the Immediate window.

' The Tab function can be used with the Print # statement.
Open "TESTFILE" For Output As #1   ' Open file for output.
' The second word prints at column 20.
Print #1, "Hello"; Tab(20); "World."
' If the argument is omitted, cursor is moved to the next print zone.
Print #1, "Hello"; Tab; "World"
Close #1   ' Close file.

The Tab function can also be used with the Print method. The following statement prints text starting at column 10.

Debug.Print Tab(10); "10 columns from start."


Tan Function

Returns a Double specifying the tangent of an angle.

Tan(number)

The required number argument is a Double or any valid numeric expression that expresses an angle in radians.

Remarks

Tan takes an angle and returns the ratio of two sides of a right triangle. The ratio is the length of the side opposite the angle divided by the length of the side adjacent to the angle.

To convert degrees to radians, multiply degrees by pi/180. To convert radians to degrees, multiply radians by 180/pi.

See Also

Example


Tan Function Example

This example uses the Tan function to return the tangent of an angle.

Dim MyAngle, MyCotangent
MyAngle = 1.3   ' Define angle in radians.
MyCotangent = 1 / Tan(MyAngle)   ' Calculate cotangent.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

TimeOfDay Function

Returns a DateTime indicating the current system time.

TimeOfDay

Remarks

To set the system time, use the TimeOfDay statement.

See Also

Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Timer Function

Returns a Double representing the number of seconds elapsed since midnight.

Timer

Remarks

The Timer function also returns fractional portions of a second.

See Also

Example


Timer Function Example

This example uses the Timer function to pause the application. The example also uses DoEvents to yield to other processes during the pause.

Dim PauseTime, Start, Finish, TotalTime
If (MsgBox("Press Yes to pause for 5 seconds", 4)) = vbYes Then
   PauseTime = 5   ' Set duration.
   Start = Timer   ' Set start time.
   Do While Timer < Start + PauseTime
      DoEvents   ' Yield to other processes.
   Loop
   Finish = Timer   ' Set end time.
   TotalTime = Finish - Start   ' Calculate total time.
   MsgBox "Paused for " & TotalTime & " seconds"
Else
   End
End If


TimeSerial Function

Returns an DateTime containing the time for a specific hour, minute, and second.

TimeSerial(hour, minute, second)

Arguments

hour
Required; Integer. Number between 0 (12:00 A.M.) and 23 (11:00 P.M.), inclusive, or a numeric expression.
minute
Required; Integer. Any numeric expression.
second
Required; Integer. Any numeric expression.

Remarks

To specify a time, such as 11:59:59, the range of numbers for each TimeSerial argument should be in the normal range for the unit, that is, 0–23 for hours and 0–59 for minutes and seconds. However, you can also specify relative times for each argument using any numeric expression that represents some number of hours, minutes, or seconds before or after a certain time. The following example uses expressions instead of absolute time numbers. The TimeSerial function returns a time for 15 minutes before (-15) six hours before noon (12 - 6), or 5:45:00 A.M.

TimeSerial(12 - 6, -15, 0)

When any argument exceeds the normal range for that argument, it increments to the next larger unit as appropriate. For example, if you specify 75 minutes, it is evaluated as one hour and 15 minutes. If any single argument is outside the range -2,147,483,648 to 2,147,483,647, an error occurs. If the time specified by the three arguments causes the date to fall outside the acceptable range of dates, an error occurs.

See Also

Example


TimeSerial Function Example

This example uses the TimeSerial function to return a time for the specified hour, minute, and second.

Dim MyTime
MyTime = TimeSerial(16, 35, 17)   ' MyTime contains serial
   ' representation of 4:35:17 PM.


TimeValue Function

Returns a DateTime containing the time.

TimeValue(time)

The required time argument is normally a string expression representing a time from 0:00:00 (12:00:00 A.M.) to 23:59:59 (11:59:59 P.M.), inclusive. However, time can also be any expression that represents a time in that range.

Remarks

You can enter valid times using a 12-hour or a 24-hour clock. For example, "2:24 P.M." and "14:24" are both valid time arguments.

If the time argument contains date information, TimeValue doesn't return it. However, if time includes invalid date information, an error occurs.

See Also

Example


TimeValue Function Example

This example uses the TimeValue function to convert a string to a time. You can also use date literals to directly assign a time to a Variant or Date variable, for example, MyTime = #4:35:17 PM#.

Dim MyTime
MyTime = TimeValue("4:35:17 PM")   ' Return a time.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Today Function

Returns a DateTime containing the current system date.

Today

Remarks

To set the system date, use the Today statement.See Also

Example


TypeName Function

Returns a String that provides information about a variable.

TypeName(varname)

The required varname argument is an Object containing any variable except a variable of a user-defined type.

Remarks

The string returned by TypeName can be any one of the following:

String returned | Variable
object type | An object whose type is objecttype
Byte | Byte value
Integer | Integer
Long | Long integer
Single | Single-precision floating-point number
Double | Double-precision floating-point number
Decimal | Decimal value
Date | Date value
String | String
Boolean | Boolean value
Error | An error value
Empty | Uninitialized
Null | No valid data
Object | An object
Unknown | An object whose type is unknown
Nothing | Object variable that doesn't refer to an object

If varname is an array, the returned string can be any one of the possible returned strings (orObject) with empty parentheses appended. For example, if varname is an array of integers, TypeName returns "Integer()".

See Also

Example

Data Type Summary | IsArray Function | IsDate Function | IsEmpty Function | IsError Function | IsNull Function | IsNumeric Function | IsObject Function


TypeName Function Example

This example uses the TypeName function to return information about a variable.

' Declare variables.
Dim NullVar, MyType, StrVar As String, IntVar As Integer, CurVar As Currency
Dim ArrayVar (1 To 5) As Integer
NullVar = Null   ' Assign Null value.
MyType = TypeName(StrVar)   ' Returns "String".
MyType = TypeName(IntVar)   ' Returns "Integer".
MyType = TypeName(CurVar)   ' Returns "Currency".
MyType = TypeName(NullVar)   ' Returns "Null".
MyType = TypeName(ArrayVar)   ' Returns "Integer()".


UBound Function

Returns a Long containing the largest available subscript for the indicated dimension of an array.

UBound(arrayname[, dimension])

The UBound function syntax has these parts:

Part | Description
arrayname | Required. Name of the array variable; follows standard variable naming conventions.
dimension | Optional; Long. Whole number indicating which dimension's upper bound is returned. Use 1 for the first dimension, 2 for the second, and so on. If dimension is omitted, 1 is assumed.

Remarks

The UBound function is used with the LBound function to determine the size of an array. Use the LBound function to find the lower limit of an array dimension.

UBound returns the following values for an array with these dimensions:

Dim A(1 To 100, 0 To 3, -3 To 4)

Statement | Return Value
UBound(A, 1) | 100
UBound(A, 2) | 3
UBound(A, 3) | 4

See Also

Example

Dim Statement | LBound Function | Public Statement | ReDim Statement

RaiseEvent Statement

Fires an event declared at module level within a class, form, or document.

RaiseEvent eventname [(argumentlist)]

The required eventname is the name of an event declared within the module and follows Basic variable naming conventions.

Arguments

eventname
Required. Name of the event to fire.
argumentlist
Optional. Comma-delimited list of variables, arrays, or expressions The argumentlist must be enclosed by parentheses. If there are no arguments, the parentheses must be omitted.

Remarks

If the event has not been declared within the module in which it is raised, an error occurs. The following fragment illustrates an event declaration and a procedure in which the event is raised.

' Declare an event at module level of a class module
Event LogonCompleted (UserName as String)

Sub
   ' Raise the event.
   RaiseEvent LogonCompleted ("AntoineJan")
End Sub

You can't use RaiseEvent to fire events that are not explicitly declared in the module. For example, if a form has a Click event, you can't fire its Click event using RaiseEvent. If you declare a Click event in the form module, it shadows the form’s own Click event. You can still invoke the form’s Click event using normal syntax for calling the event, but not using the RaiseEvent statement.

Event firing is done in the order that the connections are established. Since events can have ByRef parameters, a process that connects late may receive parameters that have been changed by an earlier event handler.

See Also

Example


UBound Function Example

This example uses the UBound function to determine the largest available subscript for the indicated dimension of an array.

Dim Upper
Dim MyArray(1 To 10, 5 To 15, 10 To 20)   ' Declare array variables.
Dim AnyArray(10)
Upper = UBound(MyArray, 1)   ' Returns 10.
Upper = UBound(MyArray, 3)   ' Returns 20.
Upper = UBound(AnyArray)   ' Returns 10.


UCase Function

Returns a String containing the specified string, converted to uppercase.

UCase(string)

The required string argument is any valid string expression.

Remarks

Only lowercase letters are converted to uppercase; all uppercase letters and nonletter characters remain unchanged.

See Also

Example

LCase Function


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

UCase$ Function

[Topic intentionally blank - content coming in later builds]


UCase Function Example

This example uses the UCase function to return an uppercase version of a string.

Dim LowerCase, UpperCase
LowerCase = "Hello World 1234"   ' String to convert.
UpperCase = UCase(LowerCase)   ' Returns "HELLO WORLD 1234".


Val Function

Returns the numbers contained in a string as a numeric value of appropriate type.

Val(string)

The required string argument is any valid string expression.

Remarks

The Val function stops reading the string at the first character it can't recognize as part of a number. Symbols and characters that are often considered parts of numeric values, such as dollar signs and commas, are not recognized. However, the function recognizes the radix prefixes &O (for octal) and &H (for hexadecimal). Blanks, tabs, and linefeed characters are stripped from the argument.

The following returns the value 1615198:

Val("    1615 198th Street N.E.")

In the code below, Val returns the decimal value -1 for the hexadecimal value shown:

Val("&HFFFF")
Note The Val function recognizes only the period (.) as a valid decimal separator. When different decimal separators are used, as in international applications, use CDbl instead to convert a string to a number.

See Also

Example


Val Function Example

This example uses the Val function to return the numbers contained in a string.

Dim MyValue
MyValue = Val("2457")   ' Returns 2457.
MyValue = Val(" 2 45 7")   ' Returns 2457.
MyValue = Val("24 and 57")   ' Returns 24.


Weekday Function

Returns an Integer containing a whole number representing the day of the week.

Weekday(date, [firstdayofweek])

Arguments

date
Required. DateTime.
firstdayofweek
Optional. A constant that specifies the first day of the week. If not specified, vbSunday is assumed.

Settings

The firstdayofweek argument has these settings:

Constant | Value | Description
UseSystemDayOfWeek | 0 | Use the day of the week specified in your system settings for the first day of the week
Sunday | 1 | Sunday (default)
Monday | 2 | Monday
Tuesday | 3 | Tuesday
Wednesday | 4 | Wednesday
Thursday | 5 | Thursday
Friday | 6 | Friday
Saturday | 7 | Saturday

Return Values

The Weekday function can return any of these values:

Constant | Value | Description
Sunday | 1 | Sunday
Monday | 2 | Monday
Tuesday | 3 | Tuesday
Wednesday | 4 | Wednesday
Thursday | 5 | Thursday
Friday | 6 | Friday
Saturday | 7 | Saturday

Remarks

If the Calendar property setting is Gregorian, the returned integer represents the Gregorian day of the week for the date argument. If the calendar is Hijri, the returned integer represents the Hijri day of the week for the date argument. For Hijri dates, the argument number is any numeric expression that can represent a date and/or time from 1/1/100 (Gregorian Aug 2, 718) through 4/3/9666 (Gregorian Dec 31, 9999).

See Also

Example


WeekdayName Function

Returns a string indicating the specified day of the week.

WeekdayName(weekday, abbreviate, firstdayofweek)

Arguments

weekday
Required. The numeric designation for the day of the week. Numeric value of each day depends on setting of the firstdayofweek setting.
abbreviate
Optional. Boolean value that indicates if the weekday name is to be abbreviated. If omitted, the default is False, which means that the weekday name is not abbreviated.
firstdayofweek
Optional. Numeric value indicating the first day of the week. See Settings section for values.

Settings

The firstdayofweek argument can have the following values:

Constant | Value | Description
UseSystemDayOfWeek | 0 | Use the day of the week specified in your system settings for the first day of the week.
Sunday | 1 | Sunday (default)
Monday | 2 | Monday
Tuesday | 3 | Tuesday
Wednesday | 4 | Wednesday
Thursday | 5 | Thursday
Friday | 6 | Friday
Saturday | 7 | Saturday

See Also

MonthName Function


Year Function

Returns an Integer containing a whole number representing the year.

Year(datetime)

The required datetime expression or any combination, that can represent a date.

Note If the Calendar property setting is Gregorian, the returned integer represents the Gregorian year for the date argument. If the calendar is Hijri, the returned integer represents the Hijri year for the date argument. For Hijri dates, the argument number is any numeric expression that can represent a date and/or time from 1/1/100 (Gregorian Aug 2, 718) through 4/3/9666 (Gregorian Dec 31, 9999).

See Also

Example


Year Function Example

This example uses the Year function to obtain the year from a specified date. In the development environment, the date literal is displayed in short date format using the locale settings of your code.

Dim MyDate, MyYear
MyDate = #February 12, 1969#   ' Assign a date.
MyYear = Year(MyDate)   ' MyYear contains 1969.


Keywords (Visual Basic for Applications)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Keywords (Visual Basic Language Reference)

Keywords by Task

As

Binary

ByRef

ByVal

Date

Else

Empty

Error

FALSE

For

Friend

Get

Input

Is

Len

Let

Lock

Me

Mid

New

Next

Nothing

Null

On

Option

Optional

ParamArray

Print

Private

Property

Public

Resume

Seek

Set

Static

Step

String

Then

Time

To

TRUE

WithEvents


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Addhandler

[Topic intentionally blank - content coming in later builds]


Arrays Keyword Summary

Action | Keywords
Verify an array. | IsArray
Create an array. | Array
Declare and initialize an array. | Dim, Private, Public, ReDim
Find the limits of an array. | LBound, UBound
Reinitialize an array. | Erase, ReDim

See Also

Arrays Keyword Summary | Collection Object Keyword Summary | Compiler Directive Keyword Summary | Control Flow Keyword Summary | Conversion Keyword Summary | Data Types Keyword Summary | Dates and Times Keyword Summary | Directories and Files Keyword Summary | Errors Keyword Summary | Financial Keyword Summary | Input and Output Keyword Summary | Math Keyword Summary | Miscellaneous Keyword Summary | Operators Keyword Summary | Registry Keyword Summary | String Manipulation Keyword Summary | Variables and Constants Keyword Summary


As <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

As

The As keyword is used in these contexts:

Const Statement

Declare Statement

Dim Statement

Function Statement

Name Statement

Open Statement

Private Statement

Property Statement

Protected Statement

Public Statement

ReDim Statement

Sub Statement


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Assembly

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Auto

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

BeginEpilogue

[Topic intentionally blank - content coming in later builds]


Binary <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Binary

The Binary keyword is used in these contexts:

Open Statement

Option Compare Statement


ByRef <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

ByRef

The ByRef keyword is used in these contexts:

Call Statement

Declare Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


ByVal <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

ByVal

The ByVal keyword is used in these contexts:

Call Statement

Declare Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Collection Object Keyword Summary

Action | Keywords
Create a Collection object. | Collection
Add an object to a collection. | Add
Remove an object from a collection. | Remove
Reference an item in a collection. | Item

See Also

Arrays Keyword Summary | Collection Object Keyword Summary | Compiler Directive Keyword Summary | Control Flow Keyword Summary | Conversion Keyword Summary | Data Types Keyword Summary | Dates and Times Keyword Summary | Directories and Files Keyword Summary | Errors Keyword Summary | Financial Keyword Summary | Input and Output Keyword Summary | Math Keyword Summary | Miscellaneous Keyword Summary | Operators Keyword Summary | Registry Keyword Summary | String Manipulation Keyword Summary | Variables and Constants Keyword Summary


Compiler Directive Keyword Summary

Action | Keywords
Define compiler constant. | #Const
Compile selected blocks of code. | #If...Then...#Else

See Also

Arrays Keyword Summary | Collection Object Keyword Summary | Compiler Directive Keyword Summary | Control Flow Keyword Summary | Conversion Keyword Summary | Data Types Keyword Summary | Dates and Times Keyword Summary | Directories and Files Keyword Summary | Errors Keyword Summary | Financial Keyword Summary | Input and Output Keyword Summary | Math Keyword Summary | Miscellaneous Keyword Summary | Operators Keyword Summary | Registry Keyword Summary | String Manipulation Keyword Summary | Variables and Constants Keyword Summary


Control Flow Keyword Summary

Action | Keywords
Branch. | GoTo, On Error
Exit or pause the program. | DoEvents, End, Exit, Stop
Loop. | Do...Loop, For...Next, For Each...Next, While...Wend, With
Make decisions. | Choose, If...Then...Else, Select Case, Switch
Use procedures. | Call, Function, Property Get, Property Let, Property Set, Sub

See Also

Arrays Keyword Summary | Collection Object Keyword Summary | Compiler Directive Keyword Summary | Control Flow Keyword Summary | Conversion Keyword Summary | Data Types Keyword Summary | Dates and Times Keyword Summary | Directories and Files Keyword Summary | Errors Keyword Summary | Financial Keyword Summary | Input and Output Keyword Summary | Math Keyword Summary | Miscellaneous Keyword Summary | Operators Keyword Summary | Registry Keyword Summary | String Manipulation Keyword Summary | Variables and Constants Keyword Summary


Conversion Keyword Summary

Action | Keywords
ANSI value to string. | Chr
String to lowercase or uppercase. | Format, LCase, Ucase
Date to serial number. | DateSerial, DateValue
Decimal number to other bases. | Hex, Oct
Number to string. | Format, Str
One data type to another. | CBool, CByte, CDate, CDbl, CDec, CInt, CLng, CSng, CStr, CVErr, Fix, Int
Date to day, month, weekday, or year. | Day, Month, Weekday, Year
Time to hour, minute, or second. | Hour, Minute, Second
String to ASCII value. | Asc
String to number. | Val
Time to serial number. | TimeSerial, TimeValue

See Also

Arrays Keyword Summary | Collection Object Keyword Summary | Compiler Directive Keyword Summary | Control Flow Keyword Summary | Conversion Keyword Summary | Data Types Keyword Summary | Dates and Times Keyword Summary | Directories and Files Keyword Summary | Errors Keyword Summary | Financial Keyword Summary | Input and Output Keyword Summary | Math Keyword Summary | Miscellaneous Keyword Summary | Operators Keyword Summary | Registry Keyword Summary | String Manipulation Keyword Summary | Type Conversion Functions | Variables and Constants Keyword Summary


Data Types Keyword Summary

Action | Keywords
Convert between data types. | CBool, CByte, CDate, CDbl, CDec, CInt, CLng, CSng, CStr, CVErr, Fix, Int
Set intrinsic data types. | Boolean, Byte, Date, Double, Integer, Long, Object(default), Single, String
Verify data types. | IsArray, IsDate, IsEmpty, IsError, IsNull, IsNumeric, IsObject

See Also

Arrays Keyword Summary | Collection Object Keyword Summary | Compiler Directive Keyword Summary | Control Flow Keyword Summary | Conversion Keyword Summary | Data Types Keyword Summary | Dates and Times Keyword Summary | Directories and Files Keyword Summary | Errors Keyword Summary | Financial Keyword Summary | Input and Output Keyword Summary | Math Keyword Summary | Miscellaneous Keyword Summary | Operators Keyword Summary | Registry Keyword Summary | String Manipulation Keyword Summary | Variables and Constants Keyword Summary


Date <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Date

The Date keyword is used in these contexts:

Date Data Type

Date Function

Date Statement


Dates and Times Keyword Summary

Action | Keywords
Get the current date or time. | Date, Now, Time
Perform date calculations. | DateAdd, DateDiff, DatePart
Return a date. | DateSerial, DateValue
Return a time. | TimeSerial, TimeValue
Set the date or time. | Date, Time
Time a process. | Timer

See Also

Arrays Keyword Summary | Collection Object Keyword Summary | Compiler Directive Keyword Summary | Control Flow Keyword Summary | Conversion Keyword Summary | Data Types Keyword Summary | Dates and Times Keyword Summary | Directories and Files Keyword Summary | Errors Keyword Summary | Financial Keyword Summary | Input and Output Keyword Summary | Math Keyword Summary | Miscellaneous Keyword Summary | Operators Keyword Summary | Registry Keyword Summary | String Manipulation Keyword Summary | Variables and Constants Keyword Summary


Directories and Files Keyword Summary

Action | Keywords
Change directory or folder. | ChDir
Change the drive. | ChDrive
Copy a file. | FileCopy
Make directory or folder. | MkDir
Remove directory or folder. | RmDir
Rename a file, directory, or folder. | Name
Return current path. | CurDir
Return file date/time stamp. | FileDateTime
Return file, directory, label attributes. | GetAttr
Return file length. | FileLen
Return file name or volume label. | Dir
Set attribute information for a file. | SetAttr

See Also

Arrays Keyword Summary | Collection Object Keyword Summary | Compiler Directive Keyword Summary | Control Flow Keyword Summary | Conversion Keyword Summary | Data Types Keyword Summary | Dates and Times Keyword Summary | Directories and Files Keyword Summary | Errors Keyword Summary | Financial Keyword Summary | Input and Output Keyword Summary | Math Keyword Summary | Miscellaneous Keyword Summary | Operators Keyword Summary | Registry Keyword Summary | String Manipulation Keyword Summary | Variables and Constants Keyword Summary


Else <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Else

The Else keyword is used in these contexts:

If...Then...Else Statement

Select Case Statement


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

ElseIf

[Topic intentionally blank - content coming in later builds]


Empty <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Empty

The Empty keyword is used as an Objectsubtype. It indicates an uninitialized variable value.

See Also

Object Data Type


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

EndPrologue

[Topic intentionally blank - content coming in later builds]


Error <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Error

The Error keyword is used in these contexts:

Error Function

Error Statement

On Error Statement


Errors Keyword Summary

Action | Keywords
Generate run-time errors. | Clear, Error, Raise
Get error messages. | Error
Provide error information. | Err
Return Error variant. | CVErr
Trap errors during run time. | On Error, Resume
Type verification. | IsError

See Also

Arrays Keyword Summary | Collection Object Keyword Summary | Compiler Directive Keyword Summary | Control Flow Keyword Summary | Conversion Keyword Summary | Data Types Keyword Summary | Dates and Times Keyword Summary | Directories and Files Keyword Summary | Errors Keyword Summary | Financial Keyword Summary | Input and Output Keyword Summary | Math Keyword Summary | Miscellaneous Keyword Summary | Operators Keyword Summary | Registry Keyword Summary | String Manipulation Keyword Summary | Variables and Constants Keyword Summary


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

ExternalSource

[Topic intentionally blank - content coming in later builds]


False <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

False

The False keyword has a value equal to 0.

See Also

Boolean Data Type | True


Financial Keyword Summary

Action | Keywords
Calculate depreciation. | DDB, SLN, SYD
Calculate future value. | FV
Calculate interest rate. | Rate
Calculate internal rate of return. | IRR, MIRR
Calculate number of periods. | NPer
Calculate payments. | IPmt, Pmt, PPmt
Calculate present value. | NPV, PV

See Also

Arrays Keyword Summary | Collection Object Keyword Summary | Compiler Directive Keyword Summary | Control Flow Keyword Summary | Conversion Keyword Summary | Data Types Keyword Summary | Dates and Times Keyword Summary | Directories and Files Keyword Summary | Errors Keyword Summary | Financial Keyword Summary | Input and Output Keyword Summary | Math Keyword Summary | Miscellaneous Keyword Summary | Operators Keyword Summary | Registry Keyword Summary | String Manipulation Keyword Summary | Variables and Constants Keyword Summary


For <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

For

The For keyword is used in these contexts:

For...Next Statement

For Each...Next Statement

Open Statement


Friend

Modifies the definition of a procedure in a form or class to make the procedure callable from modules that are outside the class but part of the project within which the class is defined.

[Private | Friend | Public] [Static] [Sub | Function | Property] procedurename

The required procedurename is the name of the procedure to be made visible throughout the project, but not visible to controllers of the class.

Remarks

Public procedures in a class can be called from anywhere, even by controllers of instances of the class. Declaring a procedure Private prevents controllers of the object from calling the procedure, but also prevents the procedure from being called from within the project in which the class itself is defined. Friend makes the procedure visible throughout the project, but not to a controller of an instance of the object. Friend can appear only in form modules and class modules, and can only modify procedure names, not variables or types. Procedures in a class can access the Friend procedures of all other classes in a project. Friend procedures don't appear in the type library of their class. A Friend procedure can't be late bound.

When placed in a class, the following code makes the member variable dblBalance accessible to all users of the class within the project. Any user of the class can get the value; only code within the project can assign a value to that variable.

Private dblBalance As Double

Public Property Get Balance() As Double
    Balance = dblBalance
End Property

Friend Property Let Balance(dblNewBalance As Double)
    dblBalance = dblNewBalance

End Property

See Also

Example


Get <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Get

The Get keyword is used in these contexts:

Get Statement

Property Get Statement


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Handles

[Topic intentionally blank - content coming in later builds]


Input <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Input

The Input keyword is used in these contexts:

Input Function

Input # Statement

Line Input # Statement

Open Statement


Input and Output Keyword Summary

Action | Keywords
Access or create a file. | Open
Close files. | Close, Reset
Control output appearance. | Format, Print, Print #, Spc, Tab, Width #
Copy a file. | FileCopy
Get information about a file. | EOF, FileAttr, FileDateTime, FileLen, FreeFile, GetAttr, Loc, LOF, Seek
Manage files. | Dir, Kill, Lock, Unlock, Name
Read from a file. | Get, Input, Input #, Line Input #
Return length of a file. | FileLen
Set or get file attributes. | FileAttr, GetAttr, SetAttr
Set read-write position in a file. | Seek
Write to a file. | Print #, Put, Write #

See Also

Arrays Keyword Summary | Collection Object Keyword Summary | Compiler Directive Keyword Summary | Control Flow Keyword Summary | Conversion Keyword Summary | Data Types Keyword Summary | Dates and Times Keyword Summary | Directories and Files Keyword Summary | Errors Keyword Summary | Financial Keyword Summary | Input and Output Keyword Summary | Math Keyword Summary | Miscellaneous Keyword Summary | Operators Keyword Summary | Registry Keyword Summary | String Manipulation Keyword Summary | Variables and Constants Keyword Summary


Is <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Is

The Is keyword is used in these contexts:

Is Operator

Select Case Statement


Keywords by Task

Category | Description
Arrays | Creating, defining, and using arrays.
Compiler Directives | Controlling compiler behavior.
Control Flow | Looping and controlling procedure flow.
Conversion | Converting numbers and data types.
Data Types | Data types and object subtypes.
Dates and Times | Converting and using date and time expressions.
Directories and Files | Controlling the file system and processing files.
Errors | Trapping and returning error values.
Financial | Performing financial calculations.
Input and Output | Receiving input and displaying or printing output.
Math | Performing trigonometric and other mathematical calculations.
Miscellaneous | Starting other applications and processing events.
Operators | Comparing expressions and other operations.
String Manipulation | Manipulating strings and string type data.
Variables and Constants | Declaring and defining variables and constants.

See Also

Arrays Keyword Summary | Collection Object Keyword Summary | Compiler Directive Keyword Summary | Control Flow Keyword Summary | Conversion Keyword Summary | Data Types Keyword Summary | Dates and Times Keyword Summary | Directories and Files Keyword Summary | Errors Keyword Summary | Financial Keyword Summary | Input and Output Keyword Summary | Math Keyword Summary | Miscellaneous Keyword Summary | Operators Keyword Summary | Registry Keyword Summary | String Manipulation Keyword Summary | Variables and Constants Keyword Summary


Len <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Len

The Len keyword is used in these contexts:

Len Function

Open Statement


Let <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Let

The Let keyword is used in these contexts:

Let Statement

Property Let Statement


Lock <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Lock

The Lock keyword is used in these contexts:

Lock, Unlock Statements

Open Statement


Math Keyword Summary

Action | Keywords
Derive trigonometric functions. | Atn, Cos, Sin, Tan
General calculations. | Exp, Log, Sqr
Generate random numbers. | Randomize, Rnd
Get absolute value. | Abs
Get the sign of an expression. | Sgn
Perform numeric conversions. | Fix, Int

See Also

Arrays Keyword Summary | Collection Object Keyword Summary | Compiler Directive Keyword Summary | Control Flow Keyword Summary | Conversion Keyword Summary | Data Types Keyword Summary | Dates and Times Keyword Summary | Directories and Files Keyword Summary | Errors Keyword Summary | Financial Keyword Summary | Input and Output Keyword Summary | Math Keyword Summary | Miscellaneous Keyword Summary | Operators Keyword Summary | Registry Keyword Summary | String Manipulation Keyword Summary | Variables and Constants Keyword Summary


Me <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Me

The Me keyword behaves like an implicitly declared variable. When a class can have more than one instance, Me provides a way to refer to the specific instance of the class where the code is executing. Using Me is particularly useful for passing information about the currently executing instance of a class to a procedure in another module. For example, suppose you have the following procedure in a module:

Sub ChangeFormColor(FormName As Form)
   FormName.BackColor = RGB(Rnd * 256, Rnd * 256, Rnd * 256)
End Sub

You can call this procedure and pass the current instance of the Form class as an argument using the following statement:

ChangeFormColor Me

See Also

Set Statement | Understanding Scope and Visibility | Understanding the Lifetime of Variables


Mid <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Mid

The Mid keyword is used in these contexts:

Mid Function

Mid Statement


Miscellaneous Keyword Summary

Action | Keywords
Process pending events. | DoEvents
Run other programs. | AppActivate, Shell
Send keystrokes to an application. | SendKeys
Sound a beep from computer. | Beep
System. | Environ
Provide a command-line string. | Command
Automation. | CreateObject, GetObject
Color. | QBColor, RGB

See Also

Arrays Keyword Summary | Collection Object Keyword Summary | Compiler Directive Keyword Summary | Control Flow Keyword Summary | Conversion Keyword Summary | Data Types Keyword Summary | Dates and Times Keyword Summary | Directories and Files Keyword Summary | Errors Keyword Summary | Financial Keyword Summary | Input and Output Keyword Summary | Math Keyword Summary | Miscellaneous Keyword Summary | Operators Keyword Summary | Registry Keyword Summary | String Manipulation Keyword Summary | Variables and Constants Keyword Summary


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

MustInherit

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

MyBase

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

MyClass

[Topic intentionally blank - content coming in later builds]


New <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

New

The New keyword is used in these contexts:

Dim Statement

Private Statement

Public Statement

Set Statement


Next <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Next

The Next keyword is used in these contexts:

For...Next Statement

For Each...Next Statement

On Error Statement

Resume Statement


Nothing <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Nothing

The Nothing keyword is used to disassociate an object variable from an actual object. Use the Set statement to assign Nothing to an object variable. For example:

Set MyObject = Nothing

Several object variables can refer to the same actual object. When Nothing is assigned to an object variable, that variable no longer refers to an actual object. When several object variables refer to the same object, memory and system resources associated with the object to which the variables refer are released only after all of them have been set to Nothing, either explicitly using Set, or implicitly after the last object variable set to Nothing goes out of scope.

See Also

Dim Statement | Private Statement | Public Statement | Set Statement | Understanding Scope and Visibility | Understanding the Lifetime of Variables


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

NotInheritable

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

NotOverridable

[Topic intentionally blank - content coming in later builds]


Null <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Null

The Null keyword is used as a Variant subtype. It indicates that a variable contains no valid data.

See Also

Variant Data Type | VarType Function


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Off

[Topic intentionally blank - content coming in later builds]


On <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

On

The On keyword is used in this context:

On Error Statement


Operators Keyword Summary

Action | Keywords
Arithmetic. | ^, –, *, /, \, Mod, +, &, =
Comparison. | =, <>, <, >, <=, >=, Like, Is
Logical operations. | Not, And, Or, Xor, Eqv, Imp BitAnd BitNot BitOr

See Also

Arrays Keyword Summary | Collection Object Keyword Summary | Compiler Directive Keyword Summary | Control Flow Keyword Summary | Conversion Keyword Summary | Data Types Keyword Summary | Dates and Times Keyword Summary | Directories and Files Keyword Summary | Errors Keyword Summary | Financial Keyword Summary | Input and Output Keyword Summary | Math Keyword Summary | Miscellaneous Keyword Summary | Operators Keyword Summary | Registry Keyword Summary | String Manipulation Keyword Summary | Variables and Constants Keyword Summary


Option <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Option

The Option keyword is used in these contexts:

Option Compare Statement

Option Strict Statement


Optional <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Optional

The Optional keyword is used in these contexts:

Declare Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Overridable

[Topic intentionally blank - content coming in later builds]


ParamArray <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

ParamArray

The ParamArray keyword is used in these contexts:

Declare Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Sub Statement


Print <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Print

The Print keyword is used in these contexts:

Print Method

Print # Statement


Private <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Private

The Private keyword is used in these contexts:

Const Statement

Declare Statement

Enum Statement

Function Statement

Private Statement

Property Statement

Protected Statement

Sub Statement


Property <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Property

The Property keyword is used in these contexts:

Property Statement


Public <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Public

The Public keyword is used in these contexts:

Const Statement

Declare Statement

Enum Statement

Event Statement

Function Statement

Property Get Statement

Property Let Statement

Property Set Statement

Public Statement

Sub Statement


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

ReadOnly

[Topic intentionally blank - content coming in later builds]


Registry Keyword Summary

Action | Keywords
Delete program settings. | DeleteSetting
Read program settings. | GetSetting, GetAllSettings
Save program settings. | SaveSetting

See Also

Arrays Keyword Summary | Collection Object Keyword Summary | Compiler Directive Keyword Summary | Control Flow Keyword Summary | Conversion Keyword Summary | Data Types Keyword Summary | Dates and Times Keyword Summary | Directories and Files Keyword Summary | Errors Keyword Summary | Financial Keyword Summary | Input and Output Keyword Summary | Math Keyword Summary | Miscellaneous Keyword Summary | Operators Keyword Summary | Registry Keyword Summary | String Manipulation Keyword Summary | Variables and Constants Keyword Summary


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

RemoveHandler

[Topic intentionally blank - content coming in later builds]


Resume <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Resume

The Resume keyword is used in these contexts:

On Error Statement

Resume Statement


Seek <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Seek

The Seek keyword is used in these contexts:

Seek Function

Seek Statement


Step <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Step

The Step keyword is used in these contexts:

For...Next Statement


String <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

String

The String keyword is used in these contexts:

String Data Type

String Function


String Manipulation Keyword Summary

Action | Keywords
Compare two strings | StrComp
Convert strings | StrConv
Convert to lowercase or uppercase | Format, Lcase, Ucase
Create string of repeating characters | Space, String
Find the length of a string | Len
Format a string | Format
Justify a string | LSet, Rset
Manipulate strings | InStr, Left, LTrim, Mid, Right, RTrim, Trim
Set string comparison rules | Option Compare
Work with ASCII and ANSI values | Asc, Chr
Replace a specified substring with another substring | Replace
Return a string array based on a specified filter criteria | Filter
Return a specified number of substrings | Split

See Also

Arrays Keyword Summary | Collection Object Keyword Summary | Compiler Directive Keyword Summary | Control Flow Keyword Summary | Conversion Keyword Summary | Data Types Keyword Summary | Dates and Times Keyword Summary | Directories and Files Keyword Summary | Errors Keyword Summary | Financial Keyword Summary | Input and Output Keyword Summary | Math Keyword Summary | Miscellaneous Keyword Summary | Operators Keyword Summary | Registry Keyword Summary | String Manipulation Keyword Summary | Variables and Constants Keyword Summary


Then <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Then

The Then keyword is used in these contexts:

#If...Then...#Else Directive

If...Then...Else Statement


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Throw

[Topic intentionally blank - content coming in later builds]


Time <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Time

The Time keyword is used in these contexts:

Time Function

Time Statement


To <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

To

The To keyword is used in these contexts:

For...Next Statement

Lock, Unlock Statements

Select Case Statement


True <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

True

The True keyword has a value equal to -1.

See Also

Boolean Data Type | False


Variables and Constants Keyword Summary

Action | Keywords
Assign value. | Let
Declare variables or constants. | Const, Dim, Private, Public, New
Get information about an object. | IsArray, IsDate, IsEmpty, IsError, IsNull, IsNumeric, IsObject, TypeName
Refer to current object. | Me
Require explicit variable declarations. | Option Strict

See Also

Arrays Keyword Summary | Collection Object Keyword Summary | Compiler Directive Keyword Summary | Control Flow Keyword Summary | Conversion Keyword Summary | Data Types Keyword Summary | Dates and Times Keyword Summary | Directories and Files Keyword Summary | Errors Keyword Summary | Financial Keyword Summary | Input and Output Keyword Summary | Math Keyword Summary | Miscellaneous Keyword Summary | Operators Keyword Summary | Registry Keyword Summary | String Manipulation Keyword Summary | Variables and Constants Keyword Summary


WithEvents <keyword>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

WithEvents

The WithEvents keyword is used in these contexts:

Dim Statement

Private Statement

Public Statement


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

WriteOnly

[Topic intentionally blank - content coming in later builds]


Methods (Visual Basic for Applications)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Methods (Visual Basic Language Reference)

Add Method

Add Method (Dictionary)

Add Method (Folders)

Assert Method

BuildPath Method

Clear Method

Close Method

Copy Method

CopyFile Method

CopyFolder Method

CreateFolder Method

CreateTextFile Method

Delete Method

DeleteFile Method

DeleteFolder Method

DriveExists Method

Exists Method

FileExists Method

FolderExists Method

GetAbsolutePathName Method

GetBaseName Method

GetDrive Method

GetDriveName Method

GetExtensionName Method

GetFile Method

GetFileName Method

GetFolder Method

GetParentFolderName Method

GetSpecialFolder Method

GetTempName Method

Item Method

Items Method

Keys Method

Move Method

MoveFile Method

MoveFolder Method

OpenAsTextStream Method

OpenTextFile Method

Print Method

Raise Method

Read Method

ReadAll Method

ReadLine Method

Remove Method

Remove Method

RemoveAll Method

Skip Method

SkipLine Method

WhatsThisMode Method

Write Method

WriteBlankLines Method

WriteLine Method


Add Method (Visual Basic for Applications)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Add Method

Adds a member to a Collection object.

object.Add (item, key, before, after)

Arguments

object
Required. An object expression that evaluates to an object in the Applies To list.
item
Required. An Object of any type that specifies the member to add to the collection.
key
Optional. A unique string expression that specifies a key string that can be used, instead of a positional index, to access a member of the collection.
before
Optional. An expression that specifies a relative position in the collection. The member to be added is placed in the collection before the member identified by the before argument. If a numeric expression, before must be a number from 1 to the value of the collection's Count property. If a string expression, before must correspond to the key specified when the member being referred to was added to the collection. You can specify a before position or an after position, but not both.
after
Optional. An expression that specifies a relative position in the collection. The member to be added is placed in the collection after the member identified by the after argument. If numeric, after must be a number from 1 to the value of the collection's Count property. If a string, after must correspond to the key specified when the member referred to was added to the collection. You can specify a before position or an after position, but not both.

Remarks

Whether the before or after argument is a string expression or numeric expression, it must refer to an existing member of the collection, or an error occurs.

An error also occurs if a specified key duplicates the key for an existing member of the collection.

See Also

Example

AddFromFile Method | AddFromGuid Method | AddFromString Method | Item Method | Remove Method | Remove Method (VBA Add-In Object Model)

Applies To: Collection Object


Add Method (Dictionary)

Adds a key and item pair to a Dictionary object.

object.Add (key, item)

The Add method has the following parts:

Arguments

object
Required. Always the name of a Dictionary object.
key
Required. The key associated with the item being added.
item
Required. The item associated with the key being added.

Remarks

An error occurs if the key already exists.

See Also

Add Method (Folders) | Exists Method | Items Method | Keys Method | Remove Method | RemoveAll Method

Applies To: Dictionary Object


AddFolders Method

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Add Method (Folders)

Adds a new Folder to a Folders collection.

object.Add folderName

Arguments

object
Required. Always the name of a Folders collection.
folderName
Required. The name of the new Folder being added.

Remarks

An error occurs if the folderName already exists.

See Also

Add Method (Dictionary)

Applies To: Folders Collection


BuildPath Method

Appends a name to an existing path.

object.BuildPath(path, name)

Arguments

object
Required. Always the name of a FileSystemObject.
path
Required. Existing path to which name is appended. Path can be absolute or relative and need not specify an existing folder.
name
Required. Name being appended to the existing path.

Remarks

The BuildPath method inserts an additional path separator between the existing path and the name, only if necessary.

See Also

Applies To: FileSystemObject Object


Clear Method

Clears all property settings of the Err object.

object.Clear

The object is always the Err object.

Remarks

Use Clear to explicitly clear the Err object after an error has been handled, for example, when you use deferred error handling with On Error Resume Next. The Clear method is called automatically whenever any of the following statements is executed:

  • Any type of Resume statement
  • Exit Sub, Exit Function, Exit Property
  • Any On Error statement
Note The On Error Resume Next construct may be preferable to On Error GoTo when handling errors generated during access to other objects. Checking Err after each interaction with an object removes ambiguity about which object was accessed by the code. You can be sure which object placed the error code in Err.Number, as well as which object originally generated the error (the object specified in Err.Source).

See Also

Example

Description Property | Err Object | HelpContext Property | HelpContextID Property (VBA Add-In Object Model) | HelpFile Property | LastDLLError Property | Number Property | On Error Statement | Raise Method | Source Property

Applies To: BindingCollection Object | DataMembers Collection | Err Object | ExportFormats Collection | Licenses Collection


Clear Method Example

This example uses the Err object's Clear method to reset the numeric properties of the Err object to zero and its string properties to zero-length strings. If Clear were omitted from the following code, the error message dialog box would be displayed on every iteration of the loop (after an error occurs) whether or not a successive calculation generated an error. You can single-step through the code to see the effect.

Dim Result(10) As Integer   ' Declare array whose elements
         ' will overflow easily.
Dim indx
On Error Resume Next   ' Defer error trapping.
Do Until indx = 10
   ' Generate an occasional error or store result if no error.
   Result(indx) = Rnd * indx * 20000
   If Err.Number <> 0 Then
      MsgBox Err, , "Error Generated: ", Err.HelpFile, Err.HelpContext
      Err.Clear   ' Clear Err object properties.
   End If
   indx = indx + 1
Loop


Close Method (FileSystemObject object)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Close Method

Closes an open TextStream file.

object.Close

The object is always the name of a TextStream object.

See Also

Read Method | ReadAll Method | ReadLine Method | Skip Method | SkipLine Method | Write Method | WriteBlankLines Method | WriteLine Method

Applies To: TextStream Object


Copy Method

Copies a specified file or folder from one location to another.

object.Copy destination[, overwrite]

Arguments

object
Required. Always the name of a File or Folder object.
destination
Required. Destination where the file or folder is to be copied. Wildcard characters are not allowed.
overwrite
Optional. Boolean value that is True (default) if existing files or folders are to be overwritten; False if they are not.

Remarks

The results of the Copy method on a File or Folder are identical to operations performed using FileSystemObject.CopyFile or FileSystemObject.CopyFolder where the file or folder referred to by object is passed as an argument. You should note, however, that the alternative methods are capable of copying multiple files or folders.

See Also

CopyFile Method | CopyFolder Method | Delete Method | Move Method | OpenAsTextStream MethodApplies To: File Object | Folder Object


CopyFile Method

Copies one or more files from one location to another.

object.CopyFile source, destination[, overwrite]

Arguments

object
Required. The object is always the name of a FileSystemObject.
source
Required. Character string file specification, which can include wildcard characters, for one or more files to be copied.
destination
Required. Character string destination where the file or files from source are to be copied. Wildcard characters are not allowed.
overwrite
Optional. Boolean value that indicates if existing files are to be overwritten. If True, files are overwritten; if False, they are not. The default is True. Note that CopyFile will fail if destination has the read-only attribute set, regardless of the value of overwrite.

Remarks

Wildcard characters can only be used in the last path component of the source argument. For example, you can use:

FileSystemObject.CopyFile "c:\mydocuments\letters\*.doc", "c:\tempfolder\"

But you can't use:

FileSystemObject.CopyFile "c:\mydocuments\*\R1???97.xls", "c:\tempfolder"

If source contains wildcard characters or destination ends with a path separator (\), it is assumed that destination is an existing folder in which to copy matching files. Otherwise, destination is assumed to be the name of a file to create. In either case, three things can happen when an individual file is copied.

  • If destination does not exist, source gets copied. This is the usual case.
  • If destination is an existing file, an error occurs if overwrite is False. Otherwise, an attempt is made to copy source over the existing file.
  • If destination is a directory, an error occurs.

An error also occurs if a source using wildcard characters doesn't match any files. The CopyFile method stops on the first error it encounters. No attempt is made to roll back or undo any changes made before an error occurs.

See Also

Copy Method | CopyFolder Method | DeleteFile Method | MoveFile MethodApplies To: FileSystemObject Object


CopyFolder Method

Recursively copies a folder from one location to another.

object.CopyFolder source, destination[, overwrite]

Arguments

object
Required. Always the name of a FileSystemObject.
source
Required. Character string folder specification, which can include wildcard characters, for one or more folders to be copied.
destination
Required. Character string destination where the folder and subfolders from source are to be copied. Wildcard characters are not allowed.
overwrite
Optional. Boolean value that indicates if existing folders are to be overwritten. If True, files are overwritten; if False, they are not. The default is True.

Remarks

Wildcard characters can only be used in the last path component of the source argument. For example, you can use:

FileSystemObject.CopyFolder "c:\mydocuments\letters\*", "c:\tempfolder\"

But you can't use:

FileSystemObject.CopyFolder "c:\mydocuments\*\*", "c:\tempfolder\"

If source contains wildcard characters or destination ends with a path separator (\), it is assumed that destination is an existing folder in which to copy matching folders and subfolders. Otherwise, destination is assumed to be the name of a folder to create. In either case, four things can happen when an individual folder is copied.

  • If destination does not exist, the source folder and all its contents gets copied. This is the usual case.
  • If destination is an existing file, an error occurs.
  • If destination is a directory, an attempt is made to copy the folder and all its contents. If a file contained in source already exists in destination, an error occurs if overwrite is False. Otherwise, it will attempt to copy the file over the existing file.
  • If destination is a read-only directory, an error occurs if an attempt is made to copy an existing read-only file into that directory and overwrite is False.

An error also occurs if a source using wildcard characters doesn't match any folders.

The CopyFolder method stops on the first error it encounters. No attempt is made to roll back any changes made before an error occurs.

See Also

Copy Method | CopyFile Method | CreateFolder Method | DeleteFolder Method | MoveFolder MethodApplies To: FileSystemObject Object


CreateFolder Method

Creates a folder.

object.CreateFolder(foldername)

Arguments

object
Required. Always the name of a FileSystemObject.
foldername
Required. String expression that identifies the folder to create.

Remarks

An error occurs if the specified folder already exists.

See Also

CopyFolder Method | CreateTextFile Method | DeleteFolder Method | MoveFolder Method

Applies To: FileSystemObject Object


CreateTextFile Method

Creates a specified file name and returns a TextStream object that can be used to read from or write to the file.

object.CreateTextFile(filename[, overwrite[, unicode]])

Arguments

object
Required. Always the name of a FileSystemObject or Folder object.
filename
Required. String expression that identifies the file to create.
overwrite
Optional. Boolean value that indicates if an existing file can be overwritten. The value is True if the file can be overwritten; False if it can't be overwritten. If omitted, existing files are not overwritten.
unicode
Optional. Boolean value that indicates whether the file is created as a Unicode or ASCII file. The value is True if the file is created as a Unicode file; False if it's created as an ASCII file. If omitted, an ASCII file is assumed.

Remarks

The following code illustrates how to use the CreateTextFile method to create and open a text file:

Sub CreateAfile
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set a = fs.CreateTextFile("c:\testfile.txt", True)
    a.WriteLine("This is a test.")
    a.Close
End Sub

If the overwrite argument is False, or is not provided, for a filename that already exists, an error occurs.

See Also

CopyFile Method | DeleteFile Method | OpenAsTextStream Method | OpenTextFile MethodApplies To: FileSystemObject Object | Folder Object


Delete Method

Deletes a specified file or folder.

object.Delete force

Arguments

object
Required. Always the name of a File or Folder object.
force
Optional. Boolean value that is True if files or folders with the read-only attribute set are to be deleted; False (default) if they are not.

Remarks

An error occurs if the specified file or folder does not exist.

The results of the Delete method on a File or Folder are identical to operations performed using FileSystemObject.DeleteFile or FileSystemObject.DeleteFolder.

The Delete method does not distinguish between folders that have contents and those that do not. The specified folder is deleted regardless of whether or not it has contents.

See Also

Copy Method | DeleteFile Method | DeleteFolder Method | Move Method | OpenAsTextStream Method

Applies To: File Object | Folder Object


DeleteFile Method

Deletes a specified file.

object.DeleteFile filespec[, force]

Arguments

object
Required. Always the name of a FileSystemObject.
filespec
Required. The name of the file to delete. The filespec can contain wildcard characters in the last path component.
force
Optional. Boolean value that is True if files with the read-only attribute set are to be deleted; False (default) if they are not.

Remarks

An error occurs if no matching files are found. The DeleteFile method stops on the first error it encounters. No attempt is made to roll back or undo any changes that were made before an error occurred.

See Also

CopyFile Method | Delete Method | DeleteFolder Method | MoveFile Method

Applies To: FileSystemObject Object


DeleteFolder Method

Deletes a specified folder and its contents.

object.DeleteFolder folderspec[, force]

Arguments

object
Required. Always the name of a FileSystemObject.
folderspec
Required. The name of the folder to delete. The folderspec can contain wildcard characters in the last path component.
force
Optional. Boolean value that is True if folders with the read-only attribute set are to be deleted; False (default) if they are not.

Remarks

The DeleteFolder method does not distinguish between folders that have contents and those that do not. The specified folder is deleted regardless of whether or not it has contents.

An error occurs if no matching folders are found. The DeleteFolder method stops on the first error it encounters. No attempt is made to roll back or undo any changes that were made before an error occurred.

See Also

CopyFolder Method | CreateFolder Method | Delete Method | DeleteFile Method | MoveFolder MethodApplies To: FileSystemObject Object


DriveExists Method

Returns True if the specified drive exists; False if it does not.

object.DriveExists(drivespec)

Arguments

object
Required. Always the name of a FileSystemObject.
drivespec
Required. A drive letter or a complete path specification.

Remarks

For drives with removable media, the DriveExists method returns True even if there are no media present. Use the IsReady property of the Drive object to determine if a drive is ready.

See Also

FileExists Method | FolderExists Method

Applies To: FileSystemObject Object


Exists Method

Returns True if a specified key exists in the Dictionary object; False if it does not.

object.Exists(key)

Arguments

object
Required. Always the name of a Dictionary object.
key
Required. Key value being searched for in the Dictionary object.

See Also

Add Method (Dictionary) | Items Method | Keys Method | Remove Method | RemoveAll Method

Applies To: Dictionary Object


FileExists Method

Returns True if a specified file exists; False if it does not.

object.FileExists(filespec)

Arguments

object
Required. Always the name of a FileSystemObject.
filespec
Required. The name of the file whose existence is to be determined. A complete path specification (either absolute or relative) must be provided if the file isn't expected to exist in the current folder.

See Also

DriveExists Method | FolderExists Method

Applies To: FileSystemObject Object


FolderExists Method

Returns True if a specified folder exists; False if it does not.

object.FolderExists(folderspec)

Arguments

object
Required. Always the name of a FileSystemObject.
folderspec
Required. The name of the folder whose existence is to be determined. A complete path specification (either absolute or relative) must be provided if the folder isn't expected to exist in the current folder.

See Also

DriveExists Method | FileExists MethodApplies To: FileSystemObject Object


GetAbsolutePathName Method

Returns a complete and unambiguous path from a provided path specification.

object.GetAbsolutePathName(pathspec)

Arguments

object
Required. Always the name of a FileSystemObject.
pathspec
Required. Path specification to change to a complete and unambiguous path.

Remarks

A path is complete and unambiguous if it provides a complete reference from the root of the specified drive. A complete path can only end with a path separator character (\) if it specifies the root folder of a mapped drive.

Assuming the current directory is c:\mydocuments\reports, the following table illustrates the behavior of the GetAbsolutePathName method.

pathspec | Returned path
"c:" | "c:\mydocuments\reports"
"c:.." | "c:\mydocuments"
"c:\\\" | "c:\"
"c:*.*\may97" | "c:\mydocuments\reports\*.*\may97"
"region1" | "c:\mydocuments\reports\region1"
"c:\..\..\mydocuments" | "c:\mydocuments"

See Also

BuildPath Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder Method | GetTempName MethodApplies To: FileSystemObject Object


GetBaseName Method

Returns a string containing the base name of the last component, less any file extension, in a path.

object.GetBaseName(path)

Arguments

object
Required. Always the name of a FileSystemObject.
path
Required. The path specification for the component whose base name is to be returned.

Remarks

The GetBaseName method returns a zero-length string ("") if no component matches the path argument.

Note The GetBaseName method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.

See Also

BuildPath Method | GetAbsolutePathName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder Method | GetTempName MethodApplies To: FileSystemObject Object


GetDrive Method

Returns a Drive object corresponding to the drive in a specified path.

object.GetDrive drivespec

Arguments

object
Required. Always the name of a FileSystemObject.
drivespec
Required. The drivespec argument can be a drive letter (c), a drive letter with a colon appended (c:), a drive letter with a colon and path separator appended (c:\), or any network share specification (\\computer2\share1).

Remarks

For network shares, a check is made to ensure that the share exists.

An error occurs if drivespec does not conform to one of the accepted forms or does not exist.

To call the GetDrive method on a normal path string, use the following sequence to get a string that is suitable for use as drivespec:

DriveSpec = GetDriveName(GetAbsolutePathName(Path))

See Also

Drive Object | DriveExists Method | GetAbsolutePathName Method | GetBaseName Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder Method | GetTempName MethodApplies To: FileSystemObject Object


GetDriveName Method

Returns a string containing the name of the drive for a specified path.

object.GetDriveName(path)

Arguments

object
Required. Always the name of a FileSystemObject.
path
Required. The path specification for the component whose drive name is to be returned.

Remarks

The GetDriveName method returns a zero-length string ("") if the drive can't be determined.

Note The GetDriveName method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.

See Also

BuildPath Method | DriveExists Method | GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder Method | GetTempName MethodApplies To: FileSystemObject Object


GetExtensionName Method

Returns a string containing the extension name for the last component in a path.

object.GetExtensionName(path)

Arguments

object
Required. Always the name of a FileSystemObject.
path
Required. The path specification for the component whose extension name is to be returned.

Remarks

For network drives, the root directory (\) is considered to be a component.

The GetExtensionName method returns a zero-length string ("") if no component matches the path argument.

See Also

BuildPath Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetFile Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder Method | GetTempName MethodApplies To: FileSystemObject Object


GetFile Method

Returns a File object corresponding to the file in a specified path.

object.GetFile(filespec)

Arguments

object
Required. Always the name of a FileSystemObject.
filespec
Required. The filespec is the path (absolute or relative) to a specific file.

Remarks

An error occurs if the specified file does not exist.

See Also

FileExists Method | GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFileName Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder Method | GetTempName Method | MoveFile MethodApplies To: FileSystemObject Object


GetFileName Method

Returns the last component of specified path that is not part of the drive specification.

object.GetFileName(pathspec)

Arguments

object
Required. Always the name of a FileSystemObject.
pathspec
Required. The path (absolute or relative) to a specific file.

Remarks

The GetFileName method returns a zero-length string ("") if pathspec does not end with the named component.

Note The GetFileName method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.

See Also

BuildPath Method | FileExists Method | GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder Method | GetTempName Method | MoveFile MethodApplies To: FileSystemObject Object


GetFolder Method

Returns a Folder object corresponding to the folder in a specified path.

object.GetFolder(folderspec)

Arguments

object
Required. Always the name of a FileSystemObject.
folderspec
Required. The folderspec is the path (absolute or relative) to a specific folder.

Remarks

An error occurs if the specified folder does not exist.

See Also

FolderExists Method | GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetParentFolderName Method | GetSpecialFolder Method | GetTempName Method | MoveFolder MethodApplies To: FileSystemObject Object


GetParentFolderName Method

Returns a string containing the name of the parent folder of the last component in a specified path.

object.GetParentFolderName(path)

Arguments

object
Required. Always the name of a FileSystemObject.
path
Required. The path specification for the component whose parent folder name is to be returned.

Remarks

The GetParentFolderName method returns a zero-length string ("") if there is no parent folder for the component specified in the path argument.

Note The GetParentFolderName method works only on the provided path string. It does not attempt to resolve the path, nor does it check for the existence of the specified path.

See Also

BuildPath Method | FolderExists Method | GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFolder Method | GetSpecialFolder Method | GetTempName Method | MoveFolder MethodApplies To: FileSystemObject Object


GetSpecialFolder Method

Returns the special folder specified.

object.GetSpecialFolder(folderspec)

Arguments

object
Required. Always the name of a FileSystemObject.
folderspec
Required. The name of the special folder to be returned. Can be any of the constants shown in the Settings section.

Settings

The folderspec argument can have any of the following values:

Constant | Value | Description
WindowsFolder | 0 | The Windows folder contains files installed by the Windows operating system.
SystemFolder | 1 | The System folder contains libraries, fonts, and device drivers.
TemporaryFolder | 2 | The Temp folder is used to store temporary files. Its path is found in the TMP environment variable.

See Also

GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFolder Method | GetParentFolderName Method | GetTempName MethodApplies To: FileSystemObject Object


GetTempName Method

Returns a randomly generated temporary file or folder name that is useful for performing operations that require a temporary file or folder.

object.GetTempName

The optional object is always the name of a FileSystemObject.

Remarks

The GetTempName method does not create a file. It provides only a temporary file name that can be used with CreateTextFile to create a file.

See Also

BuildPath Method | GetAbsolutePathName Method | GetBaseName Method | GetDrive Method | GetDriveName Method | GetExtensionName Method | GetFile Method | GetFileName Method | GetFolder Method | GetParentFolderName Method | GetSpecialFolder MethodApplies To: FileSystemObject Object


Item Method

Returns a specific member of a Collection object either by position or by key.

object.Item(index)

Arguments

object
Required. An object expression that evaluates to an object in the Applies To list.
index
Required. An expression that specifies the position of a member of the collection. If a numeric expression, index must be a number from 1 to the value of the collection's Count property. If a string expression, index must correspond to the key argument specified when the member referred to was added to the collection.

Remarks

If the value provided as index doesn’t match any existing member of the collection, an error occurs.

The Item method is the default method for a collection. Therefore, the following lines of code are equivalent:

Print MyCollection(1)
Print MyCollection.Item(1)

See Also

Example

Add Method | Caption Property | Count Property | Count Property | Name Property (VBA Add-In Object Model) | Remove Method

Applies To: Collection Object | Controls Collection | SelBookmarks Collection | Splits Collection


Items Method

Returns an array containing all the items in a Dictionary object.

object.Items

The object is always the name of a Dictionary object.

Remarks

The following code illustrates use of the Items method:

Dim a, d, i             'Create some variables
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"     'Add some keys and items
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
a = d.Items             'Get the items
For i = 0 To d.Count -1 'Iterate the array
    Print a(i)          'Print item
Next
...

See Also

Add Method (Dictionary) | Exists Method | Keys Method | Remove Method | RemoveAll Method

Applies To: Dictionary Object


Keys Method

Returns an array containing all existing keys in a Dictionary object.

object.Keys

The object is always the name of a Dictionary object.

Remarks

The following code illustrates use of the Keys method:

Dim a, d, i             'Create some variables
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"     'Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
a = d.keys              'Get the keys
For i = 0 To d.Count -1 'Iterate the array
    Print a(i)          'Print key
Next
...

See Also

Add Method (Dictionary) | Items Method | Remove Method | RemoveAll MethodApplies To: Dictionary Object


Move Method (FileSystemObject object)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Move Method

Moves a specified file or folder from one location to another.

object.Move destination

Arguments

object
Required. Always the name of a File or Folder object.
destination
Required. Destination where the file or folder is to be moved. Wildcard characters are not allowed.

Remarks

The results of the Move method on a File or Folder are identical to operations performed using FileSystemObject.MoveFile or FileSystemObject.MoveFolder. You should note, however, that the alternative methods are capable of moving multiple files or folders.

See Also

Copy Method | Delete Method | MoveFile Method | MoveFolder Method | OpenAsTextStream MethodApplies To: File Object | Folder Object


MoveFile Method

Moves one or more files from one location to another.

object.MoveFile source, destination

Arguments

object
Required. Always the name of a FileSystemObject.
source
Required. The path to the file or files to be moved. The source argument string can contain wildcard characters in the last path component only.
destination
Required. The path where the file or files are to be moved. The destination argument can't contain wildcard characters.

Remarks

If source contains wildcards or destination ends with a path separator (\), it is assumed that destination specifies an existing folder in which to move the matching files. Otherwise, destination is assumed to be the name of a destination file to create. In either case, three things can happen when an individual file is moved:

  • If destination does not exist, the file gets moved. This is the usual case.
  • If destination is an existing file, an error occurs.
  • If destination is a directory, an error occurs.

An error also occurs if a wildcard character that is used in source doesn't match any files. The MoveFile method stops on the first error it encounters. No attempt is made to roll back any changes made before the error occurs.

Important This method allows moving files between volumes only if supported by the operating system.

See Also

CopyFile Method | DeleteFile Method | Move Method | MoveFolder MethodApplies To: FileSystemObject Object


MoveFolder Method

Moves one or more folders from one location to another.

object.MoveFolder source, destination

Arguments

object
Required. Always the name of a FileSystemObject.
source
Required. The path to the folder or folders to be moved. The source argument string can contain wildcard characters in the last path component only.
destination
Required. The path where the folder or folders are to be moved. The destination argument can't contain wildcard characters.

Remarks

If source contains wildcards or destination ends with a path separator (\), it is assumed that destination specifies an existing folder in which to move the matching files. Otherwise, destination is assumed to be the name of a destination folder to create. In either case, three things can happen when an individual folder is moved:

  • If destination does not exist, the folder gets moved. This is the usual case.
  • If destination is an existing file, an error occurs.
  • If destination is a directory, an error occurs.

An error also occurs if a wildcard character that is used in source doesn't match any folders. The MoveFolder method stops on the first error it encounters. No attempt is made to roll back any changes made before the error occurs.

Important This method allows moving folders between volumes only if supported by the operating system.

See Also

CopyFolder Method | CreateFolder Method | DeleteFolder Method | Move Method | MoveFile MethodApplies To: FileSystemObject Object


OpenAsTextStream Method

Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.

object.OpenAsTextStream([iomode, [format]])

Arguments

object
Required. Always the name of a File object.
iomode
Optional. Indicates input/output mode. Can be one of three constants: ForReading, ForWriting, or ForAppending.
format
Optional. One of three Tristate values used to indicate the format of the opened file. If omitted, the file is opened as ASCII.

Settings

The iomode argument can have any of the following settings:

Constant | Value | Description
ForReading | 1 | Open a file for reading only. You can't write to this file.
ForWriting | 2 | Open a file for writing. If a file with the same name exists, its previous contents are overwritten.
ForAppending | 8 | Open a file and write to the end of the file.

The format argument can have any of the following settings:

Constant | Value | Description
TristateUseDefault | –1 | Opens the file using the system default.
TristateTrue | 1 | Opens the file as Unicode.
TristateFalse | 0 | Opens the file as ASCII.

Remarks

The OpenAsTextStream method provides the same functionality as the OpenTextFile method of the FileSystemObject. In addition, the OpenAsTextStream method can be used to write to a file.

The following code illustrates the use of the OpenAsTextStream method:

Sub TextStreamTest
    Const ForReading = 1, ForWriting = 2, ForAppending = 8
    Const TristateUseDefault = -1, TristateTrue = 1, TristateFalse = 0
    Dim fs, f, ts, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    fs.CreateTextFile "test1.txt"            'Create a file
    Set f = fs.GetFile("test1.txt")
    Set ts = f.OpenAsTextStream(ForWriting, TristateUseDefault)
    ts.Write "Hello World"
    ts.Close
    Set ts = f.OpenAsTextStream(ForReading, TristateUseDefault)
    s = ts.ReadLine
    MsgBox s
    ts.Close
End Sub

See Also

Copy Method | CreateTextFile Method | Delete Method | Move Method | OpenTextFile MethodApplies To: File Object


OpenTextFile Method

Opens a specified file and returns a TextStream object that can be used to read from or append to the file.

object.OpenTextFile(filename[, iomode[, create[, format]]])

Arguments

object
Required. Always the name of a FileSystemObject.
filename
Required. String expression that identifies the file to open.
iomode
Optional. Indicates input/output mode. Can be one of two constants, either ForReading or ForAppending.
create
Optional. Boolean value that indicates whether a new file can be created if the specified filename doesn't exist. The value is True if a new file is created; False if it isn't created. The default is False.
format
Optional. One of three Tristate values used to indicate the format of the opened file. If omitted, the file is opened as ASCII.

Settings

The iomode argument can have either of the following settings:

Constant | Value | Description
ForReading | 1 | Open a file for reading only. You can't write to this file.
ForAppending | 8 | Open a file and write to the end of the file.

The format argument can have any of the following settings:

Constant | Value | Description
TristateUseDefault | –1 | Opens the file using the system default.
TristateTrue | 1 | Opens the file as Unicode.
TristateFalse | 0 | Opens the file as ASCII.

Remarks

The following code illustrates the use of the OpenTextFile method to open a file for appending text:

Sub OpenTextFileTest
    Const ForReading = 1, ForWriting = 2, ForAppending = 8
    Dim fs, f
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.OpenTextFile("c:\testfile.txt", ForAppending,TristateFalse)
    f.Write "Hello world!"
    f.Close
End Sub

See Also

CreateTextFile Method | MoveFile Method | OpenAsTextStream MethodApplies To: FileSystemObject Object


Print Method

Prints text in the Immediate window.

object.Print [outputlist]

Arguments

object
Optional. An object expression that evaluates to an object in the Applies To list.
outputlist
Optional. Expression or list of expressions to print. If omitted, a blank line is printed.

The outputlist argument has the following syntax and parts:

{Spc(n) | Tab(n)} expression charpos

Arguments

Spc(n)
Optional. Used to insert space characters in the output, where n is the number of space characters to insert.
Tab(n)
Optional. Used to position the insertion point at an absolute column number where n is the column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone.
expression
Optional. Numeric expression or string expression to print.
charpos
Optional. Specifies the insertion point for the next character. Use a semicolon (;) to position the insertion point immediately following the last character displayed. Use Tab(n) to position the insertion point at an absolute column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone. If charpos is omitted, the next character is printed on the next line.

Remarks

Multiple expressions can be separated with either a space or a semicolon.

All data printed to the Immediate window is properly formatted using the decimal separator for the locale settings specified for your system. The keywords are output in the appropriate language for the host application.

For Boolean data, either True or False is printed. The True and False keywords are translated according to the locale setting for the host application.

Date data is written using the standard short date format recognized by your system. When either the date or the time component is missing or zero, only the data provided is written.

Nothing is written if outputlist data is Empty. However, if outputlist data is Null, Null is output. The Null keyword is appropriately translated when it is output.

For error data, the output is written as Error errorcode. The Error keyword is appropriately translated when it is output.

The object is required if the method is used outside a module having a default display space. For example an error occurs if the method is called in a standard module without specifying an object, but if called in a form module, outputlist is displayed on the form.

Note Because the Print method typically prints with proportionally-spaced characters, there is no correlation between the number of characters printed and the number of fixed-width columns those characters occupy. For example, a wide letter, such as a "W", occupies more than one fixed-width column, and a narrow letter, such as an "i", occupies less. To allow for cases where wider than average characters are used, your tabular columns must be positioned far enough apart. Alternatively, you can print using a fixed-pitch font (such as Courier) to ensure that each character uses only one column.

See Also

Example

Assert Method | Print # Statement | Spc Function | Tab Function

Applies To: Form Object, Forms Collection | UserControl Object


Print Method Example

Using the Print method, this example displays the value of the variable MyVar in the Immediate window. Note that the Print method only applies to objects that can display text.

Dim MyVar
MyVar = "Come see me in the Immediate pane."
Debug.Print MyVar


Raise Method

Generates a run-time error.

object.Raise (number, source, description, helpfile, helpcontext)

Argument

object
Required. Always the Err object.
number
Required. Long integer that identifies the nature of the error. Visual Basic errors (both Visual Basic-defined and user-defined errors) are in the range 0–65535. The range 0–512 is reserved for system errors; the range 513–65535 is available for user-defined errors. When setting the Number property to your own error code in a class module, you add your error code number to the ObjectError constant. For example, to generate the error number 513, assign ObjectError + 513 to the Number property.
source
Optional. String expression naming the object or application that generated the error. When setting this property for an object, use the form project.class. If source is not specified, the programmatic ID of the current Visual Basic project is used.
description
Optional. String expression describing the error. If unspecified, the value in Number is examined. If it can be mapped to a Visual Basic run-time error code, the string that would be returned by the Error function is used as Description. If there is no Visual Basic error corresponding to Number, the "Application-defined or object-defined error" message is used.
helpfile
Optional. The fully qualified path to the Help file in which help on this error can be found. If unspecified, Visual Basic uses the fully qualified drive, path, and file name of the Visual Basic Help file.
helpcontext
Optional. The context ID identifying a topic within helpfile that provides help for the error. If omitted, the Visual Basic Help file context ID for the error corresponding to the Number property is used, if it exists.

Remarks

All of the arguments are optional except number. If you use Raise without specifying some arguments, and the property settings of the Err object contain values that have not been cleared, those values serve as the values for your error.

Raise is used for generating run-time errors and can be used instead of the Error statement. Raise is useful for generating errors when writing class modules, because the Err object gives richer information than is possible if you generate errors with the Error statement. For example, with the Raise method, the source that generated the error can be specified in the Source property, online Help for the error can be referenced, and so on.

See Also

Example

Clear Method | Debugging Your Code and Handling Errors | Description Property | Err Object | Error Statement | Generating and Handling Errors in ActiveX Components | HelpContext Property | HelpContextID Property (VBA Add-In Object Model) | HelpFile Property | LastDLLError Property | Number Property | On Error Statement | Source Property

Applies To: Err Object


Raise Method Example

This example uses the Err object's Raise method to generate an error within an Automation object written in Visual Basic. It has the programmatic ID MyProj.MyObject. On the MacIntosh, the default drive name is "HD" and portions of the pathname are separated by colons instead of backslashes.

Const MyContextID = 1010407   ' Define a constant for contextID.
Function TestName(CurrentName, NewName)
   If Instr(NewName, "bob") Then   ' Test the validity of NewName.
      ' Raise the exception
      Err.Raise vbObjectError + 513, "MyProj.MyObject", _
      "No ""bob"" allowed in your name", "c:\MyProj\MyHelp.Hlp", _
      MyContextID
   End If
End Function


Read Method

Reads a specified number of characters from a TextStream file and returns the resulting string.

object.Read(characters)

Arguments

object
Required. Always the name of a TextStreamobject.
characters
Required. Number of characters you want to read from the file.

See Also

Close Method | ReadAll Method | ReadLine Method | Skip Method | SkipLine Method | Write Method | WriteBlankLines Method | WriteLine MethodApplies To: TextStream Object


ReadAll Method

Reads an entire TextStream file and returns the resulting string.

object.ReadAll

The object is always the name of a TextStream object.

Remarks

For large files, using the ReadAll method wastes memory resources. Other techniques should be used to input a file, such as reading a file line by line.

See Also

Close Method | Read Method | ReadLine Method | Skip Method | SkipLine Method | Write Method | WriteBlankLines Method | WriteLine MethodApplies To: TextStream Object


ReadLine Method

Reads an entire line (up to, but not including, the newline character) from a TextStream file and returns the resulting string.

object.ReadLine

The object argument is always the name of a TextStream object.

See Also

Close Method | Read Method | ReadAll Method | Skip Method | SkipLine Method | Write Method | WriteBlankLines Method | WriteLine MethodApplies To: TextStream Object


Remove Method (Visual Basic for Applications)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Remove Method

Removes a member from a Collection object.

object.Remove index

Arguments

object
Required. An object expression that evaluates to an object in the Applies To list.
index
Required. An expression that specifies the position of a member of the collection. If a numeric expression, index must be a number from 1 to the value of the collection's Count property. If a string expression, index must correspond to the key argument specified when the member referred to was added to the collection.

Remarks

If the value provided as index doesn’t match an existing member of the collection, an error occurs.

See Also

Example

Add Method | Add Method (VBA Add-In Object Model) | Item Method | Item Method (VBA Add-In Object Model) | ItemAdded Event (VBA Add-In Object Model) | ItemRemoved Event (VBA Add-In Object Model)

Applies To: BindingCollection Object | Collection Object | DataMembers Collection | ExportFormats Collection | Licenses Collection | rdoColumns Collection | rdoConnections Collection | rdoEnvironments Collection | StdDataFormats Collection


Remove Method (FileSystemObject object)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Remove Method

Removes a key, item pair from a Dictionary object.

object.Remove(key)

Arguments

object
Required. Always the name of a Dictionary object.
key
Required. Key associated with the key, item pair you want to remove from the Dictionary object.

Remarks

An error occurs if the specified key, item pair does not exist.

The following code illustrates use of the Remove method:

Dim a, d, i             'Create some variables
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"     'Add some keys and items
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...
a = d.Remove()          'Remove second pair

See Also

Add Method (Dictionary) | Exists Method | Items Method | Keys Method | RemoveAll Method

Applies To: Dictionary Object


RemoveAll Method

The RemoveAll method removes all key, item pairs from a Dictionary object.

object.RemoveAll

The object is always the name of a Dictionary object.

Remarks

The following code illustrates use of the RemoveAll method:

Dim a, d, i             'Create some variables
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"     'Add some keys and items
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...
a = d.RemoveAll         'Clear the dictionary

See Also

Add Method (Dictionary) | Exists Method | Items Method | Keys Method | Remove MethodApplies To: Dictionary Object


Skip Method

Skips a specified number of characters when reading a TextStream file.

object.Skip(characters)

Arguments

object
Required. Always the name of a TextStream object.
characters
Required. Number of characters to skip when reading a file.

Remarks

Skipped characters are discarded.

See Also

Close Method | Read Method | ReadAll Method | ReadLine Method | SkipLine Method | Write Method | WriteBlankLines Method | WriteLine MethodApplies To: TextStream Object


SkipLine Method

Skips the next line when reading a TextStream file.

object.SkipLine

The object is always the name of a TextStream object.

Remarks

Skipping a line means reading and discarding all characters in a line up to and including the next newline character.

An error occurs if the file is not open for reading.

See Also

Close Method | Read Method | ReadAll Method | ReadLine Method | Skip Method | Write Method | WriteBlankLines Method | WriteLine MethodApplies To: TextStream Object


Write Method

Writes a specified string to a TextStream file.

object.Write(string)

Arguments

object
Required. Always the name of a TextStream object.
string
Required. The text you want to write to the file.

Remarks

Specified strings are written to the file with no intervening spaces or characters between each string. Use the WriteLine method to write a newline character or a string that ends with a newline character.

See Also

Close Method | Read Method | ReadAll Method | ReadLine Method | Skip Method | SkipLine Method | WriteBlankLines Method | WriteLine MethodApplies To: TextStream Object


WriteBlankLines Method

Writes a specified number of newline characters to a TextStream file.

object.WriteBlankLines(lines)

Arguments

object
Required. Always the name of a TextStream object.
lines
Required. Number of newline characters you want to write to the file.

See Also

Close Method | Read Method | ReadAll Method | ReadLine Method | Skip Method | SkipLine Method | Write Method | WriteLine MethodApplies To: TextStream Object


WriteLine Method

Writes a specified string and newline character to a TextStream file.

object.WriteLine([string])

Arguments

object
Required. Always the name of a TextStream object.
string
Optional. The text you want to write to the file. If omitted, a newline character is written to the file.

See Also

Close Method | Read Method | ReadAll Method | ReadLine Method | Skip Method | SkipLine Method | Write Method | WriteBlankLines MethodApplies To: TextStream Object


Miscellaneous (Visual Basic for Applications)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Miscellaneous (Visual Basic Language Reference)

Character Set (0 - 127)

Character Set (128 – 255)

Document Conventions


Character Set (0 - 127)

0 |  | 32 | [space] | 64 | @ | 96 | `
1 |  | 33 | ! | 65 | A | 97 | a
2 |  | 34 | " | 66 | B | 98 | b
3 |  | 35 | # | 67 | C | 99 | c
4 |  | 36 | $ | 68 | D | 100 | d
5 |  | 37 | % | 69 | E | 101 | e
6 |  | 38 | & | 70 | F | 102 | f
7 |  | 39 | ' | 71 | G | 103 | g
8 | * * | 40 | ( | 72 | H | 104 | h
9 | * * | 41 | ) | 73 | I | 105 | i
10 | * * | 42 | * | 74 | J | 106 | j
11 |  | 43 | + | 75 | K | 107 | k
12 |  | 44 | , | 76 | L | 108 | l
13 | * * | 45 | - | 77 | M | 109 | m
14 |  | 46 | . | 78 | N | 110 | n
15 |  | 47 | / | 79 | O | 111 | o
16 |  | 48 | 0 | 80 | P | 112 | p
17 |  | 49 | 1 | 81 | Q | 113 | q
18 |  | 50 | 2 | 82 | R | 114 | r
19 |  | 51 | 3 | 83 | S | 115 | s
20 |  | 52 | 4 | 84 | T | 116 | t
21 |  | 53 | 5 | 85 | U | 117 | u
22 |  | 54 | 6 | 86 | V | 118 | v
23 |  | 55 | 7 | 87 | W | 119 | w
24 |  | 56 | 8 | 88 | X | 120 | x
25 |  | 57 | 9 | 89 | Y | 121 | y
26 |  | 58 | : | 90 | Z | 122 | z
27 |  | 59 | ; | 91 | [ | 123 | {
28 |  | 60 | < | 92 | \ | 124 | |
29 |  | 61 | = | 93 | ] | 125 | }
30 |  | 62 | > | 94 | ^ | 126 | ~
31 |  | 63 | ? | 95 | _ | 127 | 

These characters aren't supported by Microsoft Windows.

* *Values 8, 9, 10, and 13 convert to backspace, tab, linefeed, and carriage return characters, respectively. They have no graphical representation but, depending on the application, can affect the visual display of text.

See Also

Character Set (128 – 255) | Chr Function


Character Set (128 – 255)

The values in the following table are Microsoft® Windows® defaults. However, values in the ANSI character set above 127 are determined by the code page specific to your operating system.

128 | € | 160 | [space] | 192 | À | 224 | à
129 |  | 161 | ¡ | 193 | Á | 225 | á
130 | ‚ | 162 | ¢ | 194 | Â | 226 | â
131 | ƒ | 163 | £ | 195 | Ã | 227 | ã
132 | „ | 164 | ¤ | 196 | Ä | 228 | ä
133 | … | 165 | ¥ | 197 | Å | 229 | å
134 | † | 166 | ¦ | 198 | Æ | 230 | æ
135 | ‡ | 167 | § | 199 | Ç | 231 | ç
136 | ˆ | 168 | ¨ | 200 | È | 232 | è
137 | ‰ | 169 | © | 201 | É | 233 | é
138 | Š | 170 | ª | 202 | Ê | 234 | ê
139 | ‹ | 171 | « | 203 | Ë | 235 | ë
140 | Œ | 172 | ¬ | 204 | Ì | 236 | ì
141 |  | 173 |  | 205 | Í | 237 | í
142 | Ž | 174 | ® | 206 | Î | 238 | î
143 |  | 175 | ¯ | 207 | Ï | 239 | ï
144 |  | 176 | ° | 208 | Ð | 240 | ð
145 | ‘ | 177 | ± | 209 | Ñ | 241 | ñ
146 | ’ | 178 | ² | 210 | Ò | 242 | ò
147 | “ | 179 | ³ | 211 | Ó | 243 | ó
148 | ” | 180 | ´ | 212 | Ô | 244 | ô
149 | • | 181 | µ | 213 | Õ | 245 | õ
150 | – | 182 | ¶ | 214 | Ö | 246 | ö
151 | — | 183 | · | 215 | × | 247 | ÷
152 | ˜ | 184 | ¸ | 216 | Ø | 248 | ø
153 | ™ | 185 | ¹ | 217 | Ù | 249 | ù
154 | š | 186 | º | 218 | Ú | 250 | ú
155 | › | 187 | » | 219 | Û | 251 | û
156 | œ | 188 | ¼ | 220 | Ü | 252 | ü
157 |  | 189 | ½ | 221 | Ý | 253 | ý
158 | ž | 190 | ¾ | 222 | Þ | 254 | þ
159 | Ÿ | 191 | ¿ | 223 | ß | 255 | ÿ

 These characters are not supported by Microsoft Windows.

See Also

Character Set (0 - 127) | Chr Function


Document Conventions

Visual Basic documentation uses the following typographic and code conventions.

Typographic Conventions

Convention | Description
Sub, If, ChDir, Print, True, Debug | Words in bold with initial letter capitalized indicate language-specific keywords.
Setup | Words you are instructed to type appear in bold.
object, varname, arglist | Italic, lowercase letters indicate placeholders for information you supply.
pathname, filenumber | Bold, italic, and lowercase letters indicate placeholders for arguments where you can use either positional (based on the procedure's pre-defined order) or named-argument syntax.
[expressionlist] | In syntax, items inside brackets are optional.
{While | Until} | In syntax, braces and a vertical bar indicate a mandatory choice between two or more items. You must choose one of the items unless all of the items are also enclosed in brackets. For example: [{This | OrThat}]
ESC, ENTER | Words in capital letters indicate key names and key sequences.
ALT+F1, CTRL+R | A plus sign (+) between key names indicates a combination of keys. For example, ALT+F1 means hold down the ALT key while pressing the F1 key.

Code Conventions

Sample code Description
MyString = "Hello, world!"
 This font is used for code, variables, and error message text.
' This is a comment.
 An apostrophe (') introduces code comments.
MyVar = "This is an " _
& "example" _
& " of how to continue code."
 A space and an underscore ( _) continue a line of code.


Objects (Visual Basic for Applications)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Objects (Visual Basic Language Reference)

Collection Object

Debug Object

Dictionary Object

Drive Object

Drives Collection

Err Object

File Object

Files Collection

FileSystemObject Object

Folder Object

Folders Collection

TextStream Object


Collection Object

A Collection object is an ordered set of items that can be referred to as a unit.

Remarks

The Collection object provides a convenient way to refer to a related group of items as a single object. The items, or members, in a collection need only be related by the fact that they exist in the collection. Members of a collection don't have to share the same data type.

A collection can be created the same way other objects are created. For example:

Dim X As New Collection

Once a collection is created, members can be added using the Add method and removed using the Remove method. Specific members can be returned from the collection using the Item method, while the entire collection can be iterated using the For Each...Next statement.

See Also

Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Collection Object Properties, Methods, and Events

Properties

Count Property

Methods

Add Method

Item Method

Remove Method

Events

Applies To

Collection Object


Collection Object Example

This example creates a Collection object (MyClasses), and then creates a dialog box in which users can add objects to the collection. To see how this works, choose the Class Module command from the Insert menu and declare a public variable called InstanceName at module level of Class1 (type Public InstanceName) to hold the names of each instance. Leave the default name as Class1. Copy and paste the following code into the General section of another module, and then start it with the statement ClassNamer in another procedure. (This example only works with host applications that support classes.)

Sub ClassNamer()
   Dim MyClasses As New Collection   ' Create a Collection object.
   Dim Num   ' Counter for individualizing keys.
   Dim Msg As String   ' Variable to hold prompt string.
   Dim TheName, MyObject, NameList   ' Variants to hold information.
   Do
      Dim Inst As New Class1   ' Create a new instance of Class1.
      Num = Num + 1   ' Increment Num, then get a name.
      Msg = "Please enter a name for this object." & Chr(13) _
       & "Press Cancel to see names in collection."
      TheName = InputBox(Msg, "Name the Collection Items")
      Inst.InstanceName = TheName   ' Put name in object instance.
      ' If user entered name, add it to the collection.
      If Inst.InstanceName <> "" Then
         ' Add the named object to the collection.
         MyClasses.Add item := Inst, key := CStr(Num)
      End If
      ' Clear the current reference in preparation for next one.
      Set Inst = Nothing
   Loop Until TheName = ""
   For Each MyObject In MyClasses   ' Create list of names.
      NameList = NameList & MyObject.InstanceName & Chr(13)
   Next MyObject
   ' Display the list of names in a message box.
   MsgBox NameList, , "Instance Names In MyClasses Collection"

   For Num = 1 To MyClasses.Count   ' Remove name from the collection.
      MyClasses.Remove 1   ' Since collections are reindexed
            ' automatically, remove the first
   Next      ' member on each iteration.
End Sub


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Debug Object

The Debug object sends output to the Immediate window at run time.

See Also

Properties, Methods, and Events


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Debug Object Properties, Methods, and Events

Properties

Methods

Assert Method

WriteLn Method

Events

Applies To

Debug Object


Dictionary Object

Object that stores data key, item pairs.

Scripting.Dictionary

Remarks

A Dictionary object is the equivalent of a PERL associative array. Items, which can be any form of data, are stored in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually a integer or a string, but can be anything except an array.

The following code illustrates how to create a Dictionary object:

Dim d                   'Create a variable
Set d = CreateObject(Scripting.Dictionary)
d.Add "a", "Athens"     'Add some keys and items
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
...

See Also

Properties, Methods, and Events | FileSystemObject Object | TextStream Object


Dictionary Object Properties, Methods, and Events

Properties

CompareMode Property

Count Property

Item Property

Key Property

Methods

Add Method (Dictionary)

Exists Method

Items Method

Keys Method

Remove Method

RemoveAll Method

Events

Applies To

Dictionary Object


Drive Object

Provides access to the properties of a particular disk drive or network share.

Remarks

The following code illustrates the use of the Drive object to access drive properties:

Sub ShowFreeSpace(drvPath)
    Dim fs, d, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(fs.GetDriveName(drvPath))
    s = "Drive " & UCase(drvPath) & " - "
    s = s & d.VolumeName  & vbCrLf
    s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
    s = s & " Kbytes"
    MsgBox s
End Sub

See Also

Properties, Methods, and Events | DriveExists Method | Drives Collection | File Object | Files Collection | FileSystemObject Object | Folder Object | Folders Collection


Drive Object Properties, Methods, and Events

Properties

AvailableSpace Property

DriveLetter Property

DriveType Property

FileSystem Property

FreeSpace Property

IsReady Property

Path Property

RootFolder Property

SerialNumber Property

ShareName Property

TotalSize Property

VolumeName Property

Methods

Events

Applies To

Drive Object


Drives Collection

Read-only collection of all available drives.

Remarks

Removable-media drives need not have media inserted for them to appear in the Drives collection.

The following code illustrates how to get the Drives collection and iterate the collection using the For Each...Next statement:

Sub ShowDriveList
    Dim fs, d, dc, s, n
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set dc = fs.Drives
    For Each d in dc
        s = s & d.DriveLetter & " - "
        If d.DriveType = Remote Then
            n = d.ShareName
        Else
            n = d.VolumeName
        End If
        s = s & n & vbCrLf
    Next
    MsgBox s
End Sub

See Also

Properties, Methods, and Events | Drive Object | DriveExists Method | Drives Property | File Object | Files Collection | FileSystemObject Object | Folder Object | Folders Collection


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Drives Collection Properties, Methods, and Events

Properties

Count Property

Item Property

Methods

Events

Applies To

Drives Collection


Err Object

Contains information about run-time errors.

Remarks

The properties of the Err object are set by the generator of an error — Visual Basic, an object, or the programmer.

The default property of the Err object is Number. Because the default property can be represented by the object name Err, earlier code written using the Err function or Err statement doesn't have to be modified.

When a run-time error occurs, the properties of the Err object are filled with information that uniquely identifies the error and information that can be used to handle it. To generate a run-time error in your code, use the Raise method.

The Err object's properties are reset to zero or zero-length strings ("") after an Exit Sub, Exit Function, Exit Property or Resume Next statement within an error-handling routine. Using any form of the Resume statement outside of an error-handling routine will not reset the Err object's properties. The Clear method can be used to explicitly reset Err.

Use the Raise method, rather than the Error statement, to generate run-time errors for system errors and class modules. Using the Raise method in other code depends on the richness of the information you want to return.

The Err object is an intrinsic object with global scope. There is no need to create an instance of it in your code.

See Also

Example

Properties, Methods, and Events | Dictionary Object | Error Function | Error Object | Error Statement | FileSystemObject Object | On Error Statement | Resume Statement | Trappable Errors


Err Object Properties, Methods, and Events

Properties

Description Property

HelpContext Property

HelpFile Property

LastDLLError Property

Number Property

Source Property

Methods

Clear Method

Raise Method

Events

Applies To

Err Object


Err Object Example

This example uses the properties of the Err object in constructing an error-message dialog box. Note that if you use the Clear method first, when you generate a Visual Basic error with the Raise method, Visual Basic's default values become the properties of the Err object.

Dim Msg
' If an error occurs, construct an error message
On Error Resume Next   ' Defer error handling.
Err.Clear
Err.Raise 6   ' Generate an "Overflow" error.
' Check for error, then show message.
If Err.Number <> 0 Then
   Msg = "Error # " & Str(Err.Number) & " was generated by " _
         & Err.Source & Chr(13) & Err.Description
   MsgBox Msg, , "Error", Err.Helpfile, Err.HelpContext
End If


File Object

Provides access to all the properties of a file.

Remarks

The following code illustrates how to obtain a File object and how to view one of its properties.

Sub ShowFileInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = f.DateCreated
    MsgBox s
End Sub

See Also

Properties, Methods, and Events | Drive Object | Drives Collection | Files Collection | FileSystemObject Object | Folder Object | Folders Collection


File Object Properties, Methods, and Events

Properties

Attributes Property

DateCreated Property

DateLastAccessed Property

DateLastModified Property

Drive Property

Name Property

ParentFolder Property

Path Property

ShortName Property

ShortPath Property

Size Property

Type Property

Methods

Copy Method

Delete Method

Move Method

OpenAsTextStream Method

Events

Applies To

File Object


Files Collection

Collection of all File objects within a folder.

Remarks

The following code illustrates how to get a Files collection and iterate the collection using the For Each...Next statement:

Sub ShowFolderList(folderspec)
    Dim fs, f, f1, fc, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(folderspec)
    Set fc = f.Files
    For Each f1 in fc
        s = s & f1.name
        s = s & vbCrLf
    Next
    MsgBox s
End Sub

See Also

Properties, Methods, and Events | Drive Object | Drives Collection | File Object | FileSystemObject Object | Folder Object | Folders Collection


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Files Collection Properties, Methods, and Events

Properties

Count Property

Item Property

Methods

Events

Applies To

Files Collection


FileSystemObject Object

Provides access to a computer's file system.

Scripting.FileSystemObject

Remarks

The following code illustrates how the FileSystemObject is used to return a TextStream object that can be read from or written to:

Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile("c:\testfile.txt", True)
a.WriteLine("This is a test.")
a.Close

In the code shown above, the CreateObject function returns the FileSystemObject (fs). The CreateTextFile method then creates the file as a TextStream object (a), and the WriteLine method writes a line of text to the created text file. The Close method flushes the buffer and closes the file.

See Also

Properties, Methods, and Events | Dictionary Object | TextStream Object


FileSystemObject Object Properties, Methods, and Events

Properties

Drives Property

Methods

BuildPath Method

CopyFile Method

CopyFolder Method

CreateFolder Method

CreateTextFile Method

DeleteFile Method

DeleteFolder Method

DriveExists Method

FileExists Method

FolderExists Method

GetAbsolutePathName Method

GetBaseName Method

GetDrive Method

GetDriveName Method

GetExtensionName Method

GetFile Method

GetFileName Method

GetFolder Method

GetParentFolderName Method

GetSpecialFolder Method

GetTempName Method

MoveFile Method

MoveFolder Method

OpenTextFile Method

Events

Applies To

FileSystemObject Object


Folder Object

Provides access to all the properties of a folder.

Remarks

The following code illustrates how to obtain a Folder object and how to return one of its properties:

Sub ShowFolderInfo(folderspec)
    Dim fs, f, s,
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(folderspec)
    s = f.DateCreated
    MsgBox s
End Sub

See Also

Properties, Methods, and Events | Drive Object | Drives Collection | File Object | Files Collection | FileSystemObject Object


Folder Object Properties, Methods, and Events

Properties

Attributes Property

DateCreated Property

DateLastAccessed Property

DateLastModified Property

Drive Property

Files Property

IsRootFolder Property

Name Property

ParentFolder Property

Path Property

ShortName Property

ShortPath Property

Size Property

SubFolders Property

Type Property

Methods

Copy Method

CreateTextFile Method

Delete Method

Move Method

Events

Applies To

Folder Object


Folders Collection

Collection of all Folder objects contained within a Folder object.

Remarks

The following code illustrates how to get a Folders collection and how to iterate the collection using the For Each...Next statement:

Sub ShowFolderList(folderspec)
    Dim fs, f, f1, fc, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(folderspec)
    Set fc = f.SubFolders
    For Each f1 in fc
        s = s & f1.name
        s = s &  vbCrLf
    Next
    MsgBox s
End Sub

See Also

Properties, Methods, and Events | Drive Object | Drives Collection | File Object | Files Collection | FileSystemObject Object | Folder Object


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Folders Collection Properties, Methods, and Events

Properties

Count Property

Item Property

Methods

Add Method (Folders)

Events

Applies To

Folders Collection


TextStream Object

Facilitates sequential access to file.

TextStream.{property | method}

The property and method arguments can be any of the properties and methods associated with the TextStream object. Note that in actual usage TextStream is replaced by a variable placeholder representing the TextStream object returned from the FileSystemObject.

Remarks

In the following code, a is the TextStream object returned by the CreateTextFile method on the FileSystemObject:

Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.CreateTextFile("c:\testfile.txt", True)
a.WriteLine("This is a test.")
a.Close

WriteLine and Close are two methods of the TextStream Object.

See Also

Properties, Methods, and Events | Dictionary Object | FileSystemObject Object


TextStream Object Properties, Methods, and Events

Properties

AtEndOfLine Property

AtEndOfStream Property

Column Property

Line Property

Methods

Close Method

Read Method

ReadAll Method

ReadLine Method

Skip Method

SkipLine Method

Write Method

WriteBlankLines Method

WriteLine Method

Events

Applies To

TextStream Object


Operators (Visual Basic for Applications)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Operators (Visual Basic Language Reference)

Operator Summary

& Operator

* Operator

#NAME?

#NAME?

/ Operator

#NAME?

\ Operator

^ Operator

AddressOf Operator

And Operator

Eqv Operator

Imp Operator

Is Operator

Like Operator

Mod Operator

Not Operator

Or Operator

Xor Operator


Operator Precedence in Visual Basic

When several operations occur in an expression, each part is evaluated and resolved in a predetermined order called operator precedence.

When expressions contain operators from more than one category, arithmetic operators are evaluated first, comparison operators are evaluated next, and logical operators are evaluated last. Comparison operators all have equal precedence; that is, they are evaluated in the left-to-right order in which they appear. Arithmetic and logical operators are evaluated in the following order of precedence:

Arithmetic | Comparison | Logical
Exponentiation (^) | Equality (=) | Not
Negation (–) | Inequality (<>) | And
Multiplication and division (*, /) | Less than (<) | Or
Integer division (\) | Greater than (>) | Xor
Modulus arithmetic (Mod) | Less than or equal to (<=) |
Addition and subtraction (+, –) | Greater than or equal to (>=) |
Bitwise Operators (BitNot, BitAnd, BitOr, BitXor) | Like Is |
String concatenation (&) |  |

When multiplication and division occur together in an expression, each operation is evaluated as it occurs from left to right. When addition and subtraction occur together in an expression, each operation is evaluated in order of appearance from left to right. Parentheses can be used to override the order of precedence and force some parts of an expression to be evaluated before others. Operations within parentheses are always performed before those outside. Within parentheses, however, operator precedence is maintained.

The string concatenation operator (&) is not an arithmetic operator, but in precedence, it does follow all arithmetic operators and precede all comparison operators.

The Is operator is an object reference comparison operator. It does not compare objects or their values; it checks only to determine if two object references refer to the same object.

See Also

= Operator | Is Operator | Like Operator | Operator Summary


Operator Summary

Operators | Description
Arithmetic Operators | Operators used to perform mathematical calculations.
Comparison Operators | Operators used to perform comparisons.
Concatenation Operators | Operators used to combine strings.
Logical Operators | Operators used to perform logical operations.
BitwiseOperators | Operators used to perform bitwise operations.

See Also

= Operator | Operator Precedence in Visual Basic


& Operator

Used to generate a string concatenation of two expressions.

Arguments

Part
Description
result
Required; any String or ObjectdefObjectDataType@veendf98.chm variable.
expression1
Required; any expression.
expression2
Required; any expression.

Remarks

If an expression is not a string, it is converted to a String. The data type of result is String if both expressions are string expressions; otherwise, result is a String. If one or both expressions arestated as Nothing, a Variable Not Set error occurs.

See Also

Example


& Operator Example

This example uses the & operator to force string concatenation.

Dim MyStr
MyStr = "Hello" & " World"   ' Returns "Hello World".
MyStr = "Check " & 123 & " Check"   ' Returns "Check 123 Check".


&= Operator

Concatenates a string expression to a string variable and assigns the result to the variable.

Arguments

Part
Description
variable
Required; any string variable.
expression
Required; any string expression.

See Also

& Operator | *= Operator | += Operator | -= Operator | /= Operator | = Operator | \= Operator | ^= Operator


* Operator

Used to multiply two numbers.

Arguments

Part
Description
result
Required; any numeric variable.
number1
Required; any numeric expression.
number2
Required; any numeric expression.

Remarks

The data type of result is usually the same as that of the most precise expression. The order of precision, from least to most precise, is Byte, Short , Integer, Long, Single, Double, and Decimal. The following are exceptions to this order:

If | Then result is
Multiplication involves a Single and a Long, | converted to a Double.
The data type of result is a Longor Single that overflows its legal range, | A Run-time error will occur.
The data type of result is a Byte object that overflows its legal range, | A Run-time error will occur.
the data type of result is an Integer object that overflows its legal range, | A Run-time error will occur.

If one or both expressions arestated as Nothing, A Variable Not Set error occurs. If an expression is Empty, it is treated as 0.

Note The order of precision used by multiplication is not the same as the order of precision used by addition and subtraction.

See Also

Example


= Operator

Used to assign a value to a variable or property.

variable = value

Arguments

variable
Any variable or any writable property.
value
Any numeric or string literal, constant, or expression.

Remarks

The name on the left side of the equal sign can be a simple scalar variable or an element of an array. Properties on the left side of the equal sign can only be those properties that are writable at run time.

Note: The = Operator can also be used in the assignment of Boolean values, but not in the comparison of two Boolean variables. When comparing Booleans, one should use the EQV operator .

See Also

&= Operator | *= Operator | += Operator | -= Operator | /= Operator | \= Operator | ^= Operator


*= Operator

Multiplies the value of a variable by the value of an expression and assigns the result to the variable.

Arguments

Part
Description
variable
Required; any numeric variable.
expression
Required; any numeric expression.

See Also

&= Operator | * Operator | += Operator | -= Operator | /= Operator | = Operator | \= Operator | ^= Operator


+ Operator

Used to sum two numbers.

Arguments

Part
Description
result
Required; any numeric variable.
expression1
Required; any expression.
expression2
Required; any expression.

Remarks

When you use the + operator, you may not be able to determine whether addition or string concatenation will occur. Use the & operator for concatenation to eliminate ambiguity and provide self-documenting code.

If at least one expression is not an Object, the following rules apply:

If | Then
Both expressions are numeric data types (Byte, Short, Integer, Long, Single, Double, or Decimal) | Add.
Both expressions are String | Concatenate.
One expression is a numeric data type and the other is any Object | Add.
One expression is a String and the other is any Object. | Concatenate.
One expression is a numeric data type and the other is a String | A Type mismatch error occurs.
Either expression is Nothing. | A Variable Not Set error occurs.

If both expressions are Object expressions, the following rules apply:

If | Then
Both Object expressions are numeric | Add.
Both Object expressions are strings | Concatenate.
One Object expression is numeric and the other is a string | A type mismatch error occurs.

For simple arithmetic addition involving only expressions of numeric data types, the data type of result is usually the same as that of the most precise expression. The order of precision, from least to most precise, is Byte, Integer, Long, Single, Double, and Decimal. The following are exceptions to this order:

If | Then result is
A Single and a Long are added, | a Double.
The data type of result is a Byte, Short, Integer or Long, object that overflows its legal range, | A Run-time error will occur.
The data type of result is a Single or Doubleobject that overflows its legal range, | A Run-time error will occur.
The data type of result is a Decimalobject that overflows its legal range, | A Run-time error will occur if the value is too large and Zero if the value is too small.

If one or both expressions arestated as Nothing, a Variable Not Set error occurs. If both expressions are Empty, result is an Integer. However, if only one expression is Empty, the other expression is returned unchanged as result.

Note The order of precision used by addition and subtraction is not the same as the order of precision used by multiplication.


+= Operator

See Also

Example

+= Operator | Arithmetic Operators | Concatenation Operators | Operator Precedence in Visual Basic | Operator Summary

Adds the value of an expression to the value of a variable and assigns the result to the variable.

Arguments

Part
Description
variable
Required; any numeric variable.
expression
Required; any numeric expression.


- Operator

Used to find the difference between two numbers or to indicate the negative value of a numeric expression.

Syntax 1

result = number1–number2

Syntax 2

–number

The – operator syntax has these parts:

Arguments

Part
Description
result
Required; any numeric variable.
number
Required; any numeric expression.
number1
Required; any numeric expression.
number2
Required; any numeric expression.

Remarks

In Syntax 1, the – operator is the arithmetic subtraction operator used to find the difference between two numbers. In Syntax 2, the – operator is used as the unary negation operator to indicate the negative value of an expression.

The data type of result is usually the same as that of the most precise expression. The order of precision, from least to most precise, is Byte, Short Integer, Long, Single, Double, and Decimal. The following are exceptions to this order: If | Then result is
Subtraction involves a Single and a Long, | converted to a Double.
The data type of result is a Long, or Single, that overflows its legal range, | A Run-time error will occur.
The data type of result is a Byte object that overflows its legal range, | A Run-time error will occur.
The data type of result is an Integer object that overflows its legal range, | A Run-time error will occur.

One or both expressions arestated as Nothing, a Variable Not Set error occurs. If an expression is Empty, it is treated as 0.

Note The order of precision used by addition and subtraction is not the same as the order of precision used by multiplication.

See Also

Example


-= Operator

Subtracts the value of an expression from the value of a variable and assigns the result to the variable.

Arguments

Part
Description
variable
Required; any numeric variable.
expression
Required; any numeric expression.

See Also

&= Operator | *= Operator | += Operator | - Operator | /= Operator | = Operator | \= Operator | ^= Operator


/ Operator

Used to divide two numbers and return a floating-point result.

Arguments

Part
Description
result
Required; any numeric variable.
number1
Required; any numeric expression.
number2
Required; any numeric expression.

Remarks

The data type of result is usually a Double or a Doubleobject. The following are exceptions to this rule:

If | Then result is
Both expressions are Byte, Integer, or Single expressions, | a Single, if one of the expressions is a Single, else the result is a Double. If it overflows its legal range, a Run-time error will occur..
Both expressions are Byte, Integer, or Single objects, | a Single object unless it overflows its legal range; in which case a Run-time error will occur.
Division involves a Decimal and any other data type, | a Decimal data type.

If one or both expressions arestated as Nothing, a Variable Not Set error occurs. Any expression that is Empty is treated as 0.

See Also

Example


/= Operator

Divides the value of a variable by the value of an expression and assigns the result to the variable.

Arguments

Part
Description
variable
Required; any numeric variable.
expression
Required; any numeric expression.

See Also

&= Operator | *= Operator | += Operator | -= Operator | / Operator | = Operator | \= Operator | ^= Operator


\ Operator

Used to divide two numbers and return an integer result.

Arguments

Part
Description
result
Required; any numeric variable.
number1
Required; any numeric expression.
number2
Required; any numeric expression.

Remarks

Before division is performed, the numeric expressions are rounded to Byte, Integer, or Long expressions.

Usually, the data type of result is a Byte, Byteobject, Integer, Integerobject, Long, or Longobject, regardless of whether result is a whole number. Any fractional portion is truncated. However, if any expression isstated as Nothing, a Variable Not Set error occurs. Any expression that is Empty is treated as 0.

See Also

Example


\= Operator

Divides the value of a variable by the value of an expression and assigns the integer result to the variable.

Arguments

Part
Description
variable
Required; any numeric variable.
expression
Required; any numeric expression.

See Also

&= Operator | *= Operator | += Operator | -= Operator | /= Operator | = Operator | \ Operator | ^= Operator


^ Operator

Raises a number to the power of an exponent.

Arguments

Part
Description
result
Required; any numeric variable.
number
Required; any numeric expression.
exponent
Required; any numeric expression.

Remarks

A number can be negative only if exponent is an integer value. When more than one exponentiation is performed in a single expression, the ^ operator is evaluated as it is encountered from left to right.

Usually, the data type of result is a Double or an Object containing a Double.

See Also

Example


^ Operator Example

This example uses the ^ operator to raise a number to the power of an exponent.

Dim MyValue
MyValue = 2 ^ 2   ' Returns 4.
MyValue = 3 ^ 3 ^ 3   ' Returns 19683.
MyValue = (-5) ^ 3   ' Returns -125.


^= Operator

Raises the value of a variable to the power of an exponent and assigns the result back to the variable

Arguments

Part
Description
variable
Required; any numeric variable.
exponent
Required; any expression that specifies the exponent.

See Also

&= Operator | *= Operator | += Operator | -= Operator | /= Operator | = Operator | \= Operator | ^ Operator


AddressOf Operator

A unary operator that creates a procedure delegate instance that references the specific procedure.

 AddressOf procedurename

The required procedurename specifies the procedure that will be referenced by the newly created procedure delegate.

Remarks

When a procedure name appears in an argument list, usually the procedure is evaluated, and the address of the procedure’s return value is passed. The AddressOf operator appears only in the call to the API procedure. The AddressOf operator can also be used within a Delegate Statement, which also produces a reference to the procedure, but allows the user more flexibility in where they can place the AddressOf operator within their code.

Warning Using AddressOf may cause unpredictable results if you don't completely understand the concept of function callbacks. You must understand how the Basic portion of the callback works, and also the code of the DLL into which you are passing your function address. Debugging such interactions is difficult since the program runs in the same process as the development environment. In some cases, systematic debugging may not be possible.
Note You can create your own call-back function prototypes in DLLs compiled with Microsoft Visual C++ (or similar tools). To work with AddressOf, your prototype must use the __stdcall calling convention. The default calling convention (__cdecl) will not work with AddressOf.

See Also

Example


AddressOf Operator Example

The following example creates a form with a list box containing an alphabetically sorted list of the fonts in your system.

To run this example, create a form with a list box on it. The code for the form is as follows:

Option Explicit

Private Sub Form_Load()
    Module1.FillListWithFonts List1
End Sub

Place the following code in a module. The third argument in the definition of the EnumFontFamilies function is a Long that represents a procedure. The argument must contain the address of the procedure, rather than the value that the procedure returns. In the call to EnumFontFamilies, the third argument requires the AddressOf operator to return the address of the EnumFontFamProc procedure, which is the name of the callback procedure you supply when calling the Windows API function, EnumFontFamilies. Windows calls EnumFontFamProc once for each of the font families on the system when you pass AddressOf EnumFontFamProc to EnumFontFamilies. The last argument passed to EnumFontFamilies specifies the list box in which the information is displayed.

'Font enumeration types
Public Const LF_FACESIZE = 32
Public Const LF_FULLFACESIZE = 64

Type LOGFONT
        lfHeight As Long
        lfWidth As Long
        lfEscapement As Long
        lfOrientation As Long
        lfWeight As Long
        lfItalic As Byte
        lfUnderline As Byte
        lfStrikeOut As Byte
        lfCharSet As Byte
        lfOutPrecision As Byte
        lfClipPrecision As Byte
        lfQuality As Byte
        lfPitchAndFamily As Byte
        lfFaceName(LF_FACESIZE) As Byte
End Type

Type NEWTEXTMETRIC
        tmHeight As Long
        tmAscent As Long
        tmDescent As Long
        tmInternalLeading As Long
        tmExternalLeading As Long
        tmAveCharWidth As Long
        tmMaxCharWidth As Long
        tmWeight As Long
        tmOverhang As Long
        tmDigitizedAspectX As Long
        tmDigitizedAspectY As Long
        tmFirstChar As Byte
        tmLastChar As Byte
        tmDefaultChar As Byte
        tmBreakChar As Byte
        tmItalic As Byte
        tmUnderlined As Byte
        tmStruckOut As Byte
        tmPitchAndFamily As Byte
        tmCharSet As Byte
        ntmFlags As Long
        ntmSizeEM As Long
        ntmCellHeight As Long
        ntmAveWidth As Long
End Type

' ntmFlags field flags
Public Const NTM_REGULAR = &H40&
Public Const NTM_BOLD = &H20&
Public Const NTM_ITALIC = &H1&

'  tmPitchAndFamily flags
Public Const TMPF_FIXED_PITCH = &H1
Public Const TMPF_VECTOR = &H2
Public Const TMPF_DEVICE = &H8
Public Const TMPF_TRUETYPE = &H4

Public Const ELF_VERSION = 0
Public Const ELF_CULTURE_LATIN = 0

'  EnumFonts Masks
Public Const RASTER_FONTTYPE = &H1
Public Const DEVICE_FONTTYPE = &H2
Public Const TRUETYPE_FONTTYPE = &H4

Declare Function EnumFontFamilies Lib "gdi32" Alias _
    "EnumFontFamiliesA" _
    (ByVal hDC As Long, ByVal lpszFamily As String, _
    ByVal lpEnumFontFamProc As Long, LParam As Any) As Long
Declare Function GetDC Lib "user32" (ByVal hWnd As Long) As Long
Declare Function ReleaseDC Lib "user32" (ByVal hWnd As Long, _
    ByVal hDC As Long) As Long

Function EnumFontFamProc(lpNLF As LOGFONT, lpNTM As NEWTEXTMETRIC, _
    ByVal FontType As Long, LParam As ListBox) As Long
Dim FaceName As String
Dim FullName As String
    FaceName = StrConv(lpNLF.lfFaceName, vbUnicode)
    LParam.AddItem Left$(FaceName, InStr(FaceName, vbNullChar) - 1)
    EnumFontFamProc = 1
End Function

Sub FillListWithFonts(LB As ListBox)
Dim hDC As Long
    LB.Clear
    hDC = GetDC(LB.hWnd)
    EnumFontFamilies hDC, vbNullString, AddressOf EnumFontFamProc, LB
    ReleaseDC LB.hWnd, hDC
End Sub


And Operator

Used to perform a logical conjunction on two expressions.

Arguments

Part
Description
result
Required; any Boolean expressiondefboolean@veendf98.chm.
expression1
Required; any expression.
expression2
Required; any expression.

Remarks

If both expressions evaluate to True, result is True. If the second expression evaluates to False, result is False. If the first expression evaluates to False, the second expression is not evaluated and result is False. The following table illustrates how result is determined:

If expression1 is | And expression2 is | The result is
True | True | True
True | False | False
False | (not evaluated) | False
False | (not evaluated) | False

See Also

Example


And Operator Example

This example uses the And operator to perform a logical conjunction on two expressions.

Dim A, B, C, D, MyCheck
A = 10: B = 8: C = 6: D = Null   ' Initialize variables.
MyCheck = A > B And B > C   ' Returns True.
MyCheck = B > A And B > C   ' Returns False.
MyCheck = A > B And B > D   ' Returns Null.
MyCheck = A And B   ' Returns 8 (bitwise comparison).


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Arithmetic Operators

^ Operator

* Operator

/ Operator

\ Operator

Mod Operator

+ Operator

- Operator

See Also


BitAnd Operator

Used to perform a logical conjunction on two numeric expressions.

Arguments

result
Required; any numeric variable.
expression1
Required; any expression.
expression2
Required; any expression.

Remarks

The BitAnd operator performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table:

If bit in expression1 is | And bit in expression2 is | The result is
0 | 0 | 0
0 | 1 | 0
1 | 0 | 0
1 | 1 | 1

See Also

BitNot BitOr BitXor


BitNot Operator

Used to perform logical negation on a numeric expression.

Arguments

result
Required; any numeric variable.
expression
Required; any expression.

Remarks

The Not operator inverts the bit values of any variable and sets the corresponding bit in result according to the following table:

If bit in expression is | Then bit in result is
0 | 1
1 | 0

See Also

BitAnd | BitOr BitXor


BitOr Operator

Used to perform a logical disjunction on two numeric expressions.

Arguments

result
Required; any numeric variable.
expression1
Required; any expression.
expression2
Required; any expression.

Remarks

The Or operator performs a bitwise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following table:

If bit in expression1 is | And bit in expression2 is | Then result is
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 1

See Also

BitAnd | BitNot BitXor


BitXor Operator

Used to perform a logical exclusion on two expressions.

Arguments

Part
Description
result
Optional; any numeric variable.
expression1
Required; any expression.
expression2
Required; any expression.

Remarks

The BitXor operator performs as a bitwise operator. A bit-wise comparison of two expressions using exclusive-or logic to form the result, as shown in the following table:

If bit in expression1 is | And bit in expression2 is | Then result is
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0

See Also

BitAnd | BitNot | BitOr


Comparison Operators

Used to compare expressions.

Arguments

Part
Description
result
Required; any numeric variable.
expression
Required; any expression.
comparisonoperator
Required; any comparison operator.
object
Required; any object name.
string
Required; any string expression.
pattern
Required; any string expression or range of characters.

Remarks

The following table contains a list of the comparison operators and the conditions that determine whether result is True or False.

Operator | True if | False if
< (Less than) | expression1 < expression2 | expression1 >= expression2
<= (Less than or equal to) | expression1 <= expression2 | expression1 > expression2
> (Greater than) | expression1 > expression2 | expression1 <= expression2
>= (Greater than or equal to) | expression1 >= expression2 | expression1 < expression2
= (Equal to) | expression1 = expression2 | expression1 <> expression2
<> (Not equal to) | expression1 <> expression2 | expression1 = expression2

Note The Is and Like operators have specific comparison functionality that differs from the operators in the table.

If expression1 and expression2 are both Object expressions, their underlying type determines how they are compared. The following table shows how the expressions are compared or the result from the comparison, depending on the underlying type of the Object:

Question: Will we need a table of some kind?

When a Single is compared to a Double, the Single is converted to a Double.

Similarly, when a Decimal is compared with a Single or Double, the Decimal will be converted to a Single or Double. For Decimal, any fractional value less than 1E-28 may be lost, or an overflow error can occur. Such fractional value loss may cause two values to compare as equal when they are not.

See Also

Example


Comparison Operators Example

This example shows various uses of comparison operators, which you use to compare expressions.

Dim MyResult, Var1, Var2
MyResult = (45 < 35)   ' Returns False.
MyResult = (45 = 45)   ' Returns True.
MyResult = (4 <> 3)   ' Returns True.
MyResult = ("5" > "4")   ' Returns True.

Var1 = "5": Var2 = 4   ' Initialize variables.
MyResult = (Var1 > Var2)   ' Returns True.

Var1 = 5: Var2 = Empty
MyResult = (Var1 > Var2)   ' Returns True.

Var1 = 0: Var2 = Empty
MyResult = (Var1 = Var2)   ' Returns True.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Concatenation Operators

& Operator

+ Operator

See Also


GetType Operator

Used to return the class object of the specified type.

GetType(typename)Parameters

typename

The name of the type within the class object.Remarks

Examples:

GetType(Integer)‘returns the integer class object

GetType(Project1.Type1)‘returns the class object for Project1.Type1

GetType(String(*))‘returns the class object for 1D string arrays

See Also

EnterLinks


Is Operator

Used to compare two object reference variables.

Arguments

Part
Description
result
Required; any numeric variable.
object1
Required; any object name.
object2
Required; any object name.

Remarks

The Is Operator determines if two object references refer to the same object. However, it does not perform value comparisons. If object1 and object2 both refer to the same object, result is True; if they do not, result is False. Two variables can be made to refer to the same object in several ways.

See Also

Example


Is Operator Example

This example uses the Is operator to compare two object references. The object variable names are generic and used for illustration purposes only.

Dim MyObject, YourObject, ThisObject, OtherObject, ThatObject, MyCheck
Set YourObject = MyObject   ' Assign object references.
Set ThisObject = MyObject
Set ThatObject = OtherObject
MyCheck = YourObject Is ThisObject   ' Returns True.
MyCheck = ThatObject Is ThisObject   ' Returns False.
' Assume MyObject <> OtherObject
MyCheck = MyObject Is ThatObject   ' Returns False.


Like Operator

Used to compare two strings.

Arguments

Part
Description
result
Required; any numeric variable.
string
Required; any string expression.
pattern
Required; any string expression conforming to the pattern-matching conventions described in Remarks.

Remarks

If string matches pattern, result is True; if there is no match, result is False. However, if either string or pattern is stated as Nothing, a Variable Not Set error occurs.

The behavior of the Like operator depends on the Option Compare statement. The default string-comparison method for each module is Option Compare Binary.

Option Compare Binary results in string comparisons based on a sort order derived from the internal binary representations of the characters. Sort order is determined by the code page. In the following example, a typical binary sort order is shown:

A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø

Option Compare Text results in string comparisons based on a case-insensitive, textual sort order determined by your system's locale. When you sort The same characters using Option Compare Text, the following text sort order is produced:

(A=a) < (À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø)

Built-in pattern matching provides a versatile tool for string comparisons. The pattern-matching features allow you to use wildcard characters, character lists, or character ranges, in any combination, to match strings. The following table shows the characters allowed in pattern and what they match:

Characters in pattern | Matches in string
? | Any single character.
* | Zero or more characters.
# | Any single digit (0–9).
[charlist] | Any single character in charlist.
[!charlist] | Any single character not in charlist.

A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any single character in string and can include almost any character code, including digits.

Note To match the special characters left bracket ([), question mark (?), number sign (#), and asterisk (*), enclose them in brackets. The right bracket (]) can't be used within a group to match itself, but it can be used outside a group as an individual character.

By using a hyphen (–) to separate the upper and lower bounds of the range, charlist can specify a range of characters. For example, [A-Z] results in a match if the corresponding character position in string contains any uppercase letters in the range A–Z. Multiple ranges are included within the brackets without delimiters.

The meaning of a specified range depends on the character ordering valid at run time (as determined by Option Compare and the locale setting of the system the code is running on). Using the Option Compare Binary example, the range [A–E] matches A, B and E. With Option Compare Text, [A–E] matches A, a, À, à, B, b, E, e. The range does not match Ê or ê because accented characters fall after unaccented characters in the sort order.

Other important rules for pattern matching include the following:

  • An exclamation point (!) at the beginning of charlist means that a match is made if any character except the characters in charlist is found in string. When used outside brackets, the exclamation point matches itself.
  • A hyphen (–) can appear either at the beginning (after an exclamation point if one is used) or at the end of charlist to match itself. In any other location, the hyphen is used to identify a range of characters.
  • When a range of characters is specified, they must appear in ascending sort order (from lowest to highest). [A-Z] is a valid pattern, but [Z-A] is not.
  • The character sequence [] is considered a zero-length string ("").

In some languages, there are special characters in the alphabet that represent two separate characters. For example, several languages use the character "æ" to represent the characters "a" and "e" when they appear together. The Like operator recognizes that the single special character and the two individual characters are equivalent.

When a language that uses a special character is specified in the system locale settings, an occurrence of the single special character in either pattern or string matches the equivalent 2-character sequence in the other string. Similarly, a single special character in pattern enclosed in brackets (by itself, in a list, or in a range) matches the equivalent 2-character sequence in string.

See Also

Example


Like Operator Example

This example uses the Like operator to compare a string to a pattern.

Dim MyCheck
MyCheck = "aBBBa" Like "a*a"   ' Returns True.
MyCheck = "F" Like "[A-Z]"   ' Returns True.
MyCheck = "F" Like "[!A-Z]"   ' Returns False.
MyCheck = "a2a" Like "a#a"   ' Returns True.
MyCheck = "aM5b" Like "a[L-P]#[!c-e]"   ' Returns True.
MyCheck = "BAT123khg" Like "B?T*"   ' Returns True.
MyCheck = "CAT123khg" Like "B?T*"   ' Returns False.


Logical Operators

And Operator Not Operator

Or Operator

Xor Operator

See Also

= Operator

Used to compare two expressions, returning a boolean .

expression = expression

Arguments

expression
Any combination of variables, operators, constants, functions, and names of fields, controls, and properties that evaluates to a single value.

Remarks

When you compare two expressions, the result is True if both expressions are equal; otherwise, the result is False.

See Also


Mod Operator

Used to divide two numbers and return only the remainder.

Arguments

Part
Description
result
Required; any numeric variable.
number1
Required; any numeric expression.
number2
Required; any numeric expression.

Remarks

The modulus, or remainder, operator divides number1 by number2 (rounding floating-point numbers to integers) and returns only the remainder as result. For example, in the following expression, A (result) equals 5.

A = 8 Mod 3

Usually, the data type of result is a Byte, Byteobject, Integer, Integerobject, Long, or Object containing a Long, regardless of whether or not result is a whole number. Any fractional portion is truncated. However, if any expression is stated as Nothing, a Variable Not Set error occurs. Any expression that is Empty is treated as 0.

See Also

Example


Mod Operator Example

This example uses the Mod operator to divide two numbers and return only the remainder. If either number is a floating-point number, it is first rounded to an integer.

Dim MyResult
MyResult = 10 Mod 5   ' Returns 0.
MyResult = 10 Mod 3   ' Returns 1.
MyResult = 12 Mod 4.3   ' Returns 0.
MyResult = 12.6 Mod 5   ' Returns 3.


Not Operator

Used to perform logical negation on an expression.

Arguments

Part
Description
result
Required; any Boolean expressiondefboolean@veendf98.chm.
expression
Required; any expression.

Remarks

The following table illustrates how result is determined:

If expression is | Then result is
True | False
False | True

See Also

Example


Not Operator Example

This example uses the Not operator to perform logical negation on an expression.

Dim A, B, C, D, MyCheck
A = 10: B = 8: C = 6: D = Null   ' Initialize variables.
MyCheck = Not(A > B)   ' Returns False.
MyCheck = Not(B > A)   ' Returns True.
MyCheck = Not(C > D)   ' Returns Null.
MyCheck = Not A   ' Returns -11 (bitwise comparison).


Or Operator

Used to perform a logical disjunction on two expressions.

Arguments

Part
Description
result
Required; any Boolean expressiondefboolean@veendf98.chm.
expression1
Required; any expression.
expression2
Required; any expression.

Remarks

If either expression evaluates to True, result is True. If the first expression evaluates to True, the second expression is not evaluated, result is True. The following table illustrates how result is determined:

If expression1 is | And expression2 is | Then result is
True | (not evaluated) | True
True | (not evaluated) | True
False | True | True
False | False | False

See Also

Example


Or Operator Example

This example uses the Or operator to perform logical disjunction on two expressions.

Dim A, B, C, D, MyCheck
A = 10: B = 8: C = 6: D = Null   ' Initialize variables.
MyCheck = A > B Or B > C   ' Returns True.
MyCheck = B > A Or B > C   ' Returns True.
MyCheck = A > B Or B > D   ' Returns True.
MyCheck = B > D Or B > A   ' Returns Null.
MyCheck = A Or B   ' Returns 10 (bitwise comparison).


Xor Operator

Used to perform a logical exclusion on two expressions.

Arguments

Part
Description
result
Optional; any numeric variable.
expression1
Required; any expression.
expression2
Required; any expression.

Remarks

If one, and only one, of the expressions evaluates to True, result is True. However, if either expression is stated as Nothing, a Variable Not Set error occurs.

If expression1 is | And expression2 is | Then result is
True | True | False
True | False | True
False | True | True
False | False | False

The Xor operator performs as both a logical and bitwise operator. A bit-wise comparison of two expressions using exclusive-or logic to form the result, as shown in the following table:

If bit in expression1 is | And bit in expression2 is | Then result is
0 | 0 | 0
0 | 1 | 1
1 | 0 | 1
1 | 1 | 0

See Also

Example


Xor Operator Example

This example uses the Xor operator to perform logical exclusion on two expressions.

Dim A, B, C, D, MyCheck
A = 10: B = 8: C = 6: D = Null   ' Initialize variables.
MyCheck = A > B Xor B > C   ' Returns False.
MyCheck = B > A Xor B > C   ' Returns True.
MyCheck = B > A Xor C > B   ' Returns False.
MyCheck = B > D Xor A > B   ' Returns Null.
MyCheck = A Xor B   ' Returns 2 (bitwise comparison).


Properties (Visual Basic for Applications)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Properties (Visual Basic Language Reference)

AtEndOfLine Property

AtEndOfStream Property

Attributes Property

AvailableSpace Property

Calendar Property

Column Property

CompareMode Property

Count Property

Count Property

DateCreated Property

DateLastAccessed Property

DateLastModified Property

Description Property

Drive Property

DriveLetter Property

Drives Property

DriveType Property

Files Property

FileSystem Property

FreeSpace Property

HelpContext Property

HelpFile Property

IsReady Property

IsRootFolder Property

Item Property

Key Property

LastDLLError Property

Line Property

Name Property

Number Property

ParentFolder Property

Path Property

RootFolder Property

SerialNumber Property

ShareName Property

ShortName Property

ShortPath Property

Size Property

Source Property

SubFolders Property

TotalSize Property

Type Property

VolumeName Property


AtEndOfLine Property

Read-only property that returns True if the file pointer immediately precedes the end-of-line marker in a TextStream file; False if it does not.

object.AtEndOfLine

The object is always the name of a TextStream object.

Remarks

The AtEndOfLine property applies only to TextStream files that are open for reading; otherwise, an error occurs.

The following code illustrates the use of the AtEndOfLine property:

Dim fs, a, retstring
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.OpenTextFile("c:\testfile.txt", ForReading, False)
Do While a.AtEndOfLine <> True
    retstring = a.Read(1)
    ...
Loop
a.Close

See Also

AtEndOfStream Property | Column Property | Line Property

Applies To: TextStream Object


AtEndOfStream Property

Read-only property that returns True if the file pointer is at the end of a TextStream file; False if it is not.

object.AtEndOfStream

The object is always the name of a TextStream object.

Remarks

The AtEndOfStream property applies only to TextStream files that are open for reading; otherwise, an error occurs.

The following code illustrates the use of the AtEndOfStream property:

Dim fs, a, retstring
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.OpenTextFile("c:\testfile.txt", ForReading, False)
Do While a.AtEndOfStream <> True
    retstring = a.ReadLine
    ...
Loop
a.Close

See Also

AtEndOfLine Property | Column Property | Line Property

Applies To: TextStream Object


Attributes Property

Sets or returns the attributes of files or folders. Read/write or read-only, depending on the attribute.

object.Attributes [= newattributes]

Arguments

object
Required. Always the name of a File or Folder object.
newattributes
Optional. If provided, newattributes is the new value for the attributes of the specified object.

Settings

The newattributes argument can have any of the following values or any logical combination of the following values:

Constant | Value | Description
Normal | 0 | Normal file. No attributes are set.
ReadOnly | 1 | Read-only file. Attribute is read/write.
Hidden | 2 | Hidden file. Attribute is read/write.
System | 4 | System file. Attribute is read/write.
Volume | 8 | Disk drive volume label. Attribute is read-only.
Directory | 16 | Folder or directory. Attribute is read-only.
Archive | 32 | File has changed since last backup. Attribute is read/write.
Alias | 64 | Link or shortcut. Attribute is read-only.

Remarks

The following code illustrates the use of the Attributes property with a file:

Sub SetClearArchiveBit(filespec)
    Dim fs, f, r
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(fs.GetFileName(filespec))
    If f.attributes and 32 Then
        r = MsgBox("The Archive bit is set, do you want to clear it?", vbYesNo, "Set/Clear Archive Bit")
        If r = vbYes Then
            f.attributes = f.attributes - 32
            MsgBox "Archive bit is cleared."
        Else
            MsgBox "Archive bit remains set."
        End If
    Else
        r = MsgBox("The Archive bit is not set. Do you want to set it?", vbYesNo, "Set/Clear Archive Bit")
        If r = vbYes Then
            f.attributes = f.attributes + 32
            MsgBox "Archive bit is set."
        Else
            MsgBox "Archive bit remains clear."
        End If
    End If
End Sub

See Also

DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | Type PropertyApplies To: File Object | Folder Object


AvailableSpace Property

Returns the amount of space available to a user on the specified drive or network share.

object.AvailableSpace

The object is always a Drive object.

Remarks

The value returned by the AvailableSpace property is typically the same as that returned by the FreeSpace property. Differences may occur between the two values for computer systems that support quotas.

The following code illustrates the use of the AvailableSpace property:

Sub ShowAvailableSpace(drvPath)
    Dim fs, d, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(fs.GetDriveName(drvPath))
    s = "Drive " & UCase(drvPath) & " - "
    s = s & d.VolumeName  & vbCrLf
    s = s & "Available Space: " & FormatNumber(d.AvailableSpace/1024, 0)
    s = s & " Kbytes"
    MsgBox s
End Sub

See Also

DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property | VolumeName Property

Applies To: Drive Object


Column Property

Read-only property that returns the column number of the current character position in a TextStream file.

object.Column

The object is always the name of a TextStream object.

Remarks

After a newline character has been written, but before any other character is written, Column is equal to 1.

See Also

AtEndOfLine Property | AtEndOfStream Property | Line PropertyApplies To: TextStream Object


CompareMode Property

Sets and returns the comparison mode for comparing string keys in a Dictionary object.

object.CompareMode[ = compare]

Arguments

object
Required. Always the name of a Dictionary object.
compare
Optional. If provided, compare is a value representing the comparison mode used by functions such as StrComp.

Settings

The compare argument can have the following values:

Constant | Value | Description
UseCompareOption | –1 | Performs a comparison using the setting of the Option Compare statement.
BinaryCompare | 0 | Performs a binary comparison.
TextCompare | 1 | Performs a textual comparison.

Remarks

An error occurs if you try to change the comparison mode of a Dictionary object that already contains data.

The CompareMode property uses the same values as the compare argument for the StrComp function. Values greater than 2 can be used to refer to comparisons using specific Locale IDs (LCID).

See Also

Count Property | Item Property | Key Property

Applies To: Dictionary Object


Count Property (Visual Basic for Applications)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Count Property

Returns a Long (long integer) containing the number of objects in a collection. Read-only.

See Also

Example

Add Method | Item Method | Item Method (VBA Add-In Object Model) | Remove MethodApplies To: Collection Object | Licenses Collection | LinkedWindows Collection | Windows Collection


Count Property Example

This example uses the Collection object's Count property to specify how many iterations are required to remove all the elements of the collection called MyClasses. When collections are numerically indexed, the base is 1 by default. Since collections are reindexed automatically when a removal is made, the following code removes the first member on each iteration.

Dim Num, MyClasses
For Num = 1 To MyClasses.Count   ' Remove name from the collection.
   MyClasses.Remove 1   ' Default collection numeric indexes
Next   ' begin at 1.


Count Property (FileSystemObject object)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Count Property

Returns the number of items in a collection or Dictionary object. Read-only.

object.Count

The object is always the name of one of the items in the Applies To list.

Remarks

The following code illustrates use of the Count property:

Dim a, d, i             'Create some variables
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "Athens"     'Add some keys and items.
d.Add "b", "Belgrade"
d.Add "c", "Cairo"
a = d.Keys              'Get the keys
For i = 0 To d.Count -1 'Iterate the array
    Print a(i)          'Print key
Next
...

See Also

CompareMode Property | Item Property | Key PropertyApplies To: Dictionary Object | Drives Collection | Files Collection | Folders Collection


DateCreated Property

Returns the date and time that the specified file or folder was created. Read-only.

object.DateCreated

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the DateCreated property with a file:

Sub ShowFileInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = "Created: " & f.DateCreated
    MsgBox s
End Sub

See Also

Attributes Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | Type Property

Applies To: File Object | Folder Object


DateLastAccessed Property

Returns the date and time that the specified file or folder was last accessed. Read-only.

object.DateLastAccessed

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the DateLastAccessed property with a file:

Sub ShowFileAccessInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = UCase(filespec) & vbCrLf
    s = s & "Created: " & f.DateCreated & vbCrLf
    s = s & "Last Accessed: " & f.DateLastAccessed & vbCrLf
    s = s & "Last Modified: " & f.DateLastModified
    MsgBox s, 0, "File Access Info"
End Sub
Important This method depends on the underlying operating system for its behavior. If the operating system does not support providing time information, none will be returned.

See Also

Attributes Property | DateCreated Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | Type PropertyApplies To: File Object | Folder Object


DateLastModified Property

Returns the date and time that the specified file or folder was last modified. Read-only.

object.DateLastModified

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the DateLastModified property with a file:

Sub ShowFileAccessInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = UCase(filespec) & vbCrLf
    s = s & "Created: " & f.DateCreated & vbCrLf
    s = s & "Last Accessed: " & f.DateLastAccessed & vbCrLf
    s = s & "Last Modified: " & f.DateLastModified
    MsgBox s, 0, "File Access Info"
End Sub

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | Type Property

Applies To: File Object | Folder Object


Description Property (Visual Basic for Applications)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Description Property

Returns or sets a string expression containing a descriptive string associated with an object. Read/write.

For the Err object, returns or sets a descriptive string associated with an error.

Remarks

The Description property setting consists of a short description of the error. Use this property to alert the user to an error that you either can't or don't want to handle. When generating a user-defined error, assign a short description of your error to the Description property. If Description isn’t filled in, and the value of Number corresponds to a Visual Basic run-time error, the string returned by the Error function is placed in Description when the error is generated.

See Also

Example

Err Object | Error Function | GUID Property | HelpContext Property | HelpFile Property | LastDLLError Property | Major Property | Minor Property | Number Property | Source Property | Version PropertyApplies To: Err Object | Error Object (Data Report Designer) | WebClassError Object


Description Property Example

This example assigns a user-defined message to the Description property of the Err object.

Err.Description = "It was not possible to access an object necessary " _
& "for this operation."


Drive Property

Returns the drive letter of the drive on which the specified file or folder resides. Read-only.

object.Drive

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the Drive property:

Sub ShowFileAccessInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = f.Name & " on Drive " & UCase(f.Drive) & vbCrLf
    s = s & "Created: " & f.DateCreated & vbCrLf
    s = s & "Last Accessed: " & f.DateLastAccessed & vbCrLf
    s = s & "Last Modified: " & f.DateLastModified
    MsgBox s, 0, "File Access Info"
End Sub

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortPath Property | Size Property | SubFolders Property | Type PropertyApplies To: File Object | Folder Object


DriveLetter Property

Returns the drive letter of a physical local drive or a network share. Read-only.

object.DriveLetter

The object is always a Drive object.

Remarks

The DriveLetter property returns a zero-length string ("") if the specified drive is not associated with a drive letter, for example, a network share that has not been mapped to a drive letter.

The following code illustrates the use of the DriveLetter property:

Sub ShowDriveLetter(drvPath)
    Dim fs, d, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(fs.GetDriveName(drvPath))
    s = "Drive " & d.DriveLetter & ": - "
    s = s & d.VolumeName  & vbCrLf
    s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
    s = s & " Kbytes"
    MsgBox s
End Sub

See Also

AvailableSpace Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | ShortName Property | TotalSize Property | VolumeName PropertyApplies To: Drive Object


Drives Property

Returns a Drives collection consisting of all Drive objects available on the local machine.

object.Drives

The object is always a FileSystemObject.

Remarks

Removable-media drives need not have media inserted for them to appear in the Drives collection.

You can iterate the members of the Drives collection using a For Each...Next construct as illustrated in the following code:

Sub ShowDriveList
    Dim fs, d, dc, s, n
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set dc = fs.Drives
    For Each d in dc
        s = s & d.DriveLetter & " - "
        If d.DriveType = 3 Then
            n = d.ShareName
        Else
            n = d.VolumeName
        End If
        s = s & n & vbCrLf
    Next
    MsgBox s
End Sub

See Also

Drives Collection | Files PropertyApplies To: FileSystemObject Object


DriveType Property

Returns a value indicating the type of a specified drive.

object.DriveType

The object is always a Drive object.

Remarks

The following code illustrates the use of the DriveType property:

Sub ShowDriveType(drvpath)
    Dim fs, d, s, t
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(drvpath)
    Select Case d.DriveType
        Case 0: t = "Unknown"
        Case 1: t = "Removable"
        Case 2: t = "Fixed"
        Case 3: t = "Network"
        Case 4: t = "CD-ROM"
        Case 5: t = "RAM Disk"
    End Select
    s = "Drive " & d.DriveLetter & ": - " & t
    MsgBox s
End Sub

See Also

AvailableSpace Property | DriveLetter Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property | VolumeName PropertyApplies To: Drive Object


Files Property

Returns a Files collection consisting of all File objects contained in the specified folder, including those with hidden and system file attributes set.

object.Files

The object is always a Folder object.

Remarks

The following code illustrates the use of the Files property:

Sub ShowFileList(folderspec)
    Dim fs, f, f1, fc, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(folderspec)
    Set fc = f.Files
    For Each f1 in fc
        s = s & f1.name
        s = s &  vbCrLf
    Next
    MsgBox s
End Sub

See Also

DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Drives Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | Type PropertyApplies To: Folder Object


FileSystem Property

Returns the type of file system in use for the specified drive.

object.FileSystem

The object is always a Drive object.

Remarks

Available return types include FAT, NTFS, and CDFS.

The following code illustrates the use of the FileSystem property:

Sub ShowFileSystemType
    Dim fs,d, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive("e:")
    s = d.FileSystem
    MsgBox s
End Sub

See Also

AvailableSpace Property | DriveLetter Property | DriveType Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property | VolumeName PropertyApplies To: Drive Object


FreeSpace Property

Returns the amount of free space available to a user on the specified drive or network share. Read-only.

object.FreeSpace

The object is always a Drive object.

Remarks

The value returned by the FreeSpace property is typically the same as that returned by the AvailableSpace property. Differences may occur between the two for computer systems that support quotas.

The following code illustrates the use of the FreeSpace property:

Sub ShowFreeSpace(drvPath)
    Dim fs, d, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(fs.GetDriveName(drvPath))
    s = "Drive " & UCase(drvPath) & " - "
    s = s & d.VolumeName  & vbCrLf
    s = s & "Free Space: " & FormatNumber(d.FreeSpace/1024, 0)
    s = s & " Kbytes"
    MsgBox s
End Sub

See Also

AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property | VolumeName PropertyApplies To: Drive Object


HelpContext Property (Visual Basic for Applications)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HelpContext Property

Returns or sets a string expression containing the context ID for a topic in a Help file. Read/write.

Remarks

The HelpContext property is used to automatically display the Help topic specified in the HelpFile property. If both HelpFile and HelpContext are empty, the value of Number is checked. If Number corresponds to a Visual Basic run-time error value, then the Visual Basic Help context ID for the error is used. If the Number value doesn’t correspond to a Visual Basic error, the contents screen for the Visual Basic Help file is displayed.

Note You should write routines in your application to handle typical errors. When programming with an object, you can use the object's Help file to improve the quality of your error handling, or to display a meaningful message to your user if the error isn’t recoverable.

See Also

Example

Description Property | Err Object | HelpFile Property | LastDLLError Property | Number Property | Source PropertyApplies To: Err Object


HelpContext Property Example

This example uses the HelpContext property of the Err object to show the Visual Basic Help topic for the Overflow error.

Dim Msg
Err.Clear
On Error Resume Next
Err.Raise 6 ' Generate "Overflow" error.
If Err.Number <> 0 Then
   Msg = "Press F1 or HELP to see " & Err.HelpFile & " topic for" & _
   " the following HelpContext: " & Err.HelpContext
   MsgBox Msg, , "Error: " & Err.Description, Err.HelpFile, _
Err.HelpContext
End If


HelpFile Property

Returns or sets a string expression the fully qualified path to a Help file. Read/write.

Remarks

If a Help file is specified in HelpFile, it is automatically called when the user presses the Help button (or the F1 KEY) in the error message dialog box. If the HelpContext property contains a valid context ID for the specified file, that topic is automatically displayed. If no HelpFile is specified, the Visual Basic Help file is displayed.

Note You should write routines in your application to handle typical errors. When programming with an object, you can use the object's Help file to improve the quality of your error handling, or to display a meaningful message to your user if the error isn’t recoverable.

See Also

Example

Description Property | Err Object | HelpContext Property | LastDLLError Property | Number Property | Source PropertyApplies To: Err Object


HelpFile Property Example

This example uses the HelpFile property of the Err object to start the Help system. By default, the HelpFile property contains the name of the Visual Basic Help file.

Dim Msg
Err.Clear
On Error Resume Next   ' Suppress errors for demonstration purposes.
Err.Raise 6   ' Generate "Overflow" error.
Msg = "Press F1 or HELP to see " & Err.HelpFile & _
" topic for this error"
MsgBox Msg, , "Error: " & Err.Description,Err.HelpFile, Err.HelpContext


IsReady Property

Returns True if the specified drive is ready; False if it is not.

object.IsReady

The object is always a Drive object.

Remarks

For removable-media drives and CD-ROM drives, IsReady returns True only when the appropriate media is inserted and ready for access.

The following code illustrates the use of the IsReady property:

Sub ShowDriveInfo(drvpath)
    Dim fs, d, s, t
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(drvpath)
    Select Case d.DriveType
        Case 0: t = "Unknown"
        Case 1: t = "Removable"
        Case 2: t = "Fixed"
        Case 3: t = "Network"
        Case 4: t = "CD-ROM"
        Case 5: t = "RAM Disk"
    End Select
    s = "Drive " & d.DriveLetter & ": - " & t
    If d.IsReady Then
        s = s & vbCrLf & "Drive is Ready."
    Else
        s = s & vbCrLf & "Drive is not Ready."
    End If
    MsgBox s
End Sub

See Also

AvailableSpace Property | DriveExists Method | DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize Property | VolumeName PropertyApplies To: Drive Object


IsRootFolder Property

Returns True if the specified folder is the root folder; False if it is not.

object.IsRootFolder

The object is always a Folder object.

Remarks

The following code illustrates the use of the IsRootFolder property:

Dim fs
Set fs = CreateObject("Scripting.FileSystemObject")
Sub DisplayLevelDepth(pathspec)
    Dim f, n
    Set f = fs.GetFolder(pathspec)
    If f.IsRootFolder Then
        MsgBox "The specified folder is the root folder."
    Else
        Do Until f.IsRootFolder
            Set f = f.ParentFolder
            n = n + 1
        Loop
        MsgBox "The specified folder is nested " & n & " levels deep."
    End If
End Sub

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | Type PropertyApplies To: Folder Object


Item Property (FileSystemObject object)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Item Property

Sets or returns an item for a specified key in a Dictionary object. For collections, returns an item based on the specified key. Read/write.

object.Item(key) [= newitem]

Arguments

object
Required. Always the name of a collection or Dictionary object.
key
Required. Key associated with the item being retrieved or added.
newitem
Optional. Used for Dictionary object only; no application for collections. If provided, newitem is the new value associated with the specified key.

Remarks

If key is not found when changing an item, a new key is created with the specified newitem. If key is not found when attempting to return an existing item, a new key is created and its corresponding item is left empty.

See Also

CompareMode Property | Count Property | Key PropertyApplies To: Dictionary Object | Drives Collection | Files Collection | Folders Collection


Key Property

Sets a key in a Dictionary object.

object.Key(key) = newkey

Arguments

object
Required. Always the name of a Dictionary object.
key
Required. Key value being changed.
newkey
Required. New value that replaces the specified key.

Remarks

If key is not found when changing a key, a run-time error will occur.

See Also

CompareMode Property | Count Property | Item PropertyApplies To: Dictionary Object


LastDLLError Property

Returns a system error code produced by a call to a dynamic-link library (DLL). Read-only.

Remarks

The LastDLLError property applies only to DLL calls made from Visual Basic code. When such a call is made, the called function usually returns a code indicating success or failure, and the LastDLLError property is filled. Check the documentation for the DLL's functions to determine the return values that indicate success or failure. Whenever the failure code is returned, the Visual Basic application should immediately check the LastDLLError property. No exception is raised when the LastDLLError property is set.

See Also

Example

Declare Statement | Description Property | Err Object | HelpContext Property | HelpContextID Property (VBA Add-In Object Model) | HelpFile Property | Number Property | Source PropertyApplies To: Err Object


LastDLLError Property Example

When pasted into a UserForm module, the following code causes an attempt to call a DLL function. The call fails because the argument that is passed in (a null pointer) generates an error, and in any event, SQL can’t be cancelled if it isn’t running. The code following the call checks the return of the call, and then prints at the LastDLLError property of the Err object to reveal the error code. On systems without DLLs, LastDLLError always returns zero.

 Private Declare Function SQLCancel Lib "ODBC32.dll" _
 (ByVal hstmt As Long) As Integer

Private Sub UserForm_Click()
   Dim RetVal
   ' Call with invalid argument.
   RetVal = SQLCancel(myhandle&)
   ' Check for SQL error code.
   If RetVal = -2 Then
      'Display the information code.
      MsgBox "Error code is :" & Err.LastDllError
    End If
End Sub


Line Property

Read-only property that returns the current line number in a TextStream file.

object.Line

The object is always the name of a TextStream object.

Remarks

After a file is initially opened and before anything is written, Line is equal to 1.

See Also

AtEndOfLine Property | AtEndOfStream Property | Column PropertyApplies To: TextStream Object


Name Property (FileSystemObject object)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Name Property

Sets or returns the name of a specified file or folder. Read/write.

object.Name [= newname]

Arguments

object
Required. Always the name of a File or Folder object.
newname
Optional. If provided, newname is the new name of the specified object.

Remarks

The following code illustrates the use of the Name property:

Sub ShowFileAccessInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = f.Name & " on Drive " & UCase(f.Drive) & vbCrLf
    s = s & "Created: " & f.DateCreated & vbCrLf
    s = s & "Last Accessed: " & f.DateLastAccessed & vbCrLf
    s = s & "Last Modified: " & f.DateLastModified
    MsgBox s, 0, "File Access Info"
End Sub

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | Type PropertyApplies To: File Object | Folder Object


Number Property (Visual Basic for Applications)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Number Property

Returns or sets a numeric value specifying an error. Number is the Err object's default property. Read/write.

Remarks

When returning a user-defined error from an object, set Err.Number by adding the number you selected as an error code to the ObjectError constant. For example, you use the following code to return the number 1051 as an error code:

Err.Raise Number := ObjectError + 1051, Source:= "SomeClass"

See Also

Example

Description Property | Err Object | HelpContext Property | HelpContextID Property (VBA Add-In Object Model) | HelpFile Property | LastDLLError Property | Source PropertyApplies To: Err Object | WebClassError Object


Number Property Example

The first example illustrates a typical use of the Number property in an error-handling routine. The second example examines the Number property of the Err object to determine whether an error returned by an Automation object was defined by the object, or whether it was mapped to an error defined by Visual Basic. Note that the constant vbObjectError is a very large negative number that an object adds to its own error code to indicate that the error is defined by the server. Therefore, subtracting it from Err.Number strips it out of the result. If the error is object-defined, the base number is left in MyError, which is displayed in a message box along with the original source of the error. If Err.Number represents a Visual Basic error, then the Visual Basic error number is displayed in the message box.

' Typical use of Number property
Sub test()
   On Error GoTo out

   Dim x, y
   x = 1 / y   ' Create division by zero error
   Exit Sub
   out:
   MsgBox Err.Number
   MsgBox Err.Description
   ' Check for division by zero error
   If Err.Number = 11 Then
      y = y + 1
   End If
   Resume
End Sub

' Using Number property with an error from an
' Automation object
Dim MyError, Msg
' First, strip off the constant added by the object to indicate one
' of its own errors.
MyError = Err.Number - vbObjectError
' If you subtract the vbObjectError constant, and the number is still
' in the range 0-65,535, it is an object-defined error code.
If MyError > 0 And MyError < 65535 Then
   Msg = "The object you accessed assigned this number to the error: " _
          & MyError & ". The originator of the error was: " _
         & Err.Source & ". Press F1 to see originator's Help topic."
' Otherwise it is a Visual Basic error number.
Else
   Msg = "This error (# " & Err.Number & ") is a Visual Basic error" & _
         " number. Press Help button or F1 for the Visual Basic Help" _
         & " topic for this error."
End If
   MsgBox Msg, , "Object Error", Err.HelpFile, Err.HelpContext


ParentFolder Property

Returns the folder object for the parent of the specified file or folder. Read-only.

object.ParentFolder

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the ParentFolder property with a file:

Sub ShowFileAccessInfo(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = UCase(f.Name) & " in " & UCase(f.ParentFolder) & vbCrLf
    s = s & "Created: " & f.DateCreated & vbCrLf
    s = s & "Last Accessed: " & f.DateLastAccessed & vbCrLf
    s = s & "Last Modified: " & f.DateLastModified
    MsgBox s, 0, "File Access Info"
End Sub

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | Path Property | ShortName Property | ShortPath Property | Size Property | Type PropertyApplies To: File Object | Folder Object


Path Property (FileSystemObject object)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Path Property

Returns the path for a specified file, folder, or drive.

object.Path

The object is always a File, Folder, or Drive object.

Remarks

For drive letters, the root drive is not included. For example, the path for the C drive is C:, not C:\.

The following code illustrates the use of the Path property with a File object:

Sub ShowFileAccessInfo(filespec)
    Dim fs, d, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = UCase(f.Path) & vbCrLf
    s = s & "Created: " & f.DateCreated & vbCrLf
    s = s & "Last Accessed: " & f.DateLastAccessed & vbCrLf
    s = s & "Last Modified: " & f.DateLastModified
    MsgBox s, 0, "File Access Info"
End Sub

See Also

Attributes Property | AvailableSpace Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | DriveLetter Property | DriveType Property | Files Property | FileSystem Property | FreeSpace Property | IsReady Property | ParentFolder Property | RootFolder Property | SerialNumber Property | ShareName Property | ShortName Property | ShortPath Property | Size Property | SubFolders Property | TotalSize Property | Type Property | VolumeName PropertyApplies To: Drive Object | File Object | Folder Object


RootFolder Property

Returns a Folder object representing the root folder of a specified drive. Read-only.

object.RootFolder

The object is always a Drive object.

Remarks

All the files and folders contained on the drive can be accessed using the returned Folder object.

See Also

AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | SerialNumber Property | ShareName Property | TotalSize Property | VolumeName PropertyApplies To: Drive Object


SerialNumber Property

Returns the decimal serial number used to uniquely identify a disk volume.

object.SerialNumber

The object is always a Drive object.

Remarks

You can use the SerialNumber property to ensure that the correct disk is inserted in a drive with removable media.

The following code illustrates the use of the SerialNumber property:

Sub ShowDriveInfo(drvpath)
    Dim fs, d, s, t
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(fs.GetDriveName(fs.GetAbsolutePathName(drvpath)))
    Select Case d.DriveType
        Case 0: t = "Unknown"
        Case 1: t = "Removable"
        Case 2: t = "Fixed"
        Case 3: t = "Network"
        Case 4: t = "CD-ROM"
        Case 5: t = "RAM Disk"
    End Select
    s = "Drive " & d.DriveLetter & ": - " & t
    s = s & vbCrLf & "SN: " & d.SerialNumber
    MsgBox s
End Sub

See Also

AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | ShareName Property | TotalSize Property | VolumeName PropertyApplies To: Drive Object


ShareName Property

Returns the network share name for a specified drive.

object.ShareName

The object is always a Drive object.

Remarks

If object is not a network drive, the ShareName property returns a zero-length string ("").

The following code illustrates the use of the ShareName property:

Sub ShowDriveInfo(drvpath)
    Dim fs, d, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(fs.GetDriveName(fs.GetAbsolutePathName(drvpath)))
    s = "Drive " & d.DriveLetter & ": - " & d.ShareName
    MsgBox s
End Sub

See Also

AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | TotalSize Property | VolumeName PropertyApplies To: Drive Object


ShortName Property

Returns the short name used by programs that require the earlier 8.3 naming convention.

object.ShortName

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the ShortName property with a File object:

Sub ShowShortName(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = "The short name for " & "" & UCase(f.Name)
    s = s & "" & vbCrLf
    s = s & "is: " & "" & f.ShortName & ""
    MsgBox s, 0, "Short Name Info"
End Sub

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortPath Property | Size Property | SubFolders Property | Type PropertyApplies To: File Object | Folder Object


ShortPath Property

Returns the short path used by programs that require the earlier 8.3 file naming convention.

object.ShortPath

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the ShortName property with a File object:

Sub ShowShortPath(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFile(filespec)
    s = "The short path for " & "" & UCase(f.Name)
    s = s & "" & vbCrLf
    s = s & "is: " & "" & f.ShortPath & ""
    MsgBox s, 0, "Short Path Info"
End Sub

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | Size Property | SubFolders Property | Type PropertyApplies To: File Object | Folder Object


Size Property (FileSystemObject object)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Size Property

For files, returns the size, in bytes, of the specified file. For folders, returns the size, in bytes, of all files and subfolders contained in the folder.

object.Size

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the Size property with a Folder object:

Sub ShowFolderSize(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(filespec)
    s = UCase(f.Name) & " uses " & f.size & " bytes."
    MsgBox s, 0, "Folder Size Info"
End Sub

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | SubFolders Property | Type PropertyApplies To: File Object | Folder Object


Source Property (Visual Basic for Applications)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Source Property

Returns or sets a string expression specifying the name of the object or application that originally generated the error. Read/write.

Remarks

The Source property specifies a string expression representing the object that generated the error; the expression is usually the object's class name or programmatic ID. Use Source to provide information when your code is unable to handle an error generated in an accessed object. For example, if you access Microsoft Excel and it generates a Division by zero error, Microsoft Excel sets Err.Number to its error code for that error and sets Source to Excel.Application.

When generating an error from code, Source is your application’s programmatic ID.class, Source should contain a name having the form project.class. When an unexpected error occurs in your code, the Source property is automatically filled in. For errors in amodule, Source contains the project name.

See Also

Example

Description Property | Err Object | GetObject Function | HelpContext Property | HelpContextID Property (VBA Add-In Object Model) | HelpFile Property | LastDLLError Property | Number Property | On Error StatementApplies To: Err Object | WebClassError Object


Source Property Example

This example assigns the Programmatic ID of an Automation object created in Visual Basic to the variable MyObjectID, and then assigns that to the Source property of the Err object when it generates an error with the Raise method. When handling errors, you should not use the Source property (or any Err properties other than Number) programmatically. The only valid use of properties other than Number is for displaying rich information to an end user in cases where you can't handle an error. The example assumes that App and MyClass are valid references.

Dim MyClass, MyObjectID, MyHelpFile, MyHelpContext
' An object of type MyClass generates an error and fills all Err object
' properties, including Source, which receives MyObjectID, which is a
' combination of the Title property of the App object and the Name
' property of the MyClass object.
MyObjectID = App.Title & "." & MyClass.Name
Err.Raise   Number := vbObjectError + 894, Source := MyObjectID, _
            Description := "Was not able to complete your task", _
            HelpFile := MyHelpFile, HelpContext := MyHelpContext


SubFolders Property

Returns a Folders collection consisting of all folders contained in a specified folder, including those with Hidden and System file attributes set.

object.SubFolders

The object is always a Folder object.

Remarks

The following code illustrates the use of the SubFolders property:

Sub ShowFolderList(folderspec)
    Dim fs, f, f1, s, sf
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(folderspec)
    Set sf = f.SubFolders
    For Each f1 in sf
        s = s & f1.name
        s = s &  vbCrLf
    Next
    MsgBox s
End Sub

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Drives Property | Files Property | Folders Collection | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | Type PropertyApplies To: Folder Object


TotalSize Property

Returns the total space, in bytes, of a drive or network share.

object.TotalSize

The object is always a Drive object.

Remarks

The following code illustrates the use of the TotalSize property:

Sub ShowSpaceInfo(drvpath)
    Dim fs, d, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(fs.GetDriveName(fs.GetAbsolutePathName(drvpath)))
    s = "Drive " & d.DriveLetter & ":"
    s = s & vbCrLf
    s = s & "Total Size: " & FormatNumber(d.TotalSize/1024, 0) & " Kbytes"
    s = s & vbCrLf
    s = s & "Available: " & FormatNumber(d.AvailableSpace/1024, 0) & " Kbytes"
    MsgBox s
End Sub

See Also

AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | VolumeName PropertyApplies To: Drive Object


Type Property (FileSystemObject object)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Type Property

Returns information about the type of a file or folder. For example, for files ending in .TXT, "Text Document" is returned.

object.Type

The object is always a File or Folder object.

Remarks

The following code illustrates the use of the Type property to return a folder type. In this example, try providing the path of the Recycle Bin or other unique folder to the procedure.

Sub ShowFileSize(filespec)
    Dim fs, f, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set f = fs.GetFolder(filespec)
    s = UCase(f.Name) & " is a " & f.Type
    MsgBox s, 0, "File Size Info"
End Sub

See Also

Attributes Property | DateCreated Property | DateLastAccessed Property | DateLastModified Property | Drive Property | Files Property | IsRootFolder Property | Name Property | ParentFolder Property | Path Property | ShortName Property | ShortPath Property | Size Property | SubFolders PropertyApplies To: File Object | Folder Object


VolumeName Property

Sets or returns the volume name of the specified drive. Read/write.

object.VolumeName [= newname]

Arguments

object
Required. Always the name of a Drive object.
newname
Optional. If provided, newname is the new name of the specified object.

Remarks

The following code illustrates the use of the VolumeName property:

Sub ShowVolumeInfo(drvpath)
    Dim fs, d, s
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set d = fs.GetDrive(fs.GetDriveName(fs.GetAbsolutePathName(drvpath)))
    s = "Drive " & d.DriveLetter & ": - " & d.VolumeName
    MsgBox s
End Sub

See Also

AvailableSpace Property | DriveLetter Property | DriveType Property | FileSystem Property | FreeSpace Property | IsReady Property | Path Property | RootFolder Property | SerialNumber Property | ShareName Property | TotalSize PropertyApplies To: Drive Object


Statements (Visual Basic for Applications)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Statements (Visual Basic Language Reference)

A-L Statements

M-Z Statements


A-L Statements

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

A-L Statements (Visual Basic Language Reference)

AppActivate Statement

Beep Statement

Call Statement

ChDir Statement

ChDrive Statement

Close Statement

Const Statement

Date Statement

Declare Statement

Deftype Statements

DeleteSetting Statement

Dim Statement

Do...Loop Statement

End Statement

Enum Statement

Erase Statement

Event Statement

Exit Statement

FileCopy Statement

For Each...Next Statement

For...Next Statement

Function Statement

Get Statement

GoSub...Return Statement

GoTo Statement

If...Then...Else Statement

Implements Statement

Input # Statement

Kill Statement

Let Statement

Line Input # Statement

Load Statement

Lock Statement

LSet Statement


AppActivate Statement

Question: Is this a keeper or is it going away?

Activates an application window.

AppActivate title[, wait]

Arguments

title
Required. String expression specifying the title in the title bar of the application window you want to activate. The task ID returned by the Shell function can be used in place of title to activate an application.
wait
Optional. Boolean value specifying whether the calling application has the focus before activating another. If False (default), the specified application is immediately activated, even if the calling application does not have the focus. If True, the calling application waits until it has the focus, then activates the specified application.

Remarks

The AppActivate statement changes the focus to the named application or window, but does not affect whether it is maximized or minimized. Focus moves from the activated application window when the user takes some action to change the focus or close the window. Use the Shell function to start an application and set the window style.

In determining which application to activate, title is compared to the title string of each running application. If there is no exact match, any application whose title string begins with title is activated. If there is more than one instance of the application named by title, one instance is arbitrarily activated.

See Also

Example


AppActivate Statement Example

This example illustrates various uses of the AppActivate statement to activate an application window. The Shell statements assume the applications are in the paths specified.

Dim MyAppID, ReturnValue
AppActivate "Microsoft Word"   ' Activate Microsoft
   ' Word.

' AppActivate can also use the return value of the Shell function.
MyAppID = Shell("C:\WORD\WINWORD.EXE", 1)   ' Run Microsoft Word.
AppActivate MyAppID   ' Activate Microsoft
   ' Word.

' You can also use the return value of the Shell function.
ReturnValue = Shell("c:\EXCEL\EXCEL.EXE",1)   ' Run Microsoft Excel.
AppActivate ReturnValue   ' Activate Microsoft
   ' Excel.


Beep Statement

Question: Is this a dead topic?

Sounds a tone through the computer's speaker.

Beep

Remarks

The frequency and duration of the beep depend on your hardware and system software, and vary among computers.

See Also

Example


Beep Statement Example

This example uses the Beep statement to sound three consecutive tones through the computer's speaker.

Dim I
For I = 1 To 3   ' Loop 3 times.
   Beep   ' Sound a tone.
Next I


Call Statement

Transfers control to a Sub procedure, Function procedure, or dynamic-link library (DLL) procedure.

[Call] name [argumentlist]

Parameters

Call
Optional; keyword.

Call MyProc(0)

name
Required. Name of the procedure to call.
argumentlist
Optional. Comma-delimited list of variables, arrays, or expressions to pass to the procedure. Components of argumentlist may include the keywords ByVal or ByRef to describe how the arguments are treated by the called procedure. However, ByVal and ByRef can be used with Call only when calling a DLL procedure.

Remarks

You are not required to use the Call keyword when calling a procedureIf you use the Call statement to call any intrinsic, .dll or user-defined function, the function's return value is discarded.

To pass a whole array to a procedure, use the array name followed by empty parentheses.

See Also

Example


Call Statement Example

This example illustrates how the Call statement is used to transfer control to a Sub procedure, an intrinsic function, and a dynamic-link library (DLL) procedure.DLLs are not used on the Macintosh.

' Call a Sub procedure.
Call PrintToDebugWindow("Hello World")
' The above statement causes control to be passed to the following
' Sub procedure.
Sub PrintToDebugWindow(AnyString)
   Debug.Print AnyString   ' Print to the Immediate window.
End Sub

' Call an intrinsic function. The return value of the function is
' discarded.
Call Shell(AppName, 1)   ' AppName contains the path of the
      ' executable file.

' Call a Microsoft Windows DLL procedure. The Declare statement must be
' Private in a Class Module, but not in a standard Module.
Private Declare Sub MessageBeep Lib "User" (ByVal N As Integer)
Sub CallMyDll()
   Call MessageBeep(0)   ' Call Windows DLL procedure.
   MessageBeep 0   ' Call again without Call keyword.
End Sub


ChDir Statement

Changes the current directory or folder.

ChDir (path)

The required path argument is a string expression that identifies which directory or folder becomes the new default directory or folder. The path may include the drive. If no drive is specified, ChDir changes the default directory or folder on the current drive.

Remarks

The ChDir statement changes the default directory, but not the default drive. For example, if the default drive is C, the following statement changes the default directory on drive D, but C remains the default drive:

ChDir "D:\TMP"

Making relative directory changes is accomplished this way:

ChDir ".."   ' Moves up one directory.

See Also

Example


ChDir Statement Example

This example uses the ChDir statement to change the current directory or folder.

' Change current directory or folder to "MYDIR".
ChDir "MYDIR"

' Assume "C:" is the current drive. The following statement changes
' the default directory on drive "D:". "C:" remains the current drive.
ChDir "D:\WINDOWS\SYSTEM"


ChDrive Statement

Changes the current drive.

ChDrive (drive)

The required drive argument is a string expression that specifies an existing drive. If you supply a zero-length string (""), the current drive doesn't change. If the drive argument is a multiple-character string, ChDrive uses only the first letter.

See Also

Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

ChDrive Statement Example

This example uses the ChDrive statement to change the current drive.

ChDrive "D"   ' Make "D" the current drive.


Class Statement

Declares the name of a class, as well as a definition of the variables, properties, events, and methods that comprise the class.

[Public|Private|Protected|Friend||Protected Friend][MustInherit|NotInheritable] Class name
[statements]
End Class

The Class statement syntax has these parts:

Part | Description
Public | Optional. Entities declared with the Public modifier have public access. There are no restrictions on the use of public entities
Private | Optional. Entities declared with the Private modifier have private access. A private entity is accessible only within its declaration context, including any nested entities.
Protected | Optional. Entities declared with the Protected modifier have protected access. Protected access can only be specified on members of types (both regular type members and nested types), although there are different access rules for the two. A protected type member contained in a type is accessible to entities contained in a derived type, provided the access takes place through the derived type. A protected type nested in a type is accessible to entities contained in a derived type, provided the access takes place through the base type (since nested types are not inherited). Protected access is not a superset of friend access.
Friend | Optional. Entities declared with the Friend modifier have friend access. An entity with friend access is accessible only within the program that contains the entity declaration.
Protected Friend | Optional. Entities declared with the Protected Friend modifiers have the union of protected and friend accessibility.
MustInherit | Optional. Indicates that the Class contains methods that must be implemented by a deriving class. Instances of must-inherit classes cannot be created.
NotInheritable | Optional. Indicates that the Class is a class from which no further inheritance is allowed.
name | Required. Name of the Class; follows standard variable naming conventions.
statements | Optional. Statements which comprise the variables, properties, events, and methods of the class.

Within a Class block, members are declared as either Public, Private, Protected, Friend, or Protected Friend using the appropriate declaration statements. Anything declared as Private is visible only within the Class block. Anything declared as Public is visible within the Class block, as well as by code outside the Class block. Anything not explicitly declared is Public by default, except for those fields which default to Private. Public variables serve as properties of the class, as do properties explicitly declared usingProperty declarations. Default properties and methods for the class are specified in their declarations using the Default keyword. See the individual declaration statement topics for information on how this keyword is used.

Binding of unqualified names in nested classes will search the members of the class itself, then the members of its containing class, and so on out to the outermost containing class. Private members of outer classes can be referenced but an error will be given for references to instance members of containing classes.

Nested classes cannot inherit from their containing class.

See Also

Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Class Statement Example

This example uses the


Declare Statement

Used at module level to declare references to external procedures in a dynamic-link library (DLL).

Syntax 1

[Public|Private|Protected|Friend|Protected Friend] Declare Sub name Lib "libname" [Alias "aliasname"] [([arglist])]

Syntax 2

[Public|Private|Protected|Friend|Protected Friend] Declare Function name Lib "libname" [Alias "aliasname"] [([arglist])] [As type]

The Declare statement syntax has these parts:

Part | Description
Public | Optional. Entities declared with the Public modifier have public access. There are no restrictions on the use of public entities
Private | Optional. Entities declared with the Private modifier have private access. A private entity is accessible only within its declaration context, including any nested entities.
Protected | Optional. Entities declared with the Protected modifier have protected access. Protected access can only be specified on members of types (both regular type members and nested types), although there are different access rules for the two. A protected type member contained in a type is accessible to entities contained in a derived type, provided the access takes place through the derived type. A protected type nested in a type is accessible to entities contained in a derived type, provided the access takes place through the base type (since nested types are not inherited). Protected access is not a superset of friend access.
Friend | Optional. Entities declared with the Friend modifier have friend access. An entity with friend access is accessible only within the program that contains the entity declaration.
Protected Friend | Optional. Entities declared with the Protected Friend modifiers have the union of protected and friend accessibility.
Sub | Optional (either Sub or Function must appear). Indicates that the procedure doesn't return a value.
Function | Optional (either Sub or Function must appear). Indicates that the procedure returns a value that can be used in an expression.
name | Required. Any valid procedure name. Note that DLL entry points are case sensitive.
Lib | Required. Indicates that a DLL or code resource contains the procedure being declared. The Lib clause is required for all declarations.
libname | Required. Name of the DLL or code resource that contains the declared procedure.
Alias | Optional. Indicates that the procedure being called has another name in the DLL. This is useful when the external procedure name is the same as a keyword. You can also use Alias when a DLL procedure has the same name as a public variable, constant, or any other procedure in the same scope. Alias is also useful if any characters in the DLL procedure name aren't allowed by the DLL naming convention.
aliasname | Optional. Name of the procedure in the DLL or code resource. If the first character is not a number sign (#), aliasname is the name of the procedure's entry point in the DLL. If (#) is the first character, all characters that follow must indicate the ordinal number of the procedure's entry point.
arglist | Optional. List of variables representing arguments that are passed to the procedure when it is called.
type | Optional. Data type of the value returned by a Function procedure; may be Byte, Boolean, Char, Short, Integer, Long, Single, Double, Decimal, Date, String (variable length only), Object or any user-defined type. Arrays of any type cannot be returned, but an Object containing an array can.

The arglist argument has the following syntax and parts:

[Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type]

Part | Description
Optional | Optional. Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. Optional can't be used for any argument if ParamArray is used.
ByVal | Optional. Indicates that the argument is passed by value. ByVal is the default in Visual Basic.
ByRef | Optional. Indicates that the argument is passed by reference.
ParamArray | Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Object elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. The ParamArray keyword can't be used with ByVal, ByRef, or Optional.
varname | Required. Name of the variable representing the argument being passed to the procedure; follows standard variable naming conventions.
( ) | Required for array variables. Indicates that varname is an array.
type | Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Char, Integer, Long, Long8, Single, Double, Decimal, Date, String (variable length only), Object, a user-defined type, or an object type.

Remarks

For Function procedures, the data type of the procedure determines the data type it returns. You can use an As clause following arglist to specify the return type of the function. Within arglist, you can use an As clause to specify the data type of any of the arguments passed to the procedure.

See Also

Example


Declare Statement Example

This example shows how the Declare statement is used at the module level of a standard module to declare a reference to an external procedure in a dynamic-link library (DLL). You can place the Declare statements in class modules if the Declare statements are Private.

' In Microsoft Windows (16-bit):
Declare Sub MessageBeep Lib "User" (ByVal N As Integer)
' Assume SomeBeep is an alias for the procedure name.
Declare Sub MessageBeep Lib "User" Alias "SomeBeep"(ByVal N As Integer)
' Use an ordinal in the Alias clause to call GetWinFlags.
Declare Function GetWinFlags Lib "Kernel" Alias "#132"() As Long

' In 32-bit Microsoft Windows systems, specify the library USER32.DLL,
' rather than USER.DLL. You can use conditional compilation to write
' code that can run on either Win32 or Win16.
#If Win32 Then
   Declare Sub MessageBeep Lib "User32" (ByVal N As Long)
#Else
   Declare Sub MessageBeep Lib "User" (ByVal N As Integer)
#End If


Delegate Statement

Declares the parameter types and return type of a delegate class. Any procedure with matching parameters types and return type may be used to create an instance of this delegate class. The procedure can then later be invoked via the delegate instance.

[Public|Private||Protected|Friend|Protected Friend] Delegate Sub name [([arglist])]
[Public|Private||Protected|Friend|Protected Friend] Delegate Function name [([arglist])] As type

The Delegate statement syntax has these parts:

Part | Description
Public | Optional. Entities declared with the Public modifier have public access. There are no restrictions on the use of public entities.
Private | Optional. Entities declared with the Private modifier have private access. A private entity is accessible only within its declaration context, including any nested entities.
Protected | Optional. Entities declared with the Protected modifier have protected access. Protected access can only be specified on members of types (both regular type members and nested types), although there are different access rules for the two. A protected type member contained in a type is accessible to entities contained in a derived type, provided the access takes place through the derived type. A protected type nested in a type is accessible to entities contained in a derived type, provided the access takes place through the base type (since nested types are not inherited). Protected access is not a superset of friend access.
Friend | Optional. Entities declared with the Friend modifier have friend access. An entity with friend access is accessible only within the program that contains the entity declaration.
Protected Friend | Optional. Entities declared with the Protected Friend modifiers have the union of protected and friend accessibility.
name | Required. Name of the delegate type; follows standard variable naming conventions.
arglist | Optional. List of variables representing arguments that are passed to the procedure when it is called.
type | Optional. Data type of the return value.

The arglist argument has the following syntax and parts:

[ByVal | ByRef] varname[( )] [As type]

Part | Description
ByVal | Optional. Indicates that the argument is passed by value. ByVal is the default in Visual Basic.
ByRef | Optional. Indicates that the argument is passed by reference.
Varname | Required. Name of the variable representing the argument being passed to the procedure; follows standard variable naming conventions.
( ) | Required for array variables. Indicates that varname is an array.
type | Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Char, Short, Integer, Long, , Single, Double, Decimal, Date, String (variable length only), Object, a user-defined type, or an object type.

Remarks

The Delegate statement defines the parameter types and return type of a delegate class. Any procedure with matching parameters types and return type may be used to create an instance of this delegate class. The procedure can then later be invoked via the delegate instance. by calling the delegate’s Invoke method.

Each delegate class defines a constructor that is passed the specification of an object method. The only thing that can be legally specified as a argument to such a delegate constructor is an expression of the form:

AddressOf [<expression>.]<methodname>

The compile-time type of the expression must be the name of a class or an interface that contains a method of the specified name whose signature matches the signature of the delegate class. The methodname can be either a shared method or an instance method. The methodname is not optional even if you create a delegate for the default method of the class.

The method associated with a delegate instance is invoked by calling its built-in Invoke method, illustrated in the following example:

Delegate Sub MySubDelegate(x As Integer)

‘ Class 1

Sub Sub1(x As Integer)

. . .

End Sub

‘ Class 2

Test()

Dim c1 As Class1

Dim msd As MySubDelegate

c1 = New Class1

' Create an instance of the delegate.

Set msd = New MySubDelegate(AddressOf c1.Sub1)

' Call the method.

Call msd.Invoke(10)

See Also

Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Delegate Statement Example

This example uses the


DeleteSetting Statement

Deletes a section or key setting from an application's entry in the Windows registry.

DeleteSetting (appname, section[, key])

Arguments

appname
Required. String expression containing the name of the application or project to which the section or key setting applies.
section
Required. String expression containing the name of the section from which the key setting is being deleted. If only appname and section are provided, the specified section is deleted along with all related key settings.
key
Optional. String expression containing the name of the key setting being deleted.

Remarks

If all arguments are provided, the specified setting is deleted. A run-time error occurs if you attempt to use DeleteSetting on a nonexistent section or key setting.

See Also

Example


DeleteSetting Statement Example

The following example first uses the SaveSetting statement to make entries in the WindowsMacintosh registry (or .ini file on 16-bit Windows platforms) for the MyApp application, and then uses the DeleteSetting statement to remove them. Because no key argument is specified, the whole section is deleted, including the section name and all its keys.

' Place some settings in the registry.
SaveSetting appname := "MyApp", section := "Startup", _
            key := "Top", setting := 75
SaveSetting "MyApp","Startup", "Left", 50
' Remove section and all its settings from registry.
DeleteSetting "MyApp", "Startup"


Dim Statement

Declares variables and allocates storage space.

Dim [WithEvents] varname[([subscripts])] [As [New] type][= initexpr]

The Dim statement syntax has these parts:

Part | Description
WithEvents | Optional. Keyword that specifies that varname is an object variable used to respond to events raised by the instance which is assigned to the variable. You can declare as many individual variables as you like using WithEvents, but you can't create arrays with WithEvents.
varname | Required. Name of the variable; follows standard variable naming conventions.
Initial arraysize | Optional. Specifies the initial size of each dimention of the array.Up to 60 multiple dimensions may be declared.
New | Optional. When New
type | Optional. Data type of the variable; may be Byte, Boolean, Char, Short, Integer, Long, Single, Double, Decimal, Date, String, Object, a user-defined type, or an object type. Use a separate As type clause for each variable you declare.
initexpr | Optional. Any expression that provides the initial value to assign to the variable when it’s declared. A variable cannot be initialized using this syntax if an “As New” clause is used.

Remarks

Variables declared with Dim at the module level are available to all procedures within the module. At the procedure level, variables are available only within the procedure.

Use the Dim statement at module or procedure level to declare the data type of a variable. For example, the following statement declares a variable as an Integer and initializes the value to 10

Dim NumberOfEmployees As Integer = 10

Also use a Dim statement to declare the object type of a variable. The following declares a variable for a new instance of a worksheet.

Dim X As New Worksheet

If the New keyword is not used when declaring an object variable, the variable that refers to the object must be assigned an existing object before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it doesn't refer to an instance of an object.

You can initialize the values of an array by providing a list of initialization values with curly braces. The following example creates an array with four elements and initializes those elements:

Dim A(4) As Integer = {0, 1, 2, 3}

The following example creates a fixed-rank array and initializes 3 elements:

Dim A(3) As Integer = {10, 20, 30}

For multi-dimensional arrays, each separate dimension is included in curly braces. The elements are listed in row-major order. For example:

 ‘ Initialize array elements to their row index * their column index
Dim a(2, 3) As Integer = {{1*3, 1*4, 1*5},{2*3 ,2*4, 2*5}}

If you don't specify a data type or object type, the variable is Object by default.

When no initialization value is specified, a numeric variable is initialized to 0, a string is initialized to a zero-length string (""). Object variables are initialized to Nothing. Each element of a structure variable is initialized as if it were a separate variable.

Note When you use the Dim statement in a procedure, you generally put the Dim statement at the beginning of the procedure.

See Also

Example


Dim Statement Example

This example shows the Dim statement used to declare variables. It also shows the Dim statement used to declare arrays. The default lower bound for array subscripts is 0 and can be overridden at the module level using the Option Base statement.

' AnyValue and MyValue are declared as Variant by default with values
' set to Empty.
Dim AnyValue, MyValue

' Explicitly declare a variable of type Integer.
Dim Number As Integer

' Multiple declarations on a single line. AnotherVar is of type Variant
' because its type is omitted.
Dim AnotherVar, Choice As Boolean, BirthDate As Date

' DayArray is an array of Variants with 51 elements indexed, from
' 0 thru 50, assuming Option Base is set to 0 (default) for
' the current module.
Dim DayArray(50)

' Matrix is a two-dimensional array of integers.
Dim Matrix(3, 4) As Integer

' MyMatrix is a three-dimensional array of doubles with explicit
' bounds.
Dim MyMatrix(1 To 5,  4 To 9,  3 To 5) As Double

' BirthDay is an array of dates with indexes from 1 to 10.
Dim BirthDay(1 To 10) As Date

' MyArray is a dynamic array of variants.
Dim MyArray()


Do...Loop Statement

Repeats a block of statements while a condition is True or until a condition becomes True.

Do [{While | Until} condition]
[statements]
[Exit Do]
[statements]
Loop

Or, you can use this syntax:

Do
[statements]
[Exit Do]
[statements]
Loop [{While | Until} condition]

Parameters

condition
Optional. Numeric expression or string expression that is True or False. If condition is Null, condition is treated as False.
statements
One or more statements that are repeated while, or until, condition is True.

Remarks

Any number of Exit Do statements may be placed anywhere in the Do…Loop as an alternate way to exit a Do…Loop. Exit Do is often used after evaluating some condition, for example, If…Then, in which case the Exit Do statement transfers control to the statement immediately following the Loop.

When used within nested Do…Loop statements, Exit Do transfers control to the loop that is one nested level above the loop where Exit Do occurs.

See Also

Example


Do...Loop Statement Example

This example shows how Do...Loop statements can be used. The inner Do...Loop statement loops 10 times, sets the value of the flag to False, and exits prematurely using the Exit Do statement. The outer loop exits immediately upon checking the value of the flag.

Dim Check, Counter
Check = True: Counter = 0   ' Initialize variables.
Do   ' Outer loop.
   Do While Counter < 20   ' Inner loop.
      Counter = Counter + 1   ' Increment Counter.
      If Counter = 10 Then   ' If condition is True.
         Check = False   ' Set value of flag to False.
         Exit Do   ' Exit inner loop.
      End If
   Loop
Loop Until Check = False   ' Exit outer loop immediately.


End Statement

Ends a procedure or block.

End
End Function
End If
End Property
End Select
End Sub
End Try
End With

Parameters

End
Terminates execution immediately. Never required by itself but may be placed anywhere in a procedure to end code execution, close files opened with the Open statement and to clear variables.
End Function
Required to end a Function statement.
End If
Required to end a block If…Then…Else statement.
End Property
Required to end a Property Let, Property Get, or Property Set procedure.
End Select
Required to end a Select Case statement.
End Sub
Required to end a Sub statement.
End Try
Required to end a Try…Catch…Finally statement.
End With
Required to end a With statement.

Remarks

When executed, the End statement resets all module-level variables and all static local variables in all modules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Destruct event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Destruct events of forms is not executed. Files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.
The End statement provides a way to force your program to halt. For normal termination of a Visual Basic program, you should unload all forms. Your program closes as soon as there are no other programs holding references to objects created and no code executing.

See Also

Example

Class Statement | Enum Statement | Exit Statement | Function Statement | If...Then...Else Statement | Interface Statement | | Select Case Statement | Stop Statement | Sub Statement | Try ... Catch ... Finally Statement | With Statement


End Statement Example

This example uses the End Statement to end code execution if the user enters an invalid password.

Sub Form_Load
   Dim Password, Pword
   PassWord = "Swordfish"
   Pword = InputBox("Type in your password")
   If Pword <> PassWord Then
      MsgBox "Sorry, incorrect password"
      End
   End If
End Sub


Enum Statement

Declares a type for an enumeration.

[Public|Private|Protected|Friend|Protected Friend] Enum name
   membername [= constantexpression]
   membername [= constantexpression]
      . . .
End Enum

The Enum statement has these parts:

Part | Description
Public | Optional. Entities declared with the Public modifier have public access. There are no restrictions on the use of public entities.
Private | Optional. Entities declared with the Private modifier have private access. A private entity is accessible only within its declaration context, including any nested entities.
Protected | Optional. Entities declared with the Protected modifier have protected access. Protected access can only be specified on members of types (both regular type members and nested types), although there are different access rules for the two. A protected type member contained in a type is accessible to entities contained in a derived type, provided the access takes place through the derived type. A protected type nested in a type is accessible to entities contained in a derived type, provided the access takes place through the base type (since nested types are not inherited). Protected access is not a superset of friend access.
Friend | Optional. Entities declared with the Friend modifier have friend access. An entity with friend access is accessible only within the program that contains the entity declaration.
Protected Friend | Optional. Entities declared with the Protected Friend modifiers have the union of protected and friend accessibility.
name | Required. The name of the Enum type. The name must be a valid Visual Basic identifier and is specified as the type when declaring variables or parameters of the Enum type.
membername | Required. A valid Visual Basic identifier specifying the name by which a constituent element of the Enum type will be known.
constantexpression | Optional. Value of the element (evaluates to a Long). If no constantexpression is specified, the value assigned is either zero (if it is the first membername), or 1 greater than the value of the immediately preceding membername.

Remarks

Enumeration variables are variables declared with an Enum type. The elements of the Enum type are initialized to constant values within the Enum statement. The assigned values can't be modified at run time. Values can include both positive and negative numbers. For example:

Enum SecurityLevel
   IllegalEntry = -1
   SecurityLevel1 = 0
   SecurityLevel2 = 1
End Enum

An Enum statement can appear within classes, modules and structures. Once the Enum type is defined, it can be used to declare variables, parameters, or procedures returning its type.

You can't use an Enum type as the target in a With block.

See Also

Example


Enum Statement Example

The following example shows the Enum statement used to define a collection of named constants. In this case, the constants are colors you might choose to design data entry forms for a database.

Public Enum InterfaceColors
   icMistyRose = &HE1E4FF&
   icSlateGray = &H908070&
   icDodgerBlue = &HFF901E&
   icDeepSkyBlue = &HFFBF00&
   icSpringGreen = &H7FFF00&
   icForestGreen = &H228B22&
   icGoldenrod = &H20A5DA&
   icFirebrick = &H2222B2&
End Enum


Error Statement

Simulates the occurrence of an error.

Error errornumber

Argument

errornumber
Required. Can be any valid error number.

Remarks

The Error statement is supported for backward compatibility. In new code, especially when creating objects, use the Err object's Raise method to generate run-time errors.

If errornumber is defined, the Error statement calls the error handler after the properties of the Err object are assigned the following default values.

Property | Value
Number | Value specified as argument to Error statement. Can be any valid error number.
Source | Name of the current Visual Basic project.
Description | String expression corresponding to the return value of the Error function for the specified Number, if this string exists. If the string doesn't exist, Description contains a zero-length string ("").
HelpFile | The fully qualified drive, path, and file name of the appropriate Visual Basic Help file.
HelpContext | The appropriate Visual Basic Help file context ID for the error corresponding to the Number property.
LastDLLError | Zero.

If no error handler exists or if none is enabled, an error message is created and displayed from the Err object properties.

Note Not all Visual Basic host applications can create objects. See your host application's documentation to determine whether it can create classes and objects.

See Also

Example


Error Statement Example

This example uses the Error statement to simulate error number 11.

On Error Resume Next   ' Defer error handling.
Error 11   ' Simulate the "Division by zero" error.


Event Statement

Declares a user-defined event.

[Public] Event procedurename [(arglist)]

The Event statement has these parts:

Part | Description
Public | Optional. Entities declared with the Public modifier have public access. There are no restrictions on the use of public entities.
procedurename | Required. Name of the event; follows standard variable naming conventions.

The arglist argument has the following syntax and parts:

[ByVal | ByRef] varname[( )] [As type]

Part | Description
ByVal | Optional. Indicates that the argument is passed by value. ByVal is the default in Visual Basic.
ByRef | Optional. Indicates that the argument is passed by reference.
varname | Required. Name of the variable representing the argument being passed to the procedure; follows standard variable naming conventions.
type | Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Char, Short, Integer, Long, Single, Double, Decimal, Date, String (variable length only), Object, a user-defined type, or an object type.

Remarks

Once the event has been declared, use the RaiseEvent statement to fire the event. An event can't be declared to return a value. A typical event might be declared and raised as shown in the following fragments:

' Declare an event at module level

Event LogonCompleted (UserName as String)

Sub
   RaiseEvent LogonCompleted("AntoineJan")
End Sub
Note You can declare event arguments just as you do arguments of procedures, with the following exceptions: events cannot have named arguments, or Optional arguments. Events do not have return values.

See Also

Example


Event Statement Example

The following example uses events to count off seconds during a demonstration of the fastest 100 meter race. The code illustrates all of the event-related methods, properties, and statements, including the Event statement.

The class that raises an event is the event source, and the classes that implement the event are the sinks. An event source can have multiple sinks for the events it generates. When the class raises the event, that event is fired on every class that has elected to sink events for that instance of the object.

The example also uses a form (Form1) with a button (Command1), a label (Label1), and two text boxes (Text1 and Text2). When you click the button, the first text box displays "From Now" and the second starts to count seconds. When the full time (9.84 seconds) has elapsed, the first text box displays "Until Now" and the second displays "9.84"

The code for Form1 specifies the initial and terminal states of the form. It also contains the code executed when events are raised.

Option Explicit

Private WithEvents mText As TimerState

Private Sub Command1_Click()
Text1.Text = "From Now"
    Text1.Refresh
    Text2.Text = "0"
    Text2.Refresh
Call mText.TimerTask(9.84)
End Sub

Private Sub Form_Load()
    Command1.Caption = "Click to Start Timer"
    Text1.Text = ""
    Text2.Text = ""
    Label1.Caption = "The fastest 100 meter run took this long:"
    Set mText = New TimerState
    End Sub

Private Sub mText_ChangeText()
    Text1.Text = "Until Now"
    Text2.Text = "9.84"
End Sub

Private Sub mText_UpdateTime(ByVal dblJump As Double)
    Text2.Text = Str(Format(dblJump, "0"))
    DoEvents
End Sub

The remaining code is in a class module named TimerState. The Event statements declare the procedures initiated when events are raised.

Option Explicit
Public Event UpdateTime(ByVal dblJump As Double)
Public Event ChangeText()

Public Sub TimerTask(ByVal Duration As Double)
    Dim dblStart As Double
    Dim dblSecond As Double
    Dim dblSoFar As Double
    dblStart = Timer
    dblSoFar = dblStart

    Do While Timer < dblStart + Duration
        If Timer - dblSoFar >= 1 Then
            dblSoFar = dblSoFar + 1
            RaiseEvent UpdateTime(Timer - dblStart)
        End If
    Loop

    RaiseEvent ChangeText

End Sub


Exit Statement

Exits a block of Do…Loop, For...Next, Try…Catch…Finally, Function, Sub, or Property code.

Exit Do
Exit For
Exit Function
Exit Property
Exit Sub
Exit Try

Forms

Exit Do
Provides a way to exit a Do...Loop statement. It can be used only inside a Do...Loop statement. Exit Do transfers control to the statement following the Loop statement. When used within nested Do...Loop statements, Exit Do transfers control to the loop that is one nested level above the loop where Exit Do occurs.
Exit For
Provides a way to exit a For loop. It can be used only in a For...Next or For Each...Next loop. Exit For transfers control to the statement following the Next statement. When used within nested For loops, Exit For transfers control to the loop that is one nested level above the loop where Exit For occurs.
Exit Function
Immediately exits the Function procedure in which it appears. Execution continues with the statement following the statement that called the Function.
Exit Property
Immediately exits the Property procedure in which it appears. Execution continues with the statement following the statement that called the Property procedure.
Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure.
Exit Try
Immediately exits the Catch block in which it appears within a Try…Catch…Finally structure. Execution continues with the statement following the End Try statement.

Remarks

Do not confuse Exit statements with End statements. Exit does not define the end of a structure.

See Also

Example

Do...Loop Statement | End Statement | For Each...Next Statement | For...Next Statement | Function Statement | | Stop Statement | Sub Statement | Try ... Catch ... Finally Statement | Using For Each...Next Statements | Using For...Next Statements


Exit Statement Example

This example uses the Exit statement to exit a For...Next loop, a Do...Loop, and a Sub procedure.

Sub ExitStatementDemo()
Dim I, MyNum
   Do            ' Set up infinite loop.
      For I = 1 To 1000   ' Loop 1000 times.
         MyNum = Int(Rnd * 1000)   ' Generate random numbers.
         Select Case MyNum   ' Evaluate random number.
            Case 7: Exit For   ' If 7, exit For...Next.
            Case 29: Exit Do   ' If 29, exit Do...Loop.
            Case 54: Exit Sub   ' If 54, exit Sub procedure.
         End Select
      Next I
   Loop
End Sub


For Each...Next Statement

Repeats a group of statements for each element in an array or collection.

For Each element In group
[statements]
[Exit For]
[statements]
Next [element]

Parameters

element
Required. Variable used to iterate through the elements of the collection or array. For collections or arrays, element can be either a generic object variable or any specific object variable.
group
Required. Name of an object collection or array (except an array of user-defined types).
statements
Optional. One or more statements that are executed on each item in group.

Remarks

The For...Each block is entered if there is at least one element in group. Once the loop has been entered, all the statements in the loop are executed for the first element in group. If there are more elements in group, the statements in the loop continue to execute for each element. When there are no more elements in group, the loop is exited and execution continues with the statement following the Next statement.

Any number of Exit For statements may be placed anywhere in the loop as an alternative way to exit. Exit For is often used after evaluating some condition, for example If…Then, and transfers control to the statement immediately following Next.

You can nest For...Each...Next loops by placing one For...Each...Next loop within another. However, each loop element must be unique.

Note If you omit element in a Next statement, execution continues as if element is included. If a Next statement is encountered before its corresponding For statement, an error occurs.

See Also

Example

Do...Loop Statement | Exit Statement | For...Next Statement | Making Faster For...Next Loops | Using Do...Loop Statements | Using For Each...Next Statements | Using For...Next Statements | While…End While Statement


For Each...Next Statement Example

This example uses the For Each...Next statement to search the Text property of all elements in a collection for the existence of the string "Hello". In the example, MyObject is a text-related object and is an element of the collection MyCollection. Both are generic names used for illustration purposes only.

Dim Found, MyObject, MyCollection
Found = False   ' Initialize variable.
For Each MyObject In MyCollection   ' Iterate through each element.
   If MyObject.Text = "Hello" Then   ' If Text equals "Hello".
      Found = True   ' Set Found to True.
      Exit For   ' Exit loop.
   End If
Next


For...Next Statement

Repeats a group of statements a specified number of times.

For counter = start To end [Step step]
[statements]
[Exit For]
[statements]
Next [counter]

Parameters

counter
Required. Numeric variable used as a loop counter. The variable can't be a Boolean or an array element.
start
Required. Initial value of counter.
end
Required. Final value of counter.
step
Optional. Amount counter is changed each time through the loop. If not specified, step defaults to one.
statements
Optional. One or more statements between For and Next that are executed the specified number of times.

Remarks

The step argument can be either positive or negative. The value of the step argument determines loop processing as follows:

Value | Loop executes if
Positive or 0 | counter <= end
Negative | counter >= end

After all statements in the loop have executed, step is added to counter. At this point, either the statements in the loop execute again (based on the same test that caused the loop to execute initially), or the loop is exited and execution continues with the statement following the Next statement.

Tip Changing the value of counter while inside a loop can make it more difficult to read and debug your code.

Any number of Exit For statements may be placed anywhere in the loop as an alternate way to exit. Exit For is often used after evaluating of some condition, for example If...Then, and transfers control to the statement immediately following Next.

You can nest For...Next loops by placing one For...Next loop within another. Give each loop a unique variable name as its counter. The following construction is correct:

For I = 1 To 10
   For J = 1 To 10
      For K = 1 To 10
         ...
      Next K
   Next J
Next I
Note If you omit counter in a Next statement, execution continues as if counter is included. If a Next statement is encountered before its corresponding For statement, an error occurs.

See Also

Example

Do...Loop Statement | Exit Statement | For Each...Next Statement | Making Faster For...Next Loops | Using Do...Loop Statements | Using For Each...Next Statements | Using For...Next Statements | While…End While Statement


Function Statement

Declares the name, arguments, and code that form the body of a Function procedure.

[Overloads]
[Overrides|CantOverride|MustOverride] [Protected]
[Public|Private|Protected|Friend|Protected Friend] Function name [(arglist)] [As type]
   [statements]

End Function

The Function statement syntax has these parts:

Part | Description
Overloads | Optional. Indicates that the Function procedure is overloaded. That is, more than one declaration exists, each with a distinct argument declaration that allows the compiler to distinguish which version to use.
Overrides | Optional. Indicates that the Function procedure overrides an identically named function found in a base class. The data type of the arguments and the return value must exactly match those in the base class procedure.
CantOverride | Optional. Indicates that the Function procedure cannot be overridden in a derived class.
MustOverride | Optional. Indicates that a derived class must override the Function procedure in order to be creatable.
Protected | Optional. Indicates that the Function procedure can be accessed by derived classes but not by other clients of the class.
Public | Optional. Entities declared with the Public modifier have public access. There are no restrictions on the use of public entities.
Private | Optional. Entities declared with the Private modifier have private access. A private entity is accessible only within its declaration context, including any nested entities.
Protected | Optional. Entities declared with the Protected modifier have protected access. Protected access can only be specified on members of types (both regular type members and nested types), although there are different access rules for the two. A protected type member contained in a type is accessible to entities contained in a derived type, provided the access takes place through the derived type. A protected type nested in a type is accessible to entities contained in a derived type, provided the access takes place through the base type (since nested types are not inherited). Protected access is not a superset of friend access.
Friend | Optional. Entities declared with the Friend modifier have friend access. An entity with friend access is accessible only within the program that contains the entity declaration.
Protected Friend | Optional. Entities declared with the Protected Friend modifiers have the union of protected and friend accessibility.
name | Required. Name of the Function; follows standard variable naming conventions.
arglist | Optional. List of variables representing arguments that are passed to the Function procedure when it is called. Multiple variables are separated by commas.
type | Optional. Data type of the value returned by the Function procedure; may be Byte, Boolean, Char, Short, Integer, Long, Single, Double, Decimal, Date, String, or (except fixed length), Object, or any user-defined type. Arrays of any type cannot be returned, but an Object containing an array can be returned.
statements | Optional. Any group of statements to be executed within the Function procedure.
expression | Optional. Return value of the Function.

The arglist argument has the following syntax and parts:

[Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue]

Part | Description
Optional | Optional. Indicates that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. Optional can't be used for any argument if ParamArray is used.
ByVal | Optional. Indicates that the argument is passed by value. ByVal is the default in Visual Basic.
ByRef | Optional. Indicates that the argument is passed by reference.
ParamArray | Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Object elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. It may not be used with ByVal, ByRef, or Optional.
varname | Required. Name of the variable representing the argument; follows standard variable naming conventions.
type | Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, Char, Short, Integer, Long, Single, Double, Decimal Date, String (variable length only), Object, or a specific object type. If the parameter is not Optional, a user-defined type may also be specified.
defaultvalue | Optional. Any constant or constant expression. Valid for Optional parameters only. If the type is an Object, an explicit default value can only be Nothing.

Remarks

Function procedures are public by default.

All executable code must be in procedures. You can't define a Function procedure inside another Function, Sub, or Property procedure.

The Exit Function statement causes an immediate exit from a Function procedure. Program execution continues with the statement following the statement that called the Function procedure. Any number of Exit Function statements can appear anywhere in a Function procedure.

Like a Sub procedure, a Function procedure is a separate procedure that can take arguments, perform a series of statements. However, unlike a Sub procedure, you can use a Function procedure on the right side of an expression in the same way you use any intrinsic function, such as Sqr, Cos, or Chr, when you want to use the value returned by the function.

You call a Function procedure using the function name, followed by the argument list in parentheses, in an expression. A function can also be called using the Call statement in which case the return value of the function will be ignored.

To return a value from a function, either assign the value to the function name or use the Return statement. Any number of such assignments can appear anywhere within the procedure. If no value is assigned to name, the procedure returns a default value: a numeric function returns 0 and a string function returns a zero-length string ("")Empty. A function that returns an object reference returns Nothing if no object reference is assigned to name (using Set) within the Function.

The following examples show how to assign a return value to a function named BinarySearch. In this case, False is assigned to the name to indicate that some value was not found.

Function BinarySearch(. . .) As Boolean
. . .
   ' Value not found. Return a value of False.
   If lower > upper Then
      BinarySearch = False
      Exit Function
   End If
. . .
End Function

In this second example, the value is not found and the Return statement gives us a False value.

Function BinarySearch(. . .) As Boolean
. . .
   ' Value not found. Return a value of False.
   If lower > upper Then
      Return False
      Exit Function
   End If
. . .
End Function

Variables used in Function procedures fall into two categories: those that are explicitly declared within the procedure and those that are not. Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure. Variables that are used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.

Caution Visual Basic may rearrange arithmetic expressions to increase internal efficiency. Avoid using a Function procedure in an arithmetic expression when the function changes the value of variables in the same expression.

See Also

Example


Function Statement Example

This example uses the Function statement to declare the name, arguments, and code that form the body of a Function procedure. The last example uses hard-typed, initialized Optional arguments.

' The following user-defined function returns the square root of the
' argument passed to it.
Function CalculateSquareRoot(NumberArg As Double) As Double
   If NumberArg < 0 Then   ' Evaluate argument.
      Exit Function   ' Exit to calling procedure.
   Else
      CalculateSquareRoot = Sqr(NumberArg)   ' Return square root.
   End If
End Function

Using the ParamArray keyword enables a function to accept a variable number of arguments. In the following definition, FirstArg is passed by value.

Function CalcSum(ByVal FirstArg As Integer, ParamArray OtherArgs())
Dim ReturnValue
' If the function is invoked as follows:
ReturnValue = CalcSum(4, 3 ,2 ,1)
' Local variables are assigned the following values: FirstArg = 4,
' OtherArgs(1) = 3, OtherArgs(2) = 2, and so on, assuming default
' lower bound for arrays = 1.

Optional arguments can have default values and types other than Variant.

' If a function's arguments are defined as follows:
Function MyFunc(MyStr As String, Optional MyArg1 As _ Integer = 5, Optional MyArg2 = "Dolly")
Dim RetVal
' The function can be invoked as follows:
RetVal = MyFunc("Hello", 2, "World")   ' All 3 arguments supplied.
RetVal = MyFunc("Test", , 5)   ' Second argument omitted.
' Arguments one and three using named-arguments.
RetVal = MyFunc(MyStr:="Hello ", MyArg1:=7)


If...Then...Else Statement

Conditionally executes a group of statements, depending on the value of an expression.

If condition Then [statements] [Else elsestatements]

Or, you can use the block form syntax:

If condition Then
[statements]
[ElseIf condition-n Then
[elseifstatements] ...
[Else
[elsestatements]]
End If

Parameters

condition
Required. One or more of the following two types of expressions:

A Boolean expressiondefBoolean@veendf98.chm that evaluates to True or False. If condition is Null, condition is treated as False.

An expression of the form TypeOf objectname Is objecttype. The objectname is any object reference and objecttype is any valid object type. The expression is True if objectname is of the object type specified by objecttype; otherwise it is False.

statements
Optional in block form; required in single-line form that has no Else clause. One or more statements separated by colons; executed if condition is True.
condition-n
Optional. Same as condition.
elseifstatements
Optional. One or more statements executed if associated condition-n is True.
elsestatements
Optional. One or more statements executed if no previous condition or condition-n expression is True.

Remarks

You can use the single-line form (first syntax) for short, simple tests. However, the block form (second syntax) provides more structure and flexibility than the single-line form and is usually easier to read, maintain, and debug.

Note With the single-line form, it is possible to have multiple statements executed as the result of an If...Then decision. All statements must be on the same line and separated by colons, as in the following statement:
If A > 10 Then A = A + 1 : B = B + A : C = C + B

A block form If statement must be the first statement on a line. The Else, ElseIf, and End If parts of the statement can have only a line number or line label preceding them. The block If must end with an End If statement.

To determine whether or not a statement is a block If, examine what follows the Then keyword. If anything other than a comment appears after Then on the same line, the statement is treated as a single-line If statement.

The Else and ElseIf clauses are both optional. You can have as many ElseIf clauses as you want in a block If, but none can appear after an Else clause. Block If statements can be nested; that is, contained within one another.

When executing a block If (second syntax), condition is tested. If condition is True, the statements following Then are executed. If condition is False, each ElseIf condition (if any) is evaluated in turn. When a True condition is found, the statements immediately following the associated Then are executed. If none of the ElseIf conditions are True (or if there are no ElseIf clauses), the statements following Else are executed. After executing the statements following Then or Else, execution continues with the statement following End If.

Tip Select Case may be more useful when evaluating a single expression that has several possible actions. However, the TypeOf objectname Is objecttype clause can't be used with the Select Case statement.
Note TypeOf cannot be used with hard data types such as Long, Integer, and so forth other than Object.

See Also

Example


If...Then...Else Statement Example

This example shows both the block and single-line forms of the If...Then...Else statement. It also illustrates the use of If TypeOf...Then...Else.

Dim Number, Digits, MyString
Number = 53   ' Initialize variable.
If Number < 10 Then
   Digits = 1
ElseIf Number < 100 Then
' Condition evaluates to True so the next statement is executed.
   Digits = 2
Else
   Digits = 3
End If

' Assign a value using the single-line form of syntax.
If Digits = 1 Then MyString = "One" Else MyString = "More than one"

Use If TypeOf construct to determine whether the Control passed into a procedure is a text box.

Sub ControlProcessor(MyControl As Control)
   If TypeOf MyControl Is CommandButton Then
      Debug.Print "You passed in a " & TypeName(MyControl)
   ElseIf TypeOf MyControl Is CheckBox Then
      Debug.Print "You passed in a " & TypeName(MyControl)
   ElseIf TypeOf MyControl Is TextBox Then
      Debug.Print "You passed in a " & TypeName(MyControl)
   End If
End Sub


Imports Statement

Imports namespace names from referenced projects and assemblies. Also imports namespace names defined within the same project as the module in which the statement appears.

Imports [aliasname = ] namespace

The Imports statement syntax has these parts:

Part | Description
aliasname | Optional. The name by which namespace may also be known or referred to. When the Imports statement does not include aliasname, the elements defined within the specified namespace can be accessed within the module without qualification. When aliasname is specified, it must be used as a qualifier for the names contained in the namespace.
namespace | Required. The name of the namespace being imported.

Remarks

Each module can contain any number of Imports statements. Imports statements must occur in a module before any references to identifiers within the module.

Since an alias name is specified within a module, it shadows any names that are defined outside of the module including imported names. It is not permitted to define a member at module level with the same name as an import alias.

See Also

Example


Inherits Statement

Used at the top of a class definition to specify the name of the inherited class.

Inherits classname

The Inherits statement syntax has these parts:

Part | Description
classname | Required. The name of a class being inherited by the class in which the Inherits statement is used.

Remarks

If used, the Inherits statement must be the first non-blank, non-comment line in a class definition.

See Also

Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Inherits Statement Example

This example uses the


Interface Statement

Declares the name of an interface, as well as the properties and methods that comprise the interface.

[Public|Private|Protected|Friend|Protected Friend]Interface name
[Inherits interfacename[, interfacename]]
 [Property proname]
[Event proname]
[Function proname]
[Sub proname]
End Interface

The Interface statement syntax has these parts:

Part | Description
Public | Optional. Entities declared with the Public modifier have public access. There are no restrictions on the use of public entities.
Private | Optional. Entities declared with the Private modifier have private access. A private entity is accessible only within its declaration context, including any nested entities.
Protected | Optional. Entities declared with the Protected modifier have protected access. Protected access can only be specified on members of types (both regular type members and nested types), although there are different access rules for the two. A protected type member contained in a type is accessible to entities contained in a derived type, provided the access takes place through the derived type. A protected type nested in a type is accessible to entities contained in a derived type, provided the access takes place through the base type (since nested types are not inherited). Protected access is not a superset of friend access.
Friend | Optional. Entities declared with the Friend modifier have friend access. An entity with friend access is accessible only within the program that contains the entity declaration.
Protected Friend | Optional. Entities declared with the Protected Friend modifiers have the union of protected and friend accessibility.
name | Required. Name of the Interface; follows standard variable naming conventions.
Inherits | Optional. Specifies that the interface being declared inherits properties and methods from the interface specified by interfacename.
interfacename | Required if optional Inherits statement is present. Indicates the name of one or more interfaces being inherited.
Default | Optional. Indicates that the procedure with which the Default keyword is associated is the default property or method for the interface.
Property | Optional. Indicates a Property procedure that is a member of the interface.
Function | Optional. Indicates a Function procedure that is a member of the interface.
Sub | Optional. Indicates a Sub procedure that is a member of the interface.
proname | Required if optional Property, Function, or Sub statements exist. Indicates the name of the property or procedure.

Remarks

The methods and properties of an interface are implemented in a class. When methods are implemented, the return data type and the argument data types must exactly match those of the method described in the Interface block. The method name, however, need not be the same as that described in the Interface block. Methods being implemented in a class cannot be designated as Shared, nor can they be Private, except in a non-inheritable class.

The Interface statement can appear in the declaration section of any module. Interfaces are implicitly Public by default but can be explicitly declared Public, Friend, Protected, Protected Friend or Private.

An interface can have, at most, one default method or property. This implies that an interface can either inherit only one interface containing a default method or property, or its definition block can contain one method or property that is marked as default.

An interface cannot inherit from another interface whose access level is more restrictive than its own. For example, a public interface cannot inherit a friend interface.

See Also

Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Interface Statement Example

This example uses the


Kill Statement

Deletes files from a disk.

Kill (pathname)

The required pathname argument is a string expression that specifies one or more file names to be deleted. The pathname may include the directory or folder, and the drive.

Remarks

Kill supports the use of multiple-character (*) and single-character (?) wildcards to specify multiple files.

See Also

Example


Kill Statement Example

This example uses the Kill statement to delete a file from a disk.

' Assume TESTFILE is a file containing some data.
Kill "TestFile"   ' Delete file.

' Delete all *.TXT files in current directory.
Kill "*.TXT"


Lock, Unlock Statements

Controls access by other processes to all or part of a file opened using the Open statement.

Lock (channel, start, finish)
. . .
Unlock (channel, start, finish)

Arguments

channel
Required. Any valid file number.
start
Optional. Number of the first record or byte to lock or unlock.
finish
Optional. Number of the last record or byte to lock or unlock.

Remarks

The Lock and Unlock statements are used in environments where several processes might need access to the same file.

Lock and Unlock statements are always used in pairs. The arguments to Lock and Unlock must match exactly.

If the start and finish are not supplied, the lock will be for the entire file. If the start is specified but not the finish, the single record will be locked/unlocked.

If the file has been opened for sequential input or output, Lock and Unlock affect the entire file, regardless of the range specified by start and end.See Also

Example

Open Statement


Lock, Unlock Statements Example

This example illustrates the use of the Lock and Unlock statements. While a record is being modified, access by other processes to the record is denied. This example assumes that TESTFILE is a file containing five records of the user-defined type Record.

Type Record   ' Define user-defined type.
   ID As Integer
   Name As String * 20
End Type

Dim MyRecord As Record, RecordNumber   ' Declare variables.
' Open sample file for random access.
Open "TESTFILE" For Random Shared As #1 Len = Len(MyRecord)
RecordNumber = 4   ' Define record number.
Lock #1, RecordNumber   ' Lock record.
Get #1, RecordNumber, MyRecord   ' Read record.
MyRecord.ID = 234   ' Modify record.
MyRecord.Name = "John Smith"
Put #1, RecordNumber, MyRecord   ' Write modified record.
Unlock #1, RecordNumber   ' Unlock current record.
Close #1   ' Close file.


M-Z Statements

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

M-Z Statements (Visual Basic Language Reference)

Mid Statement

MkDir Statement

Name Statement

On...GoSub Statement

On...GoTo Statement

Open Statement

Option Base Statement

Option Compare Statement

Option Explicit Statement

Option Private Statement

Print # Statement

Private Statement

Property Get Statement

Property Let Statement

Property Set Statement

Public Statement

Put Statement

RaiseEvent Statement

Randomize Statement

ReDim Statement

Rem Statement

Reset Statement

RmDir Statement

RSet Statement

SaveSetting Statement

Seek Statement

Select Case Statement

SendKeys Statement

Set Statement

SetAttr Statement

Static Statement

Stop Statement

Sub Statement

Time Statement

Type Statement

Unload Statement

Unlock Statement

While...Wend Statement

Width # Statement

With Statement

Write # Statement


Mid Statement

Replaces a specified number of characters in aString variable with characters from another string.

Mid(stringvar, start[, length]) = string

Arguments

stringvar
Required. Name of string variable to modify.
start
Required; Long. Character position in stringvar where the replacement of text begins.
length
Optional; Long. Number of characters to replace. If omitted, all of string is used.
string
Required. String expression that replaces part of stringvar.

Remarks

The number of characters replaced is always less than or equal to the number of characters in stringvar.

See Also

Example

Mid Function


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

MidB Statement

[Topic intentionally blank - content coming in later builds]


Mid Statement Example

This example uses the Mid statement to replace a specified number of characters in a string variable with characters from another string.

Dim MyString
MyString = "The dog jumps"   ' Initialize string.
Mid(MyString, 5, 3) = "fox"   ' MyString = "The fox jumps".
Mid(MyString, 5) = "cow"   ' MyString = "The cow jumps".
Mid(MyString, 5) = "cow jumped over"   ' MyString = "The cow jumpe".
Mid(MyString, 5, 3) = "duck"   ' MyString = "The duc jumpe".


Namespace Statement

Declares the name of a namespace.

Namespace name
[component types]
End Namespace

Namespaces are used as an organizational system - a way of presenting program components that are exposed to other programs and applications.

Parameters

name
Required. A unique name that identifies the namespace.
component types
Required. Elements that make up the namespace. These include (but are not limited to) Enums, Structures, Interfaces, Classes, Delegates.

Remarks

Namespaces are always Public; therefore the declaration of a namespace cannot includce an access modifiers. However, the components within the namespace may have Public, Friend or Private access. If it is not stated, the default access type is Friend.Note Private members of a namespace are accessible only within the namespace declaration they were declared in.

See Also


On Error Statement

Enables an error-handling routine and specifies the location of the routine within a procedure; can also be used to disable an error-handling routine.

On Error GoTo line
On Error Resume Next
On Error GoTo 0

Arguments

On Error GoTo line
Enables the error-handling routine that starts at the line specified in the required line argument. The line argument is any line label or line number. If a run-time error occurs, control branches to line, making the error handler active. The specified line must be in the same procedure as the On Error statement, or a compile-time error will occur.
On Error Resume Next
Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred, at which point execution continues. Use this form rather than On Error GoTo when accessing objects.
On Error GoTo 0
Disables any enabled error handler in the current procedure.

Remarks

If you don't use an On Error statement, any run-time error that occurs is fatal; that is, an error message is displayed and execution stops.

An "enabled" error handler is one that is turned on by an On Error statement; an "active" error handler is an enabled handler that is in the process of handling an error. If an error occurs while an error handler is active (between the occurrence of the error and a Resume, Exit Sub, Exit Function, or Exit Property statement), the current procedure's error handler can't handle the error. Control returns to the calling procedure. If the calling procedure has an enabled error handler, it is activated to handle the error. If the calling procedure's error handler is also active, control passes back through previous calling procedures until an enabled, but inactive, error handler is found. If no such error handler is found, the error is fatal at the point at which it actually occurred. Each time the error handler passes control back to a calling procedure, that procedure becomes the current procedure. Once an error is handled by an error handler in any procedure, execution resumes in the current procedure at the point designated by the Resume statement.

Note An error-handling routine is not a Sub procedure or a Function procedure. It is a section of code marked by a line label or a line number.

Error-handling routines rely on the value in the Number property of the Err object to determine the cause of the error. The routine should test or save relevant property values in the Err object before any other error can occur or before a procedure that might cause an error is called. The property values in the Err object reflect only the most recent error. The error message associated with Err.Number is contained in Err.Description.

On Error Resume Next causes execution to continue with the statement immediately following the statement that caused the run-time error, or with the statement immediately following the most recent call out of the procedure containing the On Error Resume Next statement. This statement allows execution to continue despite a run-time error. You can place the error-handling routine where the error would occur, rather than transferring control to another location within the procedure. An On Error Resume Next statement becomes inactive when another procedure is called, so you should execute an On Error Resume Next statement in each called routine if you want inline error handling within that routine.

Note The On Error Resume Next construct may be preferable to On Error GoTo when handling errors generated during access to other objects. Checking Err after each interaction with an object removes ambiguity about which object was accessed by the code. You can be sure which object placed the error code in Err.Number, as well as which object originally generated the error (the object specified in Err.Source).

On Error GoTo 0 disables error handling in the current procedure. It doesn't specify line 0 as the start of the error-handling code, even if the procedure contains a line numbered 0. Without an On Error GoTo 0 statement, an error handler is automatically disabled when a procedure is exited.

To prevent error-handling code from running when no error has occurred, place an Exit Sub, Exit Function, or Exit Property statement immediately before the error-handling routine, as in the following fragment:

Sub InitializeMatrix(Var1, Var2, Var3, Var4)
   On Error GoTo ErrorHandler
   . . .
   Exit Sub
ErrorHandler:
   . . .
   Resume Next
End Sub

Here, the error-handling code follows the Exit Sub statement and precedes the End Sub statement to separate it from the procedure flow. You can place error-handling code anywhere in a procedure.

Untrapped errors in objects are returned to the controlling application when the object is running as an executable file. Within the development environment, untrapped errors are returned to the controlling application only if the proper options are set. See your host application's documentation for a description of which options should be set during debugging, how to set them, and whether the host can create classes.

If you create an object that accesses other objects, you should try to handle any unhandled errors they pass back. If you cannot, map the error codes in Err.Number to one of your own errors, and then pass them back to the caller of your object. You should specify your error by adding your error code to the ObjectError constant. For example, if your error code is 1052, assign it as follows:

Err.Number = ObjectError + 1052
Important System errors during calls to Windows dynamic-link libraries (DLL) do not raise exceptions and cannot be trapped with Visual Basic error trapping. When calling DLL functions, you should check each return value for success or failure (according to the API specifications), and in the event of a failure, check the value in the Err object's LastDLLError property.

See Also

Example

Debugging Your Code and Handling Errors | End Statement | Err Object | Exit Statement | Generating and Handling Errors in ActiveX Components | Handling Run-Time Errors in ActiveX Components | LastDLLError Property | Resume Statement | Trappable Errors


On Error Statement Example

This example first uses the On Error GoTo statement to specify the location of an error-handling routine within a procedure. In the example, an attempt to delete an open file generates error number 55. The error is handled in the error-handling routine, and control is then returned to the statement that caused the error. The On Error GoTo 0 statement turns off error trapping. Then the On Error Resume Next statement is used to defer error trapping so that the context for the error generated by the next statement can be known for certain. Note that Err.Clear is used to clear the Err object's properties after the error is handled.

Sub OnErrorStatementDemo()
   On Error GoTo ErrorHandler   ' Enable error-handling routine.
   Open "TESTFILE" For Output As #1   ' Open file for output.
   Kill "TESTFILE"   ' Attempt to delete open
            ' file.
   On Error Goto 0   ' Turn off error trapping.
   On Error Resume Next   ' Defer error trapping.
   ObjectRef = GetObject("MyWord.Basic")   ' Try to start nonexistent
            ' object, then test for
'Check for likely Automation errors.
   If Err.Number = 440 Or Err.Number = 432 Then
      ' Tell user what happened. Then clear the Err object.
      Msg = "There was an error attempting to open the Automation object!"
      MsgBox Msg, , "Deferred Error Test"
      Err.Clear   ' Clear Err object fields
   End If
Exit Sub      ' Exit to avoid handler.
ErrorHandler:   ' Error-handling routine.
   Select Case Err.Number   ' Evaluate error number.
      Case 55   ' "File already open" error.
         Close #1   ' Close open file.
      Case Else
         ' Handle other situations here...
   End Select
   Resume   ' Resume execution at same line
            ' that caused the error.
End Sub


Open Statement

Question: If Close is now a Function, is Open still a Statement?

Enables input/output (I/O) to a file.

Open (channel, filename, mode, access, share, recordlength)

Arguments

channel
Required. Any valid file number Use the FreeFile function to obtain the next available file number.
filename
Required. String expression that specifies a file name — may include directory or folder, and drive.
mode
Optional Enum specifying the file mode: Append, Binary, Input, Output, or Random. If unspecified, the file is opened for Random access.
access
Optional. Keyword specifying the operations permitted on the open file: Read, Write, or ReadWrite. Defaults to ReadWrite.
share
Optional. Enum specifying the operations restricted on the open file by other processes: Shared, Lock Read, Lock Write, and Lock Read Write. Defaults to Shared.
recordlength
Optional. Number less than or equal to 32,767 (bytes). For files opened for random access, this value is the record length. For sequential files, this value is the number of characters buffered.

Remarks

You must open a file before any I/O operation can be performed on it. Open allocates a buffer for I/O to the file and determines the mode of access to use with the buffer.

If the file specified by pathname doesn't exist, it is created when a file is opened for Append, Binary, Output, or Random modes.

The channel to open can be found using the Freefile() function.

See Also

Example


Open Statement Example

This example illustrates various uses of the Open statement to enable input and output to a file.

The following code opens the file TESTFILE in sequential-input mode.

Open "TESTFILE" For Input As #1
' Close before reopening in another mode.
Close #1

This example opens the file in Binary mode for writing operations only.

Open "TESTFILE" For Binary Access Write As #1
' Close before reopening in another mode.
Close #1

The following example opens the file in Random mode. The file contains records of the user-defined type Record.

Type Record   ' Define user-defined type.
   ID As Integer
   Name As String * 20
End Type

Dim MyRecord As Record   ' Declare variable.
Open "TESTFILE" For Random As #1 Len = Len(MyRecord)
' Close before reopening in another mode.
Close #1

This code example opens the file for sequential output; any process can read or write to file.

Open "TESTFILE" For Output Shared As #1
' Close before reopening in another mode.
Close #1

This code example opens the file in Binary mode for reading; other processes can't read file.

Open "TESTFILE" For Binary Access Read Lock Read As #1


Option Compare Statement

Used at module level to declare the default comparison method to use when string data is compared.

Option Compare {Binary | Text }

Remarks

If used, the Option Compare statement must appear in a module before any procedures.

The Option Compare statement specifies the string comparison method (Binary or Text) for a class, module or structure. If an Option Compare statement is not included, the default text comparison method is Binary.

Option Compare Binary results in string comparisons based on a sort order derived from the internal binary representations of the characters. In Microsoft Windows, sort order is determined by the code page. A typical binary sort order is shown in the following example:

A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø

Option Compare Text results in string comparisons based on a case-insensitive text sort order determined by your system's locale. When the same characters are sorted using Option Compare Text, the following text sort order is produced:

(A=a) < ( À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø)

See Also

Example


Option Compare Statement Example

This example uses the Option Compare statement to set the default string comparison method. The Option Compare statement is used at the module level only.

' Set the string comparison method to Binary.
Option compare Binary    ' That is, "AAA" is less than "aaa".
' Set the string comparison method to Text.
Option compare Text   ' That is, "AAA" is equal to "aaa".


Option Explicit Statement

Used at module level to force explicit declaration of all variables in that module.

Syntax

Option Explicit

Remarks

If used, the Option Explicit statement must appear in a module before any procedures.

When Option Explicit appears in a module, you must explicitly declare all variables using the Dim, Private, Public, or ReDim statements. If you attempt to use an undeclared variable name, an error occurs at compile time.

If you don't use the Option Explicit statement, all undeclared variables are of Object type.

Note Use Option Explicit to avoid incorrectly typing the name of an existing variable or to avoid confusion in code where the scope of the variable is not clear.

See Also

Example

Const Statement | Dim Statement | Function Statement | Option Base Statement | Option Compare Statement | Option Private Statement | Private Statement | Public Statement | ReDim Statement | Sub Statement


Option Explicit Statement Example

This example uses the Option Explicit statement to force explicit declaration of all variables. Attempting to use an undeclared variable causes an error at compile time. The Option Explicit statement is used at the module level only.

Option explicit   ' Force explicit variable declaration.
Dim MyVar   ' Declare variable.
MyInt = 10   ' Undeclared variable generates error.

MyVar = 10' Declared variable does not generate error.


Option Strict Statement

Restricts implicit data type conversions to only widening conversions. This explicitly disallows any data type conversions in which data loss would occur and any conversion between numeric types and strings.

Option Strict

Remarks

Visual Basic generally allows implicit conversions of any data type to any other data type. Data loss can occur when the value of one data type is converted to a data type with less precision or smaller capacity, however, a runtime error message will occur if data will be lost in such a conversion. Option Strict ensures compile-time notification of these types of conversions so they may be avoided.

In addition to the conditions described above, Option Strict generates an error for:

  • Any undeclared variable since it is implied that Option Strict also means Option Explicit.
  • late-binding

The following is a list of widening conversions:

Type | Widens to
Boolean | Object
Byte | Short, Integer, Long, Decimal, Single, Double, Object
Char | Integer, Long, Decimal, Single, Double, Object
Short | Integer, Long, Decimal, Single, Double, Object
Integer | Long, Decimal, Single, Double, Object
Long | , Decimal, Double, Object
Single | Double, Object
Double | Object
Date | , Object
String | Object
Null | Object
Nothing | Object
Empty | Object
Fixed-length String | String, Object
class | Object; any of the classes that it inherits from; any of the interfaces that it implements (for COM2 defined classes this will only include the interfaces listed in the class’s definition within it’s type library).
Interface | Object; any of the interfaces that it inherits from.
Structure | Object
Array | Object

See Also

Example


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Option Strict Statement Example

This example uses the


Print # Statement

Writes display-formatted data to a sequential file.

Print (channel, output)
PrintLine (channel, output)

Arguments

channel
Required. Any valid file number.
output
Optional. One or more comma-delimited Expressions to write to a file.

Settings

The output argument settings are:

[{Spc(n) | Tab[(n)]}] [expression] [charpos]

Setting | Description
Spc(n) | Used to insert space characters in the output, where n is the number of space characters to insert.
Tab(n) | Used to position the insertion point to an absolute column number, where n is the column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone.
expression | Numeric expressions or string expressions to print.
charpos | Specifies the insertion point for the next character. Use a semicolon to position the insertion point immediately after the last character displayed. Use Tab(n) to position the insertion point to an absolute column number. Use Tab with no argument to position the insertion point at the beginning of the next print zone. If charpos is omitted, the next character is printed on the next line.

Question: Are we keeping these settings?

Remarks

Print will not include a linefeed at the end of a line; PrintLine, however, will.

Data written with Print # is usually read from a file with LineInput # or Input.

If you omit output for PrintLine, a blank line is printed to the file; for Print, nothing is output. Multiple expressions separated with a comma will be aligned on Tab boundries.

For Boolean data, either True or False is printed. The True and False keywords are not translated, regardless of the locale.

Date data is written to the file using the standard short date format recognized by your system. When either the date or the time component is missing or zero, only the part provided is written to the file.

Nothing is written to the file if output data is Empty. However, if outputlist data is dbNull, Null is written to the file.

For Error data, the output appears as Error errorcode. The Error keyword is not translated regardless of the locale.

All data written to the file using Print # is internationally aware; that is, the data is properly formatted using the appropriate decimal separator. If the user wishes to output data for use by multiple locales, then Write # should be used.

See Also

Example


Print # Statement Example

This example uses the Print # statement to write data to a file.

Open "TESTFILE" For Output As #1   ' Open file for output.
Print #1, "This is a test"   ' Print text to file.
Print #1,   ' Print blank line to file.
Print #1, "Zone 1"; Tab ; "Zone 2"   ' Print in two print zones.
Print #1, "Hello" ; " " ; "World"   ' Separate strings with space.
Print #1, Spc(5) ; "5 leading spaces "   ' Print five leading spaces.
Print #1, Tab(10) ; "Hello"   ' Print word at column 10.

' Assign Boolean, Date, Null and Error values.
Dim MyBool, MyDate, MyNull, MyError
MyBool = False : MyDate = #February 12, 1969# : MyNull = Null
MyError = CVErr(32767)
' True, False, Null, and Error are translated using locale settings of
' your system. Date literals are written using standard short date
' format.
Print #1, MyBool ; " is a Boolean value"
Print #1, MyDate ; " is a date"
Print #1, MyNull ; " is a null value"
Print #1, MyError ; " is an error value"
Close #1   ' Close file.


Private Statement

Used at module level to declare private variables and allocate storage space.

Private [WithEvents] varname[([subscripts])] [As [New] type][= initexpr]
[,[WithEvents] varname[([subscripts])] [As [New] type][= initexpr]]
. . .

The Private statement syntax has these parts:

Part | Description
WithEvents | Optional. Keyword that specifies that varname is an object variable used to respond to events triggered by an ActiveX object. You can declare as many individual variables as you like using WithEvents, but you can't create arrays with WithEvents. You can't use New with WithEvents.
varname | Required. Name of the variable; follows standard variable naming conventions.
subscripts | Optional. Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax for arrays where both the lower and upper bounds are specified:
 | [lower To] upper [,[lower To] upper] . . .
 | For fixed-rank arrays. the lower bound value of the array is not specified and the “*” character is used in place of the upper bound value.
New | Optional. Keyword that enables implicit creation of an object. If you use New when declaring the object variable, a new instance of the object is created on first reference to it, so you don't have to use the Set statement to assign the object reference. The New keyword can't be used to declare variables of any intrinsic data type, can't be used to declare instances of dependent objects, and can’t be used with WithEvents.
type | Optional. Data type of the variable; may be Byte, Boolean, Char, Short, Integer, Long, Single, Double, Decimal, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, a user-defined type, or an object type. Use a separate As type clause for each variable being defined.
initexpr | Optional. Any expression that provides the initial value to assign to the variable when it’s declared. A variable cannot be initialized using this syntax if an “As New” clause is used.

Remarks

Private variables are available only to the class, module or structure in which they are declared.

Use the Private statement to declare the data type of a variable. For example, the following statement declares a variable as an Integer and initializes the value to 10.

Private NumberOfEmployees As Integer = 10

You can also use a Private statement to declare the object type of a variable. The following statement declares a variable for a new instance of a worksheet.

Private X As New Worksheet

If the New keyword isn't used when declaring an object variable, the variable that refers to the object must be assigned an existing object using the Set statement before it can be used. Until it's assigned an object, the declared object variable has the special value Nothing, which indicates that it doesn't refer to any particular instance of an object.

If you don't specify a data type or object type, , the variable is Object by default.You can initialize the values of a fixed-size or fixed-rank array by surrounding the initialization values with braces ({}). The following example creates a fixed-size array with four elements:

Dim A(3) as Integer = {0, 1, 2, 3}

The following example creates a fixed-rank array and initializes 3 elements:

Dim A(*) As Integer = {10, 20, 30}

You can also use the Private statement with empty parentheses to declare a dynamic array. You then initialize the values of the array in the same way as for fixed-size arrays. The following example initializes values for a dynamic array:

Dim A() as Integer = {0, 1, 2, 3}

If you want to initialize a dynamic array with any lower bound other than the default (either 0 or 1), you must use the ReDim statement. For example:

ReDim A(2 To 5) as Integer = {0, 1, 2, 3}

For multi-dimensional arrays, each separate dimension is included in curly braces. The elements are listed in row-major order. For example:

 ‘ Initialize array elements to their row index * their column index
Dim a(1 to 2, 3 to 5) As Integer = {{1*3, 1*4, 1*5},{2*3 ,2*4, 2*5}}

After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, Protected or Dim statement, an error occurs.

If you don't specify a data type or object type, the variable is Object by default.

When no initialization value is specified, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string (""), and a fixed-length string is filled with zeros. Object variables are initialized toEmpty. Each element of a user-defined type variable is initialized as if it were a separate variable.

Note When you use the Private statement in a procedure, you generally put the Private statement at the beginning of the procedure.

See Also

Example


Private Statement Example

This example shows the Private statement being used at the module level to declare variables as private; that is, they are available only to the module in which they are declared.

Private Number As Integer   ' Private Integer variable.
Private NameArray(1 To 5) As String   ' Private array variable.
' Multiple declarations, two Variants and one Integer, all Private.
Private MyVar, YourVar, ThisVar As Integer


Property Statement

Used to assign values, arrays or other objects to variables.

[Default|ReadOnly|WriteOnly] Property varname ([parameter list]) [As typename]
   Get
      [block]
   End Get
   Set
      [block]
   End Set
End Property

Parameters

varname
Required. A unique name that identifies the Property.

parameter list

Required. This identifies the signature of the property. Unless specified, the list default is ByVal.

typename
Optional. If no data type is specified, the default type is Object.

Remarks

The declaration of the property determines what the user can do with that property:

  • If the ReadOnly modifier is used, the property is known as a "Read-only property" and must only have a Get…End Get block. Therefore, the user is only able to retrieve the value of the property. An error will be raised if the user attempts to assign a value to that property.
  • If the WriteOnly modifier is used, the property is known as a "Write-only property" and must only have a Set…End Set block. This allows the user to store a value to the property. An error will be raised if the user attempts to refer to the property, except in the assignment of a value to that property.
  • If the Default modifier is used, or if no modifier is used, the property must have both a Set…End Set and a Get…End Get block. The property is said to be a read-write property.

See Also


Public Statement

Used at module level to declare public variables and allocate storage space.

Public [WithEvents] varname[([subscripts])] [As [New] type][= initexpr]
[,[WithEvents] varname[([subscripts])] [As [New] type][= initexpr]]
. . .

The Public statement syntax has these parts:

Part | Description
WithEvents | Optional. Keyword specifying that varname is an object variable used to respond to events triggered by an ActiveX object. You can declare as many individual variables as you like using WithEvents, but you can't create arrays with WithEvents. You can't use New with WithEvents.
varname | Required. Name of the variable; follows standard variable naming conventions.
subscripts | Optional. Dimensions of an array variable; up to 60 multiple dimensions may be declared. The subscripts argument uses the following syntax for arrays where both the lower and upper bounds are specified: [lower To] upper [,[lower To] upper] . . . For fixed-rank arrays. the lower bound value of the array is not specified and the “*” character is used in place of the upper bound value.
New | Optional. Keyword that enables implicit creation of an object. If you use New when declaring the object variable, a new instance of the object is created on first reference to it, so you don't have to use the Set statement to assign the object reference. The New keyword can't be used to declare variables of any intrinsic data type, can't be used to declare instances of dependent objects, and can't be used with WithEvents.
type | Optional. Data type of the variable; may be Byte, Boolean, Char, Short, Integer, Long, Single, Double, Decimal, Date, String, (for variable-length strings), String * length (for fixed-length strings), Object, a user-defined type, or an object type. Use a separate As type clause for each variable being defined.
initexpr | Optional. Any expression that provides the initial value to assign to the variable when it’s declared. A variable cannot be initialized using this syntax if an “As New” clause is used.

Remarks

Variables declared using the Public statement are available to all procedures in all classes, modules and structures in all applications.

Use the Public statement to declare the data type of a variable. For example, the following statement declares a variable as an Integer and initializes the value to 10.

Public NumberOfEmployees As Integer = 10

Also use a Public statement to declare the object type of a variable. The following statement declares a variable for a new instance of a worksheet.

Public X As New Worksheet

If the New keyword is not used when declaring an object variable, the variable that refers to the object must be assigned an existing object using the Set statement before it can be used. Until it is assigned an object, the declared object variable has the special value Nothing, which indicates that it doesn't refer to any particular instance of an object.

You can initialize the values of a fixed-size or fixed-rank array by surrounding the initialization values with curly braces. The following example creates a fixed-size array with four elements:

Dim A(3) as Integer = {0, 1, 2, 3}

The following example creates a fixed-rank array and initializes 3 elements:

Dim A(*) As Integer = {10, 20, 30}

You can also use the Public statement with empty parentheses to declare a dynamic array. You then initialize the values of the array in the same way as for fixed-size arrays. The following example initializes values for a dynamic array:

Dim A() as Integer = {0, 1, 2, 3}

If you want to initialize a dynamic array with any lower bound other than the default (either 0 or 1), you must use the ReDim statement. For example:

ReDim A(2 To 5) as Integer = {0, 1, 2, 3}

For multi-dimensional arrays, each separate dimension is included in curly braces. The elements are listed in row-major order. For example:

 ‘ Initialize array elements to their row index * their column index
Dim a(1 to 2, 3 to 5) As Integer = {{1*3, 1*4, 1*5},{2*3 ,2*4, 2*5}}

After declaring a dynamic array, use the ReDim statement within a procedure to define the number of dimensions and elements in the array. If you try to redeclare a dimension for an array variable whose size was explicitly specified in a Private, Public, Protected or Dim statement, an error occurs.

If you don't specify a data type or object type the variable is Object by default.

When no initialization value is specified, a numeric variable is initialized to 0, a variable-length string is initialized to a zero-length string (""), and a fixed-length string is filled with zeros. Object variables are initialized toEmpty. Each element of a user-defined type variable is initialized as if it were a separate variable.

See Also

Example


Public Statement Example

This example uses the Public statement at the module level (General section) of a standard module to explicitly declare variables as public; that is, they are available to all procedures in all modules in all applications unless Option Private Module is in effect.

Public Number As Integer   ' Public Integer variable.
Public NameArray(1 To 5) As String   ' Public array variable.
' Multiple declarations, two Variants and one Integer, all Public.
Public MyVar, YourVar, ThisVar As Integer


Put Statement

Writes data from a variable to a disk file.

Put (channel, value, recordnumber)

Arguments

channel
Required. Any valid file number.
value
Required. Valid variable name containing data written to disk.
recordnumber
Optional. Record number (Random mode files) or byte number (Binary mode files) at which writing begins.

Remarks

Data written with Put is usually read from a file with Get.

The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. If you omit recordnumber, the next record or byte after the last Get or Put statement or pointed to by the last Seek function is written.

For files opened in Random mode, the following rules apply:

  • If the length of the data being written is less than the length specified in the Len clause of the Open statement, Put writes subsequent records on record-length boundaries. The space between the end of one record and the beginning of the next record is padded with the existing contents of the file buffer. Because the amount of padding data can't be determined with any certainty, it is generally a good idea to have the record length match the length of the data being written. If the length of the data being written is greater than the length specified in the Len clause of the Open statement, an exception will be thrown.
  • If the variable being written is a variable-length string, Put writes a 2-byte descriptor containing the string length, and then writes the data that goes into the variable. Therefore, the record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual length of the string. If the variable being read into is a fixed-length string, then only the string length will be written.
  • If the variable being written is an Object of a numeric type, Put writes 2 bytes identifying the VarType of the Variant and then writes the variable. For example, when writing a Variant of VarType 3, Put writes 6 bytes: 2 bytes identifying the Variant as VarType 3 (Integer) and 4 bytes containing the data. The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual number of bytes required to store the variable.
  • If the variable being written is an Object of VarType 8 (String), Put writes 2 bytes identifying the VarType, 2 bytes indicating the length of the string, and then writes the string data. The record length specified by the Len clause in the Open statement must be at least 4 bytes greater than the actual length of the string.
  • Question: Even though Variant is taboo, the specs are still using it…what’s going to happen with these sections?
  • If the variable being written is a dynamic array, Put writes a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * NumberOfDimensions. The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to write the array data and the array descriptor. For example, the following array declaration requires 118 bytes when the array is written to disk.
    Dim MyArray(1 To 5,1 To 10) As Integer
  • The 118 bytes are distributed as follows: 18 bytes for the descriptor (2 + 8 * 2), and 100 bytes for the data (5 * 10 * 2).
  • If the variable being written is a fixed-size array, Put writes only the data. No descriptor is written to disk.
  • If the variable being written is any other type of variable (not a variable-length string or an Object), Put writes only the variable data. The record length specified by the Len clause in the Open statement must be greater than or equal to the length of the data being written.
  • Put writes elements of user-defined types as if each were written individually, except there is no padding between elements.

For files opened in Binary mode, all of the Random rules apply, except:

  • The Len clause in the Open statement has no effect. Put writes all variables to disk contiguously; that is, with no padding between records.
  • For any array other than an array in a user-defined type, Put writes only the data. No descriptor is written.
  • Put writes variable-length strings that are not elements of user-defined types without the 2-byte length descriptor. The number of bytes written equals the number of characters in the string. For example, the following statements write 10 bytes to file number 1:
    VarString$ = String$(10," ")
Put #1,,VarString$

See Also

Example


Put Statement Example

This example uses the Put statement to write data to a file. Five records of the user-defined type Record are written to the file.

Type Record   ' Define user-defined type.
   ID As Integer
   Name As String * 20
End Type

Dim MyRecord As Record, RecordNumber   ' Declare variables.
' Open file for random access.
Open "TESTFILE" For Random As #1 Len = Len(MyRecord)
For RecordNumber = 1 To 5   ' Loop 5 times.
   MyRecord.ID = RecordNumber   ' Define ID.
   MyRecord.Name = "My Name" & RecordNumber   ' Create a string.
   Put #1, RecordNumber, MyRecord   ' Write record to file.
Next RecordNumber
Close #1   ' Close file.


Randomize Statement

Initializes the random-number generator.

Randomize [number]

The optional number argument is a Objector any valid numeric expression.

Remarks

Randomize uses number to initialize the Rnd function's random-number generator, giving it a new seed value. If you omit number, the value returned by the system timer is used as the new seed value.

If Randomize is not used, the Rnd function (with no arguments) uses the same number as a seed the first time it is called, and thereafter uses the last generated number as a seed value.

Note To repeat sequences of random numbers, call Rnd with a negative argument immediately before using Randomize with a numeric argument. Using Randomize with the same value for number does not repeat the previous sequence.

See Also

Example


Randomize Statement Example

This example uses the Randomize statement to initialize the random-number generator. Because the number argument has been omitted, Randomize uses the return value from the Timer function as the new seed value.

Dim MyValue
Randomize   ' Initialize random-number generator.

MyValue = Int((6 * Rnd) + 1)   ' Generate random value between 1 and 6.


ReDim Statement

Used at procedure level to reallocate storage space for dynamic array variables.

ReDim [Preserve] varname(size) [As type][= initexpr]
[,varname(subscripts) [As type][= initexpr]]
 . . .

The ReDim statement syntax has these parts:

Part | Description
Preserve | Optional. Keyword used to preserve the data in an existing array when you change the size of the last dimension.
varname | Required. Name of the variable; follows standard variable naming conventions.
size | RequiredSize of each dimension:
type | Optional. Data type of the variable; may be Byte, Boolean, Char, Short, Integer, Long, Single, Double, Decimal, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, a user-defined type, or an object type. Use a separate As type clause for each variable being defined. For an Object containing an array, type describes the type of each element of the array, but doesn't change the Object to some other type.

Remarks

The ReDim statement is used to size or resize an array that has already been formally declared.

You can use the ReDim statement repeatedly to change the number of elements; however, you cannot change the number of dimensions in the array. However, you can't declare an array of one data type and later use ReDim to change the array to another data type, unless the array is contained in anObject.

If you use the Preserve keyword, you can resize only the last array dimension and you can't change the number of dimensions at all. For example, if your array has only one dimension, you can resize that dimension because it is the last and only dimension. However, if your array has two or more dimensions, you can change the size of only the last dimension and still preserve the contents of the array. The following example shows how you can increase the size of the last dimension of a dynamic array without erasing any existing data contained in the array.

ReDim X(10, 10, 10)
. . .
ReDim Preserve X(10, 10, 15)

Similarly, when you use Preserve, you can change the size of the array only by changing the upper bound; changing the lower bound causes an error.

If you make an array smaller than it was, data in the eliminated elements will be lost. If you pass an array to a procedure by reference, you can't redimension the array within the procedure.

See Also

Example


ReDim Statement Example

This example uses the ReDim statement to allocate and reallocate storage space for dynamic-array variables. It assumes the Option Base is 1.

Dim MyArray() As Integer   ' Declare dynamic array.
Redim MyArray(5)   ' Allocate 5 elements.
For I = 1 To 5   ' Loop 5 times.
   MyArray(I) = I   ' Initialize array.
Next I

The next statement resizes the array and erases the elements.

Redim MyArray(10)   ' Resize to 10 elements.
For I = 1 To 10   ' Loop 10 times.
   MyArray(I) = I   ' Initialize array.
Next I

The following statement resizes the array but does not erase elements.

Redim Preserve MyArray(15)   ' Resize to 15 elements.


Rem Statement

Used to include explanatory remarks in a program.

Rem comment

You can also use the following syntax:

' comment

The optional comment argument is the text of any comment you want to include. A space is required between the Rem keyword and comment.

Remarks

If you use line numbers or line labels, you can branch from a GoTo statement to a line containing a Rem statement. Execution continues with the first executable statement following the Rem statement. If the Rem keyword follows other statements on a line, it must be separated from the statements by a colon (:).

You can use an apostrophe (') instead of the Rem keyword. When you use an apostrophe, the colon is not required after other statements.

See Also

Example


Rem Statement Example

This example illustrates the various forms of the Rem statement, which is used to include explanatory remarks in a program.

Dim MyStr1, MyStr2
MyStr1 = "Hello": Rem Comment after a statement separated by a colon.
MyStr2 = "Goodbye"    ' This is also a comment; no colon is needed.


Reset Statement

Closes all disk files opened using the Open statement.

Reset ()

Remarks

The Reset statement closes all active files opened by the Open statement and. has the same function as Close() without any parameters.

See Also

Example


Reset Statement Example

This example uses the Reset statement to close all open files and write the contents of all file buffers to disk. Note the use of the Variant variable FileNumber as both a string and a number.

Dim FileNumber
For FileNumber = 1 To 5   ' Loop 5 times.
   ' Open file for output. FileNumber is concatenated into the string
   ' TEST for the file name, but is a number following a #.
   Open "TEST" & FileNumber For Output As #FileNumber
   Write #FileNumber, "Hello World"   ' Write data to file.
Next FileNumber
Reset   ' Close files and write contents
      ' to disk.


Resume Statement

Resumes execution after an error-handling routine is finished.

Resume [0]
Resume Next
Resume line

Arguments

Resume
Required. If the error occurred in the same procedure as the error handler, execution resumes with the statement that caused the error. If the error occurred in a called procedure, execution resumes at the statement that last called out of the procedure containing the error-handling routine.
Resume Next
Required. If the error occurred in the same procedure as the error handler, execution resumes with the statement immediately following the statement that caused the error. If the error occurred in a called procedure, execution resumes with the statement immediately following the statement that last called out of the procedure containing the error-handling routine (or On Error Resume Next statement).
Resume line
Required. Execution resumes at the line specified in the required line argument. The line argument is a line label or line number, and must be in the same procedure as the error handler.

Remarks

If you use a Resume statement anywhere except in an error-handling routine, an error will error occur.

The Resume statement cannot be used in any procedure that contains a Try…Catch…Finally statement.

See Also

Try...Catch...Finally Statement | Error Function | Error Statement | OnError Statement


Resume Statement Example

This example uses the Resume statement to end error handling in a procedure, and then resume execution with the statement that caused the error. Error number 55 is generated to illustrate using the Resume statement.

Sub ResumeStatementDemo()
   On Error GoTo ErrorHandler   ' Enable error-handling routine.
   Open "TESTFILE" For Output As #1   ' Open file for output.
   Kill "TESTFILE"   ' Attempt to delete open file.
   Exit Sub   ' Exit Sub to avoid error handler.
ErrorHandler:   ' Error-handling routine.
   Select Case Err.Number   ' Evaluate error number.
      Case 55   ' "File already open" error.
         Close #1   ' Close open file.
      Case Else
         ' Handle other situations here....
   End Select
   Resume   ' Resume execution at same line
   ' that caused the error.
End Sub


SaveSetting Statement

Saves or creates an application entry in the Windows registry.

SaveSetting (appname, section, key, setting)

Arguments

appname
Required. String expression containing the name of the application or project to which the setting applies.
section
Required. String expression containing the name of the section in which the key setting is being saved.
key
Required. String expression containing the name of the key setting being saved.
setting
Required. Expression containing the value to which key is being set.

Remarks

If the key setting can't be saved for any reason, an error occurs.

See Also

Example


SaveSetting Statement Example

The following example first uses the SaveSetting statement to make entries in the WindowsMacintosh registry (or .ini file on 16-bit Windows platforms) for the MyApp application, and then uses the DeleteSetting statement to remove them.

' Place some settings in the registry.
SaveSetting appname := "MyApp", section := "Startup", _
            key := "Top", setting := 75
SaveSetting "MyApp","Startup", "Left", 50
' Remove section and all its settings from registry.
DeleteSetting "MyApp", "Startup"


Seek Statement

Sets the position for the next read/write operation within a file opened using the Open statement.

Seek [#]filenumber, position

Arguments

filenumber
Required. Any valid file number.
position
Required. Number in the range 1 – 2,147,483,647, inclusive, that indicates where the next read/write operation should occur.

Remarks

Record numbers specified in Get and Put statements override file positioning performed by Seek.

Performing a file-write operation after a Seek operation beyond the end of a file extends the file. If you attempt a Seek operation to a negative or zero position, an error occurs.

See Also

Example


Seek Statement Example

This example uses the Seek statement to set the position for the next read or write within a file. This example assumes TESTFILE is a file containing records of the user-defined type Record.

Type Record   ' Define user-defined type.
   ID As Integer
   Name As String * 20
End Type

For files opened in Random mode, Seek sets the next record.

Dim MyRecord As Record, MaxSize, RecordNumber   ' Declare variables.
' Open file in random-file mode.
Open "TESTFILE" For Random As #1 Len = Len(MyRecord)
MaxSize = LOF(1) \ Len(MyRecord)   ' Get number of records in file.
' The loop reads all records starting from the last.
For RecordNumber = MaxSize To 1 Step - 1
   Seek #1, RecordNumber   ' Set position.
   Get #1, , MyRecord   ' Read record.
Next RecordNumber
Close #1   ' Close file.

For files opened in modes other than Random mode, Seek sets the byte position at which the next operation takes place. Assume TESTFILE is a file containing a few lines of text.

Dim MaxSize, NextChar, MyChar
Open "TESTFILE" For Input As #1   ' Open file for input.
MaxSize = LOF(1)   ' Get size of file in bytes.
' The loop reads all characters starting from the last.
For NextChar = MaxSize To 1 Step -1
   Seek #1, NextChar   ' Set position.
   MyChar = Input(1, #1)   ' Read character.
Next NextChar
Close #1   ' Close file.


Select Case Statement

Executes one of several groups of statements, depending on the value of an expression.

Select Case testexpression
[Case expressionlist-n
   [statements-n]] ...
[Case Else
   [elsestatements]]
End Select

Parameters

testexpression
Required. Any numeric expression or string expression.
expressionlist-n
Required if a Case appears. Delimited list of one or more of the following forms: expression, expression To expression, Is comparisonoperator expression. The To keyword specifies a range of values. If you use the To keyword, the smaller value must appear before To. Use the Is keyword with comparison operators (except Is and Like) to specify a range of values. If not supplied, the Is keyword is automatically inserted.
statements-n
Optional. One or more statements executed if testexpression matches any part of expressionlist-n.
elsestatements
Optional. One or more statements executed if testexpression doesn't match any of the Case clause.

Remarks

If testexpression matches any Case expressionlist expression, the statements following that Case clause are executed up to the next Case clause, or, for the last clause, up to End Select. Control then passes to the statement following End Select. If testexpression matches an expressionlist expression in more than one Case clause, only the statements following the first match are executed.

The Case Else clause is used to indicate the elsestatements to be executed if no match is found between the testexpression and an expressionlist in any of the other Case selections. Although not required, it is a good idea to have a Case Else statement in your Select Case block to handle unforeseen testexpression values. If no Case expressionlist matches testexpression and there is no Case Else statement, execution continues at the statement following End Select.

You can use multiple expressions or ranges in each Case clause. For example, the following line is valid:

Case 1 To 4, 7 To 9, 11, 13, Is > MaxNumber
Note The Is comparison operator is not the same as the Is keyword used in the Select Case statement.

You also can specify ranges and multiple expressions for character strings. In the following example, Case matches strings that are exactly equal to everything, strings that fall between nuts and soup in alphabetic order, and the current value of TestItem:

Case "everything", "nuts" To "soup", TestItem

Select Case statements can be nested. Each nested Select Case statement must have a matching End Select statement.

See Also

Example


Select Case Statement Example

This example uses the Select Case statement to evaluate the value of a variable. The second Case clause contains the value of the variable being evaluated, and therefore only the statement associated with it is executed.

Dim Number
Number = 8   ' Initialize variable.
Select Case Number   ' Evaluate Number.
Case 1 To 5   ' Number between 1 and 5, inclusive.
   Debug.Print "Between 1 and 5"
' The following is the only Case clause that evaluates to True.
Case 6, 7, 8   ' Number between 6 and 8.
   Debug.Print "Between 6 and 8"
Case 9 To 10   ' Number is 9 or 10.
Debug.Print "Greater than 8"
Case Else   ' Other values.
   Debug.Print "Not between 1 and 10"
End Select


SetAttr Statement

Sets attribute information for a file.

SetAttr (String, fileattributes)

Arguments

pathname
Required. String expression that specifies a file name — may include directory or folder, and drive.
attributes
Required. Constant or numeric expression, whose sum specifies file attributes.

Settings

The attributes argument settings are:

Constant | Value | Description
Normal | 0 | Normal (default).
ReadOnly | 1 | Read-only.
Hidden | 2 | Hidden.
System | 4 | System file.
Archive | 32 | File has changed since last backup.

Note These constants are specified by Visual Basic for Applications. The names can be used anywhere in your code in place of the actual values.

Remarks

A run-time error occurs if you try to set the attributes of an open file.

See Also

Example


SetAttr Statement Example

This example uses the SetAttr statement to set attributes for a file.

SetAttr "TESTFILE", vbHidden   ' Set hidden attribute.
SetAttr "TESTFILE", vbHidden + vbReadOnly   ' Set hidden and read-only
   ' attributes.


Stop Statement

Suspends execution.

Stop

Remarks

You can place Stop statements anywhere in procedures to suspend execution. Using the Stop statement is similar to setting a breakpoint in the code.

The Stop statement suspends execution, but unlike End, it doesn't close any files or clear variables, unless it is in a compiled executable (.exe) file.

See Also

Example


Stop Statement Example

This example uses the Stop statement to suspend execution for each iteration through the For...Next loop.

Dim I
For I = 1 To 10   ' Start For...Next loop.
   Debug.Print I   ' Print I to the Immediate window.
   Stop   ' Stop during each iteration.
Next I


Sub Statement

Declares the name, arguments, and code that form the body of a Sub procedure.

[Private|Public|Protected|Friend|Protected Friend] Sub name [(arglist)]
   [statements]
   [Exit Sub]
   [statements]
End Sub

The Sub statement syntax has these parts:

Part | Description
Overloads | Optional. Indicates that the Sub procedure is overloaded. That is, more than one declaration exists, each with a distinct argument declaration that allows the compiler to distinguish which version to use.
Overrides | Optional. Indicates that the Sub procedure overrides an identically named function found in a base class. The data type of the arguments and the return value must exactly match those in the base class procedure.
CantOverride | Optional. Indicates that the Sub procedure cannot be overridden in a derived class.
MustOverride | Optional. Indicates that a derived class must override the Sub procedure in order to be creatable.
Public | Optional. Entities declared with the Public modifier have public access. There are no restrictions on the use of public entities.
Private | Optional. Entities declared with the Private modifier have private access. A private entity is accessible only within its declaration context, including any nested entities.
Protected | Optional. Entities declared with the Protected modifier have protected access. Protected access can only be specified on members of types (both regular type members and nested types), although there are different access rules for the two. A protected type member contained in a type is accessible to entities contained in a derived type, provided the access takes place through the derived type. A protected type nested in a type is accessible to entities contained in a derived type, provided the access takes place through the base type (since nested types are not inherited). Protected access is not a superset of friend access.
Friend | Optional. Entities declared with the Friend modifier have friend access. An entity with friend access is accessible only within the program that contains the entity declaration.
Protected Friend | Optional. Entities declared with the Protected Friend modifiers have the union of protected and friend accessibility.
name | Required. Name of the Sub; follows standard variable naming conventions.
arglist | Optional. List of variables representing arguments that are passed to the Sub procedure when it is called. Multiple variables are separated by commas.
statements | Optional. Any group of statements to be executed within the Sub procedure.

The arglist argument has the following syntax and parts:

[Optional] [ByVal | ByRef] [ParamArray] varname[( )] [As type] [= defaultvalue]

Part | Description
Optional | Optional. Keyword indicating that an argument is not required. If used, all subsequent arguments in arglist must also be optional and declared using the Optional keyword. Optional can't be used for any argument if ParamArray is used.
ByVal | Optional. Indicates that the argument is passed by value. ByVal is the default in Visual Basic.
ByRef | Optional. Indicates that the argument is passed by reference.
ParamArray | Optional. Used only as the last argument in arglist to indicate that the final argument is an Optional array of Object elements. The ParamArray keyword allows you to provide an arbitrary number of arguments. ParamArray can't be used with ByVal, ByRef, or Optional.
varname | Required. Name of the variable representing the argument; follows standard variable naming conventions.
type | Optional. Data type of the argument passed to the procedure; may be Byte, Boolean, , Short, Integer, Long, Single, Double, Decimal, Date, String (variable-length only), Object, or a specific object type. A user-defined type can also be specified for arguments in procedures declared a Private or Friend.
defaultvalue | Optional. Any constant or constant expression. Valid for Optional parameters only. If the type is an Object, an explicit default value can only be Nothing.

Remarks

Sub procedures are public by default

All executable code must be in procedures. You can't define a Sub procedure inside another Sub, Function, or Property procedure.

The Exit Sub keywords cause an immediate exit from a Sub procedure. Program execution continues with the statement following the statement that called the Sub procedure. Any number of Exit Sub statements can appear anywhere in a Sub procedure.

Like a Function procedure, a Sub procedure is a separate procedure that can take arguments and perform a series of statements. However, unlike a Function procedure, which returns a value, a Sub procedure can't be used in an expression.

You call a Sub procedure using the procedure name followed by the argument list. See the Call statement for specific information on how to call Sub procedures.

Variables used in Sub procedures fall into two categories: those that are explicitly declared within the procedure and those that are not. Variables that are explicitly declared in a procedure (using Dim or the equivalent) are always local to the procedure. Variables that are used but not explicitly declared in a procedure are also local unless they are explicitly declared at some higher level outside the procedure.

Caution A procedure can use a variable that is not explicitly declared in the procedure, but a naming conflict can occur if anything you defined at the module level has the same name. If your procedure refers to an undeclared variable that has the same name as another procedure, constant or variable, it is assumed that your procedure is referring to that module-level name. To avoid this kind of conflict, explicitly declare variables. You can use an Option Strict statement to force explicit declaration of variables.
Note You can't use GoTo, or Return to enter or exit a Sub procedure.

See Also

Example


Sub Statement Example

This example uses the Sub statement to define the name, arguments, and code that form the body of a Sub procedure.

' Sub procedure definition.
' Sub procedure with two arguments.
Sub SubComputeArea(Length, TheWidth)
   Dim Area As Double   ' Declare local variable.
   If Length = 0 Or TheWidth = 0 Then
   ' If either argument = 0.
      Exit Sub   ' Exit Sub immediately.
   End If
   Area = Length * TheWidth   ' Calculate area of rectangle.
   Debug.Print Area   ' Print Area to Debug window.
End Sub


SyncLock Statement

Allows statements to be synchronized on a single expression.

SyncLock expression
...[Block]
End SyncLock

Parameters

expression
Required. A unique collection of operators and values that yield a single result.

Remarks

The SyncLock statement ensures that multiple threads do not execute the same statements at the same time. When the thread reaches the SyncLock block, it evaluates the expression and maintains this exclusivity until it has an lock on the object that is returned by the expression. This prevents an expression from changing values during the running of several threads, which can give unexpected results from your code.

Note The type of the expression in a SyncLock statement must be a reference type, such as a class, a module, an interface, an array or a delegate.

See Also


TimeOfDay Statement

Sets the system time.

TimeOfDay = datetime

The required datetime argument is any numeric expression, string expression, or any combination, that can represent a time.

Remarks

If datetime is a string, TimeOfDay attempts to convert it to a time using the time separators you specified for your system. If it can't be converted to a valid time, an error occurs.

See Also

Example


Today Statement

Sets the current system date.

Today = date

For systems running Microsoft Windows 95, the required date specification must be a date from January 1, 1980 through December 31, 2099. For systems running Microsoft Windows NT, date must be a date from January 1, 1980 through December 31, 2079. For systems running Microsoft Windows 98 or Microsoft Windows 2000, date must be a date from January 1, 1980 through December 31, 2099.

See Also

Example


Try...Catch...Finally Statement

Provides a way to handle some or all possible errors that may occur in a given block of code, while still running code.

Try
   tryStatements
[Catch1 [exception [As type]] [When expression]
   catchStatements1
[Exit Try]
Catch2 [exception [As type]] [When expression]
   catchStatements2
[Exit Try]
…
Catchn [exception [As type]] [When expression]
   catchStatementsn]
[Exit Try]
[Finally
   finallyStatements]
End Try

Arguments

tryStatements
Required. Statement(s) where an error can occur. Can be a compound statement.
exception
Required. Any variable name. The initial value of exception is the value of the thrown error.
type
Required. Specifies the type of a class filter. If the value of exception is of the type specified by type or of a derived type, the identifier becomes bound to the exception object.
expression
Required. Any expression that describes a generic filter. Typically used to filter by error number.

catchStatements

Required. Statement(s) to handle errors occurring in the associated tryStatement. Can be a compound statement.

Exit Try
Required. Keyword that breaks out of the Try…Catch…Finally structure. Execution resumes with the code immediately following the End Try statement. Not allowed in finallyStatements.
finallyStatements
Required. Statement(s) that are executed after all other error processing has occurred.

Remarks

If errors occur that the programmer has not handled, Visual Studio for Applications simply provides its normal error message to a user, as if there was no error handling.

The tryStatements argument contains code where an error can occur, while catchStatements contains code to handle any error that does occur. If an error occurs in tryStatements, program control is passed to the appropriate catchStatement for disposition. The exception is an instance of the Exception class or an instance of a class that derives from the Exception class corresponding to the error that occurred in tryStatements. The Exception class instance contains information about the error including, among other things, its number and message.

The following simplified example illustrates the structure of the Try…Catch…Finally statement:

Sub TryExample
   Dim x As Integer       ' Declare variables.
Dim y As Integer
   Try                    ' Setup structured error handling.
      x \= y              ' Cause a "Divide by Zero" error.
   Catch e As Exception   ' Catch the error.
      MessageBox.Show e.toString ' Show friendly error message.
   Finally
      Beep                ' Beep after error processing.
   End Try
End Sub

See Also

Example


Structure Statement

Used to create a user-defined class containing one or more elements of a class.

[Public|Private|Friend] Structure varname
NonMethod Declarations
Method Declarations
End Structure

The Structure statement syntax has these parts:

Part | Description
Public | Optional. Entities declared with the Public modifier have public access. There are no restrictions on the use of public entities
Private | Optional. Entities declared with the Private modifier have private access. A private entity is accessible only within its declaration context, including any nested entities.
Friend | Optional. Entities declared with the Friend modifier have friend access. An entity with friend access is accessible only within the program that contains the entity declaration.
varname | Required. Name of the user-defined type; follows standard variable naming conventions.

Remarks

Structures support many of the same features of classes. For example, structures support the ability to define properties, methods, and events with each member defined with either private, friend, or public accessibility. Structures can implement interfaces and handle events. Structures can have parameterized constructors.

The following features of classes are not supported by structures:

  • structures can not explicitly inherit from another type; however they implicitly inherit the methods of the Object class
  • structures can not be inherited from; i.e. all structures are implicitly “CantInherit”
  • it is illegal to define a parameterless constructor for a structure; a parameterless constructor is implicitly defined for a class that initializes all the structure’s data members to their default value
  • it is illegal to define a destructor for a structure
  • the declarations of data members of a structure can not include initializers nor can they use the “As New <type>” declaration syntax or specify an initial size for an array
  • structures are value types rather than reference types
  • the default accessibility level of data member declarations in structures is Public rather than Private as it is for classes and modules.

The fact that structures are value types rather than reference types are reflected in their use rather than their declaration. Specifically:

  • a variable or data member that is declared to be a structure implicitly includes an initialization of the structure via the parameterless constructor. I.E. “Dim s As Struct1” is equivalent to “Dim s As Struct1 = New Struct1()”
  • assigning a structure instance or passing a structure instance to a byval parameter causes the structure to be copied
  • equality testing is performed by a field by field equality test

Note that structures do not support the data member declaration syntax supported by UDTs where the statement simply contained the variable name and an As clause without an initial “Dim” or “Public”.

See Also


Width # Statement

Assigns an output line width to a file opened using the Open statement.

Width (channel, recordwidth)

Arguments

channel
Required. Any valid file number.
recordwidth
Required. Numeric expression in the range 0–255, inclusive, that indicates how many characters appear on a line before a new line is started. If width equals 0, there is no limit to the length of a line. The default value for width is 0.

See Also

Example


Width # Statement Example

This example uses the Width # statement to set the output line width for a file.

Dim I
Open "TESTFILE" For Output As #1   ' Open file for output.
VBA.Width 1, 5   ' Set output line width to 5.
For I = 0 To 9   ' Loop 10 times.
   Print #1, Chr(48 + I);   ' Prints five characters per line.
Next I
Close #1   ' Close file.


With Statement

Executes a series of statements on a single object or a user-defined type.

With object
[statements]
End With

Parameters

object
Required. Name of an object or a user-defined type.
statements
Optional. One or more statements to be executed on object.

Remarks

The With statement allows you to perform a series of statements on a specified object without requalifying the name of the object. For example, to change a number of different properties on a single object, place the property assignment statements within the With control structure, referring to the object once instead of referring to it with each property assignment. The following example illustrates use of the With statement to assign values to several properties of the same object.

With MyLabel
   .Height = 2000
   .Width = 2000
   .Caption = "This is MyLabel"
End With
Note Once a With block is entered, object can't be changed. As a result, you can't use a single With statement to affect a number of different objects.

You can nest With statements by placing one With block within another. However, because members of outer With blocks are masked within the inner With blocks, you must provide a fully qualified object reference in an inner With block to any member of an object in an outer With block.

Note In general, it's recommended that you don't jump into or out of With blocks. The object reference for a With block is stored in a temporary variable that has the same lifetime as the procedure. It is set by the With statement, and thus may not be set if you jump into the With block. It is set to Nothing by End With, so jumping out will not free the reference.

Note : Well said, Glenn.

See Also

Example


With Statement Example

This example uses the With statement to execute a series of statements on a single object. The object MyObject and its properties are generic names used for illustration purposes only.

With MyObject
   .Height = 100      ' Same as MyObject.Height = 100.
   .Caption = "Hello World"   ' Same as MyObject.Caption = "Hello World".
   With .Font
      .Color = Red      ' Same as MyObject.Font.Color = Red.
      .Bold = True      ' Same as MyObject.Font.Bold = True.
   End With
End With


Write # Statement

Writes data to a sequential file. Data written with Write # is usually read from a file with Input #.

Write (channel, output)

Arguments

channel
Required. Any valid file number.
output
Optional. One or more comma-delimited expressionsto write to a file.

Remarks

If you omit the output, a blank line is printed to the file. Multiple expressions can be separated with a comma.

Unlike the Print # statement, the Write # statement inserts commas between items and quotation marks around strings as they are written to the file. You don't have to put explicit delimiters in the list. When Write # is used to write data to a file, only the following data formats are supported and several universal assumptions are followed so the data can always be read and correctly interpreted using Input #, regardless of locale:

  • Numeric data is always written using the period as the decimal separator.
  • For Boolean data, either #TRUE# or #FALSE# is printed. The True and False keywords are not translated, regardless of locale.
  • Date data is written to the file using the universal date format. When either the date or the time component is missing or zero, only the part provided gets written to the file.
  • Nothing is written to the file if output data is Empty. However, for Null data, #NULL# is written.
  • For Error data, the output appears as #ERROR errorcode#. The Error keyword is not translated, regardless of locale.

Write # inserts a newline character, that is, a carriage return–linefeed (Chr(13) + Chr(10)), after it has written the final character in output to the file.

Note You should not write strings that contain embedded quotation marks, for example, "1,2""X" for use with the Input # statement: Input # parses this string as two complete and separate strings.

See Also

Example


Write # Statement Example

This example uses the Write # statement to write raw data to a sequential file.

Open "TESTFILE" For Output As #1   ' Open file for output.
Write #1, "Hello World", 234   ' Write comma-delimited data.
Write #1,   ' Write blank line.

Dim MyBool, MyDate, MyNull, MyError
' Assign Boolean, Date, Null, and Error values.
MyBool = False : MyDate = #February 12, 1969# : MyNull = Null
MyError = CVErr(32767)
' Boolean data is written as #TRUE# or #FALSE#. Date literals are
' written in universal date format, for example, #1994-07-13#
 'represents July 13, 1994. Null data is written as #NULL#.
' Error data is written as #ERROR errorcode#.
Write #1, MyBool ; " is a Boolean value"
Write #1, MyDate ; " is a date"
Write #1, MyNull ; " is a null value"
Write #1, MyError ; " is an error value"
Close #1   ' Close file.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Visual Basic Language Specification

Version 7.0

Draft 13

The Visual Basic Compiler Team


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

1. Introduction


1.1 What is Visual Basic 7.0?

Visual Basic 7.0 is the next step in the evolution of the BASIC language at Microsoft. It is designed to provide the same ease of use for Web programming using the NGWS Frameworks and Runtime that earlier versions of Visual Basic provided for Windows programming.

This document describes the Visual Basic 7.0 language. It is meant to be a complete language description, not a language tutorial or a user's reference manual.


1.2 The purpose of Visual Basic 7.0

For nearly a decade, the Visual Basic language has been a cornerstone of the Windows platform. It is easy to underestimate the impact that Visual Basic 1.0 had on the Windows market – for the first time, writing Windows applications was a simple and relatively painless task, something graspable by a wide range of programmers. Similarly, the introduction of Visual Basic 4.0 was important for helping to establish Automation as the standard object architecture of the Windows platform.

Microsoft is in the middle of a shift, however, from providing an operating system to providing Web Services. This shift recognizes the reality that applications are beginning to migrate from a standalone executable sitting on a user's hard drive to a distributed application delivered by a Web server across the Internet. A key part of Microsoft's thrust into this new Web Services space is the NGWS Frameworks and Runtime. The NGWS Frameworks and Runtime is designed from the ground up to allow developers to easily write and deploy complex Web applications.

Visual Basic 7.0 is designed to provide the same ease of use for building applications for the NGWS Frameworks and Runtime that earlier versions of Visual Basic provided for developing on the Windows platform.


1.3 Statement of principles

The design of Visual Basic 7.0 encompasses the following principles, in relative order of importance:

  • Visual Basic 7.0 is recognizable as the descendent of previous versions of Visual Basic, and an existing Visual Basic programmer will feel an immediate familiarity with the language.
  • Visual Basic 7.0 syntax and semantics are simple, straightforward and easy to understand. The language avoids features that cause unexpected behavior.
  • Visual Basic 7.0 allows developers to take advantage of the major features of the NGWS Frameworks and Runtime and is consistent with the its conventions.
  • Visual Basic 7.0 is reasonably "upgradeable" from previous versions of Visual Basic. That is, it is possible in a significant number of cases to take existing Visual Basic code and, with a well-defined set of transformations, produce a working Visual Basic 7.0 program.
  • Because the NGWS Runtime is explicitly designed to support multiple computer languages, Visual Basic 7.0 is designed to work well in a multi-language environment.
  • Visual Basic 7.0 is as compatible with previous versions of Visual Basic as possible. Whenever practical, Visual Basic 7.0 has the same syntax, the same semantics and the same runtime behavior as its predecessors.

These principles complement the original design principles of Visual Basic. For the purpose of completeness those principles were:

  • Visual Basic is designed to be as safe a language to write in as possible. In general, Visual Basic tries to balance reliability, ease of use, and efficiency in the definition of the language.
  • Visual Basic is designed to be extremely approachable. A reasonable understanding of the language should be attainable by a large portion of computer users and ease of use is significant.
  • Visual Basic is designed to enable rapid program development, while not compromising reliability.
  • Visual Basic code is predictable and efficient.
  • Visual Basic may be used either as a strongly typed language, or as a loosely typed language. This enables rapid development in the latter case, better correctness of user code in the former.


1.4 Guidelines for language changes

In order to move the Visual Basic language forward, it is necessary to introduce incompatibilities between the Visual Basic 7.0 language and previous versions of Visual Basic. Because of the potential impact of language incompatibilities on users, it is done so only when there is a clear justification. In general, there are only two situations that are considered serious enough to justify an incompatibility:

  • A feature has caused significant confusion or difficultly for Visual Basic programmers, based on the feedback that the Visual Basic team has collected from end users.
  • A feature is fundamentally in conflict with the design of the NGWS Frameworks and Runtime.

When designing a feature that is incompatible with previous versions, the ability to upgrade code from previous versions is taken into consideration, but is not an absolute requirement.


1.5 Grammar notation

There are two main grammars interspersed throughout this specification: a lexical grammar and a syntactic grammar. The lexical grammar defines how characters can be combined to form tokens; the syntactic grammar defines how the tokens can be combined to form Visual Basic 7.0 programs. There are also several secondary grammars used for preprocessing operations like conditional compilation. It is important to note that the grammars in this specification are not intended to be formal (that is, usable by LEX or YACC), but are designed to be human readable.

All of the grammars use a modified BNF notation, which consists of a set of productions that include non-terminal and terminal names. Each non-terminal is defined by one or more productions. In a production, non-terminal names are shown in italic type, and terminal names are shown in a bold fixed-width font. Text in normal type and surrounded by angle bracket meta-symbols is an informal terminal (for example, "< all Unicode characters >"). Each grammar starts with the non-terminal Start.

The casing of alphabetic characters is unimportant in Visual Basic 7.0 programs. For simplicity, all terminals will be given in a "standard casing," but any casing will match them. Terminals that are printable elements of the ASCII character set are represented by their corresponding ASCII characters.

A set of productions begins with the name of a non-terminal, followed by two colons and an equals sign. The right-hand side contains a terminal or non-terminal production. Line breaks and indentation may be added for readability and are not part of the production. A non-terminal may have multiple productions that are separated by the vertical bar meta-symbol ("|"). Items included in the meta-symbols square brackets ("[]") are optional. A meta-symbol plus ("+") following an item means the item may occur one or more times.


2. Lexical Grammar

The first step in compiling a Visual Basic 7.0 program is to translate a raw stream of Unicode characters into a series of logical lines made up of an ordered set of lexical tokens. A logical line spans from either the start of the stream or a line terminator through to the next line terminator, excepting line continuations.

Start ::= [ LogicalLine+ ]

LogicalLine ::= [ LogicalLineElement+ ] [ Comment ] LineTerminator
LogicalLineElement ::= Whitespace | Token
Token ::= Identifier | Keyword | Literal | Separator | Operator


2.1 Characters and lines

Visual Basic 7.0 programs are comprised of characters from the Unicode character set.

Character ::= < any Unicode character except a LineTerminator >


2.1.1 Line termination

Unicode line break characters separate lines. Because Visual Basic 7.0 is not a free-format language, line terminators are significant and play a part in the syntactic grammar.

LineTerminator ::= < Unicode line break characters >


2.1.2 Line continuation

A single underline character preceded by at least one whitespace character appearing as the last non-whitespace character of a text line is a line continuation. Line continuations are treated as whitespace and do not mark the end of logical lines.

LineContinuation ::= Whitespace _ [ Whitespace+ ] LineTerminator


2.1.3 Whitespace

Whitespace serves only to separate tokens and is otherwise ignored. Logical lines containing only whitespace are ignored. Note that line terminators are not considered whitespace.

Whitespace ::= < Unicode blank characters > | LineContinuation


2.1.4 Comments

A comment begins with a single quote character or the keyword REM anywhere on a source line. The end of the physical line ends the comment, and no processing at all is done on the characters between the beginning of the comment and the line terminator. Comments are always ignored.

Comment ::= CommentMarker [ Character+ ]
CommentMarker ::= ' | REM


2.2 Identifiers

An identifier may be composed of Unicode alphanumeric characters and the underscore character, and begins with an underscore or an alphabetic character. If an identifier begins with an underscore, it must contain at least one other character to disambiguate from a line continuation.

Regular identifiers may not match keywords, but escaped identifiers can. An escaped identifier is an identifier delimited by square brackets. Escaped identifiers follow the same rules as regular identifiers except that they may match keywords and may not have type characters.

Identifiers are case insensitive. Two identifiers that differ only in their alphabetic casing are considered the same identifier.

Identifier ::=
NonEscapedIdentifier [ TypeCharacter ] |
EscapedIdentifier
NonEscapedIdentifier ::= < IdentifierName but not Keyword >
EscapedIdentifier ::= [ IdentifierName ]
IdentifierName ::= IdentifierStart [ IdentifierCharacter+ ]
IdentifierStart ::=
AlphaCharacter |
UnderscoreCharacter IdentifierCharacter
IdentifierCharacter ::=
UnderscoreCharacter
AlphaCharacter
NumericCharacter
CombiningCharacter
AlphaCharacter ::= < Unicode alphabetic character >
NumericCharacter ::= < Unicode decimal digit character >
CombiningCharacter ::= < Unicode combining character >
UnderscoreCharacter ::= < Unicode connection character >
IdentifierOrKeyword ::= Identifer | Keyword


2.2.1 Type characters

A type character may optionally follow a non-escaped identifier. The type character is not considered part of the identifier itself, and serves only to denote the type of the identifier. If a type character is used in a declaration, then the type character must agree with the type of the identifier. If the type is omitted from the declaration, the type of the type character is implicitly substituted.

No whitespace may come between an identifier and its type character. If a type character is appended to an identifier that conceptually does not have a type (for example, a namespace name), or the type of the type character disagrees with the declared type of the of the identifier, an error results. There are no type characters for Byte or Short, due to the lack of suitable characters.

TypeCharacter ::=
IntegerTypeCharacter |
LongTypeCharacter |
DecimalTypeCharacter |
SingleTypeCharacter |
DoubleTypeCharacter |
StringTypeCharacter
IntegerTypeCharacter ::= %
LongTypeCharacter ::= &
DecimalTypeCharacter ::= @
SingleTypeCharacter ::= !
DoubleTypeCharacter ::= #
StringTypeCharacter ::= $


2.3 Keywords

A keyword is a word that has special meaning in some language constructs. (Null is reserved even though it has no meaning in Visual Basic 7.0)

Keyword ::= one of

AddHandler | AddressOf | Alias | And | Ansi
As | Assembly | Auto | BeginEpilogue | Binary
BitAnd | BitNot | BitOr | BitXor | Boolean
ByRef | Byte | ByVal | Call | Case
Catch | CBool | CByte | CChar | CDate
CDec | CDbl | Car | CInt | Class
CLng | CObj | Compare | Const | Const
CShort | CSng | CStr | CType | Date
Decimal | Declare | Default | Delegate | Dim
Do | Double | Each | Else | ElseIf
End | EndIf | EndPrologue | Enum | Erase
Error | Event | Exit | Explicit | ExternalSource
False | Finally | For | Friend | Function
get | GetType | GoTo | Handles | If
Implements | Imports | In | Inherits | Integer
Interface | Is | Lib | Like | Long
Loop | Me | Mod | Module | MustInherit
MustOverride | MyBase | MyClass | Namespace | Next
New | Not | Nothing | NotInteritable | NotOverridable
Null | Object | Off | On | Option
Optional | Or | Overloads | Overridable | Overrides
ParamArray | Preserve | Private | Property | Protected
Public | RaiseEvent | ReadOnly | ReDim | REM
RemoveHandler | Resume | Return | Select | Set
Shadows | Shared | Short | Single | Static
Step | Stop | Strict | String | Sturcture
Sub | SyncLock | Text | Then | Throw
To | True | Try | TypeOf | Unicode
Until | When | While | With | WithEvents
WriteOnly | Xor |  |  |


2.4 Literals

A literal is a textual representation of a particular value of a type. Visual Basic 7.0 literals include integer, floating point, decimal, string, date, decimal and boolean literals.

Literal ::= NumericLiteral | StringLiteral | CharacterLiteral | DateLiteral | BooleanLiteral | NullLiteral
NumericLiteral ::= IntegerLiteral | FloatingPointLiteral | DecimalLiteral


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

2.4.1 Boolean literals

True and False are literals of the Boolean type that map to the true and false state, respectively.

BooleanLiteral ::= True | False


2.4.2 Integer literals

Integer literals can be decimal (base 10), hexadecimal (base 16) or octal (base 8). A decimal integer literal is a string of decimal digits. An octal literal is &O followed by a string of octal digits. A hexadecimal literal is &H followed by a string of hexadecimal digits. Decimal literals are always signed; octal and hexadecimal literals are always unsigned.

The type of a literal is determined by its value or by the following type character. If no type character is specified, values in the range of the Integer type are typed as Integer; values outside the range for Integer are typed as Long. Octal and hexadecimal literals are treated as a bitwise representation of a signed type for the purpose of determining type; this means that the literal &HFFFFFFFF is typed as an Integer, not a Long. If an integer literal's type is at odds with the size required to hold the integer literal, an error results.

IntegerLiteral ::= IntegralLiteralValue [ IntegralTypeCharacter ]
IntegralTypeCharacter ::=
ShortCharacter |
IntegerCharacter |
LongCharacter |
IntegerTypeCharacter |
LongTypeCharacter
ShortCharacter ::= S
IntegerCharacter ::= I
LongCharacter ::= L
IntegralLiteralValue ::= IntLiteral | OctalLiteral | HexLiteral
IntLiteral ::= Digit+
OctalLiteral ::= & O OctalDigit+
HexLiteral ::= & H HexDigit+
OctalDigit ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7
Digit ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
HexDigit ::= 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F


2.4.3 Floating point literals

A floating-point literal is a mantissa, which consists of string of decimal digits, an optional decimal point (the ASCII period character), and an optional exponent. A floating-point literal is of type Double if no type character or the Double type character is specified. If the Single type character is specified, the literal is of type Single. If a floating-point literal's type is at odds with the size required to hold the floating point literal, an error results.

FloatingPointLiteral ::=
FloatingPointLiteralValue [ FloatingPointTypeCharacter ] |
IntLiteral FloatingPointTypeCharacter
FloatingPointTypeCharacter ::=
SingleCharacter |
DoubleCharacter |
SingleTypeCharacter |
DoubleTypeCharacter
SingleCharacter ::= F
DoubleCharacter ::= R
FloatingPointLiteralValue ::=
IntLiteral . IntLiteral [ Exponent ] |
. IntLiteral [ Exponent ] |
IntLiteral Exponent
Exponent ::= E [ Sign ] IntLiteral
Sign ::= + | -


2.4.4 Decimal Literals

A decimal literal is a string of digits, optionally containing a decimal point, followed by the Decimal type character. If the literal is an invalid decimal value, an error results.

DecimalLiteral:
IntLiteral . IntLiteral DecimalCharacter |
. IntLiteral DecimalCharacter |
IntLiteral DecimalCharacter
DecmialLiteralTypeCharacter ::= DecimalCharacter | DecimalTypeCharacter
DecimalCharacter ::= D


2.4.5 String literals

A string constant is a sequence of zero or more Unicode characters beginning and ending with an ASCII double quote character. Within a string, a sequence of two double quotes is an escape to represent a double quote in the string. A string constant is of the String type.

StringLiteral ::= " [ StringCharacter+ ] "
StringCharacter ::= < Character except for " > | ""


2.4.6 Character literals

A character literal represents a single Unicode character of the Char type. Two double quotes is an escape to represent a double quote.

CharacterLiteral ::= " StringCharacter " C


2.4.7 Date literals

A date literal is a string of Unicode characters representing a date enclosed between two ASCII sharp characters. The literal evaluates to a Date value of the equivalent date/time. The method of converting from the Unicode characters to a date/time value is unspecified.

DateLiteral ::= # Character+ #


2.4.8 Null literal

Nothing is a literal that represents the null type. It is not possible to declare a variable of the null type, nor is it possible to convert to the null type. The null type may be converted to any reference type.

ReferenceLiteral ::= Nothing


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

2.5 Separators

The following separators formed from ASCII characters are punctuators:

Separator ::= ( | ) | ! | # | , | . | :


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

2.6 Operators

The following ASCII characters denote operators or may be combined to denote operators:

Operator ::= & | * | + | - | / | \ | ^ | < | = | >


3. Preprocessing

Once a file has been lexically analyzed, several different kinds of source preprocessing are done. The most important is conditional compilation, which affects which source is processed by the syntactic grammar. There are also two types of directives – external source directives and region directives – that provide meta-information about the source.


3.1 External source directives

A source file may include external source directives that indicate a mapping between source lines and text external to the source. External source directives have no effect on compilation and may not be nested.

Source ::= [ ExternalSourceElement+ ]
ExternalSourceElement ::= ExternalSourceGroup | LogicalLine
ExternalSourceGroup ::=
# ExternalSource ( StringLiteral , IntLiteral ) LineTerminator
[ LogicalLine+ ]
# End ExternalSource LineTerminator


3.2 Prologue/epilogue directives

Prologue/epilogue directives group lines of source and have no effect on compilation.

Source ::= [ RegionElement+ ]
RegionElement ::= EpilogueDirective | PrologueDirective | LogicalLine
PrologueDirective ::= # EndPrologue
EpilogueDirective ::= # BeginEpilogue


3.3 Conditional compilation directives

Conditional compilation controls whether sequences of logical lines are translated into actual code. At the beginning of conditional compilation, all logical lines are enabled; enclosing lines in conditional compilation statements may selectively disable sequences of lines within the file.

Source ::= [ ConditionalElement+ ]
ConditionalElement ::= ConditionalIfGroup | ConditionalConstantDeclaration | LogicalLine


3.3.1 Conditional constants

A conditional constant declares an identifier (which may match keywords) in a per-file conditional compilation declaration space. The scope of the constant is the entire source file in which the constant is defined, although previous to its textual declaration the constant contains Nothing. Conditional constant names may be used without having being declared – in that case, the constant always contains Nothing. The compilation environment may also define any number of conditional constants in the conditional compilation declaration space.

The conditional constant may be assigned any constant expression. All conditional constants are considered to be of type Object.

ConditionalConstantDeclaration ::= # Const IdentifierOrKeyword = ConstantExpression LineTerminator


3.3.2 Conditional statements

Each of the conditional compilation expressions within a single conditional compilation statement group is evaluated in textual order from first to last until one of the expressions evaluates to True. All lines enclosed by the group are disabled except for lines between the statement containing the True expression and the next conditional statement of the group, or between the else statement and the end statement if an else appears in the group and all of the expressions evaluate to False.

The constant expression is evaluated and then converted to Boolean. If the expression is not convertible to Boolean, an error results.

ConditionalIfGroup ::=
# If ConstantExpression [ Then ] LineTerminator
[ ConditionalElement+ ]
[ ConditionalElseIfGroup+ ]
[ ConditionalElseGroup ]
# End If LineTerminator
ConditionalElseIfGroup ::=
# ElseIf ConstantExpression [ Then ] LineTerminator
[ ConditionalElement+ ]
ConditionalElseGroup ::=
# Else LineTerminator
[ ConditionalElement+ ]


4. General Concepts

A Visual Basic 7.0 program is made up of a collection of entities that have names. These entities are introduced through declarations and represent the "meaning" of the program.

At a top level, namespaces are entities that organize other entities. They may contain nested namespaces and types. Types are entities that describe values and define executable code. Types may contain nested types and type members. Type members are constants, data members, methods, properties, events, enumeration values and constructors.


4.1 Declaration spaces

The ability to declare an entity is governed by the entity's containing declaration space. A declaration space is a collection of entities that allows for unambiguous name resolution. Except in the case of overloaded type members, it is an error for two or more declarations to introduce an entity with the same name into a declaration space. Also, a declaration space may never contain different kinds of entities with the same name. For example, a declaration space can never contain a data member and a method by the same name.

Entities are introduced into a declaration space by either declarations or inheritance. An entity's containing declaration space is called the entity's declaration context. A declaration, in turn, creates a new declaration space to contain the entity declarations (if any) nested within it. Thus, the declarations in a program create a hierarchy of declaration spaces.


4.1.1 Overloading and signatures

The only way to declare more than one entity of the same kind with the same name in a declaration space is through overloading. Overloading may only occur on type members, specifically methods, instance constructors and properties. Signatures are the enabling mechanism for the overloading of type members — every type member that can be overloaded has a signature. A name may have several type members overloaded on it, provided that the signatures of all the type members are unique.

The signature of a type member is made up of the name of the type member and the number and types of its formal parameters (unlike previous versions, Visual Basic 7.0 considers enumerations distinct types). It is important to note that the following play no part in signatures: modifiers to a signature (Shared, etc), modifiers to a parameter (ByVal, ByRef), the names of parameters, the return type of a method, and the element type of a property. It is not possible to overload on any of these things.

A method with optional parameters is considered to have multiple signatures, one for each of the possible parameter lists that can be specified by the caller. A method with a paramarray parameter is considered to have an infinite number of signatures: one with the explicit type of the paramarray (that is, a single-dimensional array), and then a progression of signatures starting with the parameter list without the paramarray and successively adding parameters of the element type of the paramarray.


4.2 Inheritance

An inheritance relationship between two types is one in which one of the types derives from the other type, the latter type being called the base type. In general, a derived type's declaration space implicitly contains all of the accessible type members of its direct base type, except for the base's constructors. Some important aspects of inheritance are:

  • Inheritance is transitive. If C is derived from B, and B is derived from A, then C inherits the type members declared in B as well as the type members declared in A.
    • A derived type extends its direct base type. A derived type can add new type members to those it inherits or shadow inherited type members, but it cannot remove the definition of an inherited type member.
    • Because an instance of a type contains all of the type members of its base type, a conversion always exists from a derived type to its base type.

Visual Basic 7.0's type system is unified in the sense that all types must have a base type, except for the type Object. Thus, Object is the ultimate base type of all types, and all types can be converted to it.


4.2.1 NotOverridable Classes

A NotOverridable class is a class that can not be inherited from. NotOverridable classes are primarily used to prevent unintended inheritance, but also enable certain runtime optimizations. In particular, all methods of NotOverridable classes are implicitly NotOverridable methods which can be invoked faster than Overridable methods.


4.2.2 Interfaces and multiple inheritance

Interface inheritance follows different rules than regular type inheritance in that an interface may derive from multiple interfaces. This raises the possibility that an interface can inherit a type member with the same name from multiple base interfaces. In that case, the multiply inherited name is not available in the derived interface. That is, when an interface inherits members with the same name from multiple base interfaces, referring to any of those members through the derived interface causes an error, regardless of signatures or overloading. Conflicting members must be referenced through a base interface name.


4.2.3 Shadowing

A derived type can shadow the name of inherited type members by redeclaring it. Shadowing a name does not remove the inherited type members by that name; it merely makes all of the inherited type members (including overloads) unavailable in the derived class. The shadowing declaration may be any type of entity. Note that it is legal to shadow a name of type members that have been multiply inherited through interface inheritance, thus making the name available in the derived interface.

Because methods are allowed to shadow inherited methods, it is possible for a class to contain several overridable methods with the same signature. This does not present an ambiguity problem, since all but the most derived method are hidden. Shadowing requires the explicit Shadows modifier, or else an error will be reported. It is not an error to specify the Shadows modifier if there is no such type member name to shadow.

ShadowsModifier ::= Shadows


4.3 Interface implementation

An implementation relationship between a type and interface is one in which a type declares that it implements the interface. Such a declaration requires that the type implement all the type members of the interface it is implementing. A type that supports a particular interface is convertible to that interface. This allows types to guarantee that they support certain methods without requiring an inheritance relationship.

A type implementing an interface with multiply inherited type members of the same name must still implement those methods even though they can not be accessed directly from the derived interface being implemented. Even MustInherit classes must provide declarations of all the members of interfaces that they implement; however they can defer implementation of these methods to derived classes by declaring the methods as MustOverride.


4.4 MustInherit Classes

A MustInherit class is an incomplete class where the implementation of some of the methods and/or properties of the class is not provided and instead must be provided by inheriting classes. A MustInherit class cannot be instantiated so it is an error to use the New operator on such a class. While it is possible to have variables and values whose compile time types are a MustInherit class, such variables and values will necessarily either be Nothing or contain references to instances of classes which inherit from the MustInherit class.

When a class derives from a MustInherit class, the deriving class must either also be a MustInherit class or it must override and provide implementations for all of the base class's MustOverride methods.


4.5 Overridable methods

An Overridable method is a method whose implementation can be changed by derived classes. This enables classes to exhibit polymorphic behavior wherein the actions performed by a method invocation vary depending on the runtime type of the instance through which the method is invoked.

MustOverride methods are a form of overridable method in which the class that introduces the method defines the method name, return type, parameter types, and accessibility level but no implementation of the method is provided. MustOverride methods are allowed only in MustInherit classes.

In contrast to overridable methods, the implementation of a non-overridable method is invariant: the implementation is the same whether the method is invoked on an instance of the class in which it is declared or an instance of a derived class. In a non-overridable method invocation, the compile time type of the instance is the determining factor.


4.5.1 Overriding methods

A type may override an inherited overridable method by supplying a method with the same name and signature and marking the declaration with the Overrides keyword. Whereas a method declared with Overridable introduces a new method, a method declared with Overrides replaces the inherited implementation of a method. Normally an overriding method is itself overridable; however it it possible to declare an overriding method as NotOverridable, which prevents any further overriding of the method in derived classes.

A compile time error occurs unless all of the following are true for an overriding method:

  • The declaration context contains an accessible inherited method with the same signature as the override method.
  • The inherited method being overridden is overridable. A method is overridable if it is declared with either Overridable, MustOverride, or Overrides.
  • The accessibility domain of the method being declared is the same as the accessibility domain of the inherited method being overridden.

In an overridable method invocation, the runtime type of the instance for which the invocation takes place determines the actual method implementation to invoke. At runtime the most derived implementation of the instance method is called, based on the type of the instance.


4.5.2 Implementing methods

Both structures and classes can implement interfaces. The intent to implement an interface is declared by the Implements statement which specified one or more interfaces to be implemented. The structure or class must also supply an implementation of each member of the interface by providing a method with the same signature and an Implements clause. A single method may implement several interface type members, as long as they all have the same signature.

A inherited class may not implement an interface type member already implemented by any of its base classes. However, when an interface method is implemented using an overridable method in a base type, it is possible for derived classes to override the overridable method and alter the implementation of the interface. A derived class may implement an interface whose base interfaces are implemented by its base classes. In that case, the derived class only implements the interface's type members not already implemented by the base types.


4.6 Accessibility

Each declared item has an accessibility level.. When access to an entity is allowed, the entity is said to be accessible. Conversely, when access to an entity is disallowed, the entity is said to be inaccessible. Accessibility does not change the scope of an entity's name. The accessibility domain of a declaration is the set of all contexts in which the declared entity is accessible.

The five access levels are public, protected, friend, protected friend, and private. The most permissive access level is public, and the four other access levels are all subsets of public access. The least permissive access level is private, and the four other access levels are all supersets of private access.

The access level for a declaration is specified via an optional access modifier, which can be can be Public, Protected, Friend, Private or the combination of Protected and Friend. If no access modifier is specified, a default access level is used depending on the declaration context; the permitted access levels also depend on the declaration context.

  • Entities declared with the Public modifier have public access. There are no restrictions on the use of public entities.
  • Entities declared with the Protected modifier have protected access. Protected access can only be specified on members of classes (both regular type members and nested classes), although there are different access rules for the two. A protected type member contained in a class is accessible to entities contained in a derived class, provided the access takes place through the derived class. A protected type nested in a class is accessible to items contained in a derived class, provided the access takes place through the base class (since nested types are not inherited). Protected access is not a superset of friend access.
  • Entities declared with the Friend modifier have friend access. An entity with friend access is accessible only within the assembly that contains the entity declaration.
  • Entities declared with the Protected Friend modifiers have the union of protected and friend accessibility. That is they are accessible from all code within the same assembly and they are accessible from all derived classes.
  • Entities declared with the Private modifier have private access. A private entity is accessible only within its declaration context, including any nested entities.

There is never any restriction on the level of accessibility specified in a declaration. For example, a type declared with Private access may contain a type member with Public access.

AccessModifier ::= Public | Protected | Friend | Private


4.6.1 Constituent types

Types that are referenced in the declaration of a type or type member are called the constituent types of the declaration. For example, the type of a constant, the return type of a method and the parameter types of a constructor are all constituent types. The accessibility domain of a constituent type of a declaration must be the same as or a superset of the accessibility domain of the declaration itself.


4.7 Scope

The scope of an entity's name is the set of all contexts within which it is possible to refer to that name without qualification. In general, the scope of an entity's name is its declaration context and is visible throughout its entire scope. However, an entity's declaration may contain nested declarations of entities with the same name. In that case, only the nested entity's name is visible in the nested declaration, and the containing entity's name is shadowed. Access to a shadowed name is only possible through qualification.

Shadowing through nesting occurs when namespaces or types are nested within namespaces, when types are nested within other types, and in the bodies of type members. Shadowing through the nesting of declarations always occurs implicitly, no explicit syntax is required. When a name in an inner scope shadows a name in an outer scope, it shadows all overloaded entities of that name.


4.7.1 Qualified names

Names may be qualified by other names. This can be useful when a declaration or executable statement needs to refer to a name outside of that name's scope or to a shadowed entity. A qualified name is a series of identifiers separated by periods; a name on the right side of a period is resolved in the declaration space specified by the name on the left side of the period.

The fully qualified name of an entity is a qualified name that contains the name of all containing entities. The fully qualified name of an entity is N.T, where T is the name of the entity and N is the fully qualified name of its containing entity.

Because other languages may introduce entities that match keywords in the language, Visual Basic 7.0 allows keywords to be part of a qualified name as long as they follow a period. Keywords used in this way are treated as identifiers.

QualifiedIdentifier ::=
Identifier |
QualifiedIdentifier . IdentifierOrKeyword


4.8 Name Resolution

Name resolution is the process of matching a name reference to an entity or set of entities (in the case of overloaded type members). The process starts with a name in a particular context, and then resolves the name through a set of steps.


4.8.1 Name matching

A name matches an entity or set of overloaded entities if the following conditions are true:

  • The names are the same, ignoring casing.
  • If the referencing context requires a namespace or type, the entity is a namespace or type. This means that in cases where a type name or namespace name is unambiguously needed, locals and type members do not shadow namespaces and types.


4.8.2 Qualified name resolution

Given a qualified name of the form N.R, where R is the rightmost identifier in the qualified name:

  • Resolve N, which may be either a qualified or unqualified name. If resolution of N fails or doesn't resolve to a namespace or type declaration, an error occurs. If R matches accessible members of N, then stop.
  • Otherwise, if N contains one or more standard modules, and R matches accessible members of exactly one standard module, then stop.
  • Otherwise, an error occurs.


4.8.3 Unqualified name resolution

Given an unqualified name R:

  • If the referencing context is a method, for each nested block containing the reference context, starting from the innermost and going to the outermost:
    • If R matches a local or parameter, then stop. If the local matched is the function return local or the getter return local of a property and the referencing context is not a variable expression, then continue. If the local matches is the setter value local of a property and the referencing context is a variable expression, then continue.
  • Otherwise, for each nested type containing the reference context, starting from the innermost and going to the outermost:
    • If the current type is an interface and R matches accessible type members that were inherited from more than one base interface, then an error occurs.
    • Otherwise, if R matches accessible members of the type, then stop.
  • Otherwise, for each nested namespace containing the reference context, starting from the innermost and going to the outermost (global) namespace do the following:
    • If R matches an accessible member of the namespace, then stop.
    • Otherwise, if the namespace contains one or more standard modules, and R matches accessible members in exactly one standard module, then stop. If R matches accessible members in more than one standard module, an error occurs.
    • Otherwise, if the namespace declaration for the namespace has one or more import aliases, and R matches one of them, then stop.
    • Otherwise, if the namespace declaration for the namespace has one or more namespace imports and R matches an accessible member in exactly one namespace, then stop. If R matches an accessible member in more than one namespace, an error results.
  • Otherwise, an error occurs.


4.9 Variables

A variable stores values of a particular type. A variable may or may not have a physical storage location associated with it. Visual Basic 7.0 is a type-safe language, which means that every variable in a program has a type and the language guarantees that values stored in variables are always of the appropriate type. Every type has a "default value" which variables of that type that represent storage locations are initialized to before any reference to the variable can be made. For a variable of a value type, the default value is the result of initializing each field to the default value of its type. For a variable of a reference type, the default value is Nothing.


5. Attributes

The Visual Basic 7.0 language enables the programmer to specify declarative information about entities defined in the program. For example, decorating a method in a class with the modifiers Public, Protected Friend, Protected, Friend, or Private specifies its accessibility.

Visual Basic 7.0 also enables programmers to invent new kinds of declarative information and to specify them for various program entities. For instance, a framework might define a HelpContext attribute that can be placed on program elements such as classes and methods to provide a mapping from program elements to documentation.

New kinds of declarative information are defined through the declaration of attribute classes, which may have positional parameters and data member/property initializers. The new declarative information is specified on entities through attribute sections. Individual attributes specified on declarations may be retrieved at runtime through the NGWS Runtime reflection. Reflection is a set of classes that provides users access to the descriptions of classes.


5.1 Attribute classes

The declaration of an attribute class defines a new kind of attribute that can be placed on a declaration. A class that derives from System.Attribute is an attribute class. The attribute class must have a System.AttributeUsage attribute that declares what the attribute is valid on, whether it may be used multiple times in a declaration and whether it is inherited.

To be recognized by Visual Basic 7.0, the declaration of an attribute class is subject to the following additional restrictions:

  • The attribute class must have public accessibility and may not be abstract.
  • All of the types in which an attribute class is nested must have public accessibility.
  • The attribute class must have at least one public instance constructor.
  • Each of the formal parameter types for each of the public constructors of an attribute class must be a legal attribute type.
  • Each of the public non-shared read-write data members must be a legal attribute type.

A type is an attribute type if it is one of the following:

  • An primitive type except for Decimal.
  • The type System.Type or System.String.
  • An enumerated type, provided that it has public accessibility and that the types in which it is nested (if any) also have public accessibility.

It is not an error to declare an attribute class in Visual Basic 7.0 that does not follow the rules outlined above. However, an attribute that violates any of the rules is not usable in an attribute section.


5.2 Attribute sections

Attributes are specified in attribute sections. Each attribute section is surrounded in angle brackets, with multiple attributes specified in a comma-separated list. The order in which attributes are specified and the manner in which they are arranged is not significant. Attributes may be single use only. If a single use attribute is specified more than once in an attribute section, it is an error. Attributes may also restrict the kinds of declarations they may be used on. If an attribute is specified on a kind of declaration it does not support, it is an error.

Attributes may be inheritable. A derived type inherits all inheritable attributes defined on its base type. If the derived type declares an attribute of the same type as an inherited attribute, the derived declaration overrides the base declaration if it single-use. Multi-use attributes are always aggregated.

An attribute consists of an optional attribute modifier, an attribute name and an optional list of positional arguments and data member/property initializers. If there are no parameters or initializers, the parenthesis may be omitted. If an attribute has a modifier, it must be in an attribute block at the top of a source file. Unlike a normal constructor invocation, if an attribute has no parameters, it may omit the parenthesis.

Attributes ::= < AttributeList >
AttributeList ::=
Attribute |
AttributeList , Attribute
Attribute ::= [ AttributeModifier : ] AttributeName [ ( [ AttributeArguments ] ) ]
AttributeModifier ::= Assembly | Module


5.2.1 Assembly and module attributes

A source file may contain an attribute block at the top of the file that specifies attributes for the NGWS Runtime assembly or module that will contain the source file. Each attribute in the attribute block must be prefixed by an optional modifier, either Assembly or Module, and a colon.


5.3 Attribute name

The name of an attribute specifies an attribute class. The name of an attribute class that corresponds to an attribute identifier is either the identifier itself or the concatenation of the qualified identifier and "Attribute". When resolving an attribute identifier, the identifier will first be looked up as-is. If that lookup fails, then "Attribute" will be appended and the lookup tried again. Thus, an attribute specified as System.Attr can have either a corresponding attribute class of System.Attr or System.AttrAttribute.

AttributeName ::= QualifiedIdentifier


5.4 Attribute arguments

Arguments to an attribute may take two forms: positional arguments and data member/property initializers. Positional arguments to the attribute (if any) must precede the data member/property initializers. A positional argument consists of a constant expression; a data member/property initializer consists of an identifier, followed by a colon and an equal sign, followed by a constant expression.

Given an attribute with attribute class T, positional argument list P and data member/property initializer list N, determining whether the arguments are legal consists of the following steps:

  • Follow the compile time processing steps for compiling an expression of the form New T(P). This either results in a compile time error, or determines a constructor on T that can be invoked at runtime.
  • If the constructor determined in the step above does not have public accessibility, then a compile time error occurs.
  • For each named argument Arg in N:
    • Let Name be the identifier of the data member/property initializer Arg.
    • Name must identify a non-shared read-write public data member or property on T. If T has no such data member or property, then a compile time error occurs.
AttributeArguments ::=
AttributePositionalArgumentList |
AttributePositionalArgumentList , DataMemberPropertyInitializerList |
DataMemberPropertyInitializerList
AttributePositionalArgumentList ::=
ConstantExpression |
AttributePositionalArgumentList , ConstantExpression
DataMemberPropertyInitializerList ::=
DataMemberPropertyInitializer
DataMemberPropertyInitializerList , DataMemberPropertyInitializer
DataMemberPropertyInitializer ::= Identifier : = ConstantExpression


6. Source Files and Namespaces

A Visual Basic 7.0 program consists of one or more separate source files. When a program is compiled, all of the source files are processed together. Thus, source files can depend on each other, possibly in a circular fashion without any forward-declaration mechanism.

A source file consists of an optional set of attributes, option directives and import directives, followed by a namespace body. The body of the source file functions as an implicit namespace declaration for the global namespace, meaning that all declarations at the top level of a source file are placed in the global namespace. The textual order in which declarations are made in the program text is generally of no significance, with some exceptions.

Source ::=
[ Attributes ]
[ OptionDirective+ ]
[ ImportsDirective+ ]
[ NamespaceBody ]


6.1 Compilation options

There are five compilation options that affect the semantics of the language. Three options, strict type semantics, explicit declaration semantics and comparison semantics, can be specified using option directives or can be defined by the compilation environment. The other two options may only be defined by the compilation environment. An option directive applies only to the source file in which it appears, and only one of each type of option directive may appear in a source file.

OptionDirective ::= OptionExplicitDirective | OptionStrictDirective | OptionCompareDirective


6.1.1 Explicit declaration

The Option Explicit directive determines whether local variables may be implicitly declared. The directive may be followed by the keywords On or Off, if the On/Off keywords are omitted, then On is assumed. If no directive is specified in a file, then the compilation environment determines which will be used. Explicit declaration semantics are covered in more detail in the Statements chapter.

OptionExplicitDeclaration ::= Option Explicit [ OnOff ] LineTerminator
OnOff ::= On | Off


6.1.2 Strict type checking

The Option Strict directive determines whether conversions and operations on Object are governed by "strict" or "permissive" type semantics. The directive may be followed by the keywords On or Off, if the On/Off keywords are omitted, then On is assumed. If no directive is specified in a file, then the compilation environment determines which will be used. Strict and permissive semantics are covered in more detail in the Conversions and Operators chapters.

OptionStrictDirective ::= Option Strict [ OnOff ] LineTerminator


6.1.3 String comparison types

The Option Compare directive determines the semantics of string comparisons. String comparisons may either be done through binary comparisons or text comparisons. If no directive is specified in a file, then the compilation environment determines which will be used. The semantics of string comparisons is covered in more detail in the Operators chapter.

OptionCompareDirective ::= Option Compare CompareOption LineTerminator
CompareOption ::= Binary | Text


6.1.4 Integer overflow checks

Integer operations can either be checked or not checked for overflow conditions. If overflow conditions are being checked and an integer operation overflows, a System.OverflowException exception is thrown. Otherwise, the integer operation silently overflows. The compilation environment determines whether this option is on or off; and the exact semantics are covered in more detail in the Operators chapter.


6.1.5 Floating point error checks

There are two non-finite states that can be produced by floating point operations: infinity and NaN (Not A Number). If floating point error checking is on, attempting to store or pass as an argument a non-finite floating point number causes a System.NotFiniteNumberException exception to be thrown. The compilation environment determines whether this option is on or off; the exact semantics are covered in the more detail in the Statements and Expressions chapters.


6.2 Import directives

Import directives import the names of entities into a source file, allowing the names to be referenced without qualification. All import directives must appear after any option directives but before any type declarations. The compilation environment may also define implicit import directives.

Import directives make names available in a source file, but do not declare anything in the global namespace's declaration space. The scope of the names imported by an import directive extends over the source file. The scope of an import directive specifically does not include other import directives, nor does it include other source files. Import directives may not refer to one another.

It is important to note that the namespace or type names that appear in import directives must always be fully qualified. That is, the leftmost identifier in a namespace or type name is always resolved in the global namespace and then resolution proceeds according to normal name resolution rules. This is the only place in the language where such a rule applies and it ensures that there is no way to make a name completely hidden from qualification. If this rule did not exist, once a name in the global namespace was hidden in a particular source file, it would be impossible to specify any names from that namespace in a qualified way.

ImportsDirective ::= Imports ImportsClauses LineTerminator
ImportsClauses ::=
ImportsClause |
ImportsClauses , ImportsClause
ImportsClause ::= ImportsAliasClause | ImportsNamespaceClause


6.2.1 Import aliases

An import alias defines an alias for a namespace or type. The identifier of a directive must be unique within the global namespace (not just the global namespace declaration in the source file in which the import alias is defined), even though it does not declare a name in the global namespace's declaration space. An import alias can create an alias for any namespace or type. Accessing a namespace or type through an alias yields exactly the same result as accessing the namespace or type through its declared name. Nested declarations may shadow the import alias name.

ImportsAliasClause ::= Identifier = NamespaceOrTypeName
NamespaceOrTypeName ::= NamespaceName | TypeName


6.2.2 Namespace imports

A namespace import imports all of the members of a namespace or type, enabling the identifier of each member to be used without qualification. It is illegal to import a type that intrinsically has no members .

Unlike an import alias, a namespace import has no restrictions on the names it imports and may import namespaces and types whose identifiers are already declared within the global namespace. The names imported by a namespace import are shadowed by import aliases and declarations in the global namespace. When more than one imported namespace contains members by the same name, a reference to that name is considered ambiguous and causes an error.

ImportsNamespaceClause ::= NamespaceOrTypeName


6.3 Namespaces

Visual Basic 7.0 programs are organized using namespaces. Namespaces are used both as an "internal" organization system for a program, and as an "external" organization system – a way of presenting program elements that are exposed to other programs. Import directives are provided to facilitate the use of namespaces.

Unlike the other kinds of entities, namespaces may be declared multiple times within the same program and may be declared across many programs, with each declaration contributing members to the same namespace. When dealing with the public members of a namespace, it is irrelevant to the language where a particular member was declared. If two programs define an entity with the same name in the same namespace, references to that name from a context where both are available are considered ambiguous and cause an error.

There is a global namespace which has no name and whose nested namespaces and types can always be accessed without qualification. The scope of a namespace member declared in the global namespace is the entire program text of each namespace. Otherwise, the scope of a type or namespace declared in a namespace whose fully qualified name is N is the program text of each namespace whose corresponding namespace's fully qualified name is N or whose fully qualified name begins with N.

NamespaceName ::= QualifiedIdentifier


6.3.1 Namespace declaration

A namespace declaration consists of the keyword Namespace, followed by a qualified identifier and optional namespace member declarations. If the namespace name is qualified, the namespace declaration is treated as if it was lexically nested within namespace declarations corresponding to each name in the qualified name.

Namespaces are implicitly public and the declaration of a namespace cannot include any access modifiers.

NamespaceDeclaration ::=
Namespace QualifiedIdentifier LineTerminator
[ NamespaceMemberDeclaration+ ]
End Namespace LineTerminator


6.3.2 Namespace members

Namespace members can only be namespace declarations and type declarations. Type declarations may have public, friend or private access. The default access for types is friend access. It is important to note that private members of a namespace are accessible only within the namespace declaration they were declared in.

NamespaceMemberDeclaration ::=
NamespaceDeclaration |
TypeDeclaration
TypeDeclaration ::=
ModuleDeclaration |
NonModuleDeclaration
NonModuleDeclarataion ::=
EnumDeclaration |
StructureDeclaration |
InterfaceDeclaration |
ClassDeclaration |
DelegateDeclarataion


7. Types

With one exception, types in Visual Basic 7.0 are divided into two categories: value types and reference types. Enumerated types, structure types, and all the primitive types are value types. Class types, interface types, array types, delegate types, and strings are reference types. The abstract root type Object, which is an alias for System.Object, is special in that it is neither specifically a reference type nor a value type. Thus, a variable of type Object can either contain a value type or a reference type.

TypeName ::= ValueTypeName | ReferenceTypeName | ObjectTypeName | ModuleTypeName
ObjectTypeName ::= QualifiedIdentfier | Object
ValueTypeName ::= PrimitiveTypeName | StructureTypeName | EnumTypeName
ReferenceTypeName ::=
ClassTypeName |
|
InterfaceTypeName |
DelegateTypeName |
ArrayTypeName


7.1 Value and reference types

Although value types and reference types can be extremely similar in terms of declaration syntax, the semantics of the two kinds of types are very distinct.

Reference types are always stored on the NGWS Runtime managed heap, and may only be accessed through a reference. This allows the NGWS Runtime garbage collector to track outstanding references to a particular instance and free the instance once no more references remain. Thus, a variable of reference type always contains a reference to a value of that type. Assignment to a variable of a reference type creates a copy of the reference, not a copy of the value being referenced.

Value types are normally stored directly on the stack, within an array or within another type. When the location containing a value type instance is destroyed, the value type instance is destroyed. Value types are always accessed directly and it is not possible to create a reference to a value type. This ensures that it is not possible to refer to a value class instance that has already been freed. A variable of a value type always contains a value of that type. Unlike reference types, it is not possible for a value of a value type to be Nothing or to reference an object of a more derived type. Assignment to a variable of a value type creates a copy of the value being assigned.


7.2 Primitive types

The primitive types are identified through keywords, which are primitive for predefined structure types in the System namespace. An primitive type and the structure type it aliases are completely indistinguishable. In other words, writing the reserved word Byte is exactly the same as writing System.Byte.

Because aprimitive type aliases a structure type, every primitive type has members. For example, Integer has the members declared in System.Int32. Literals can be treated as instances of their corresponding types.

The primitive types differ from other structure types in that they permit certain additional operations:

  • Most primitive types permit values to be created by writing literals. For example, 123I is a literal of type Integer.
  • When the operands of an expression are all primitive type constants, it is possible for the compiler to evaluate the expression at compile time. Such an expression is known as a constant expression.
  • It is possible to declare constants of the primitive types.

Visual Basic 7.0 defines the following primitive types:

  • The integral value types Byte (1-byte unsigned integer), Short (2-byte signed integer), Integer (4-byte signed integer), and Long (8-byte signed integer). These types map to System.Byte, System.Int16, System.Int32, and System.Int64, respectively. The default value of an integral type is equivalent to the literal 0.
  • The floating-point value types Single (4-byte floating point) and Double (8-byte floating point). These types map to System.Single and System.Double, respectively. The default value of a floating-point type is equivalent to the literal 0.0.
  • The Decimal type (12-byte decimal value), which maps to System.Decimal. The default value of decimal is equivalent to the literal 0@.
  • The Boolean data type, which represents a truth-value, typically the result of a relational or logical operation. The literal is of type System.Boolean. The default value of the Boolean type is equivalent to the literal False.
  • The Date data type, which represents a date and/or a time and maps to System.DateTime. The default value of the Date type is equivalent to the literal # 01/01/0001 12:00:00AM #
  • The Char data type, which represents a single Unicode character and maps to System.Char. The default value of the Char type is equivalent to the literal ""C.

It is important note is that signed bytes and unsigned integral types are not supported in Visual Basic 7.0. As a result, there are four value types in the type system that are illegal to use in a program: System.SByte, System.UInt16, System.UInt32 and System.UInt64. Any reference to these types will generate an error.

PrimitiveTypeName ::= NumericTypeName | Boolean | Date | Char
NumericTypeName ::= IntegralTypeName | FloatingPointTypeName | Decimal
IntegralTypeName ::= Byte | Short | Integer | Long
FloatingPointTypeName ::= Single | Double


7.2.1 Decimal

Decimal is an 12-byte data type suitable for financial and monetary calculations. The decimal type can represent values ranging from 1.0 × 10-28 to approximately 7.9 × 1028 with 28-29 significant digits. The finite set of values of type decimal are of the form s × m × 10e, where s is 1 or –1, 0 = m < 296, and -28 = e = 0. A decimal is represented as a 6-byte integer scaled by a power of ten.

Operations on values of type decimal are exact to 28 or 29 digits, but to no more than 28 decimal places. Results are rounded to the nearest representable value, and, when a result is equally close to two representable values, to the value that has an even number in the least significant digit position.


7.3 Enumerations

Enumerations are types that give symbolic representation to a set of values of one of the primitive integral types. Enumerations are generally treated as distinct types. For an enumeration type E, the default value is the value produced by the expression Convert(0, E).

The underlying type of an enumeration must be an integral type that can represent all the enumerator values defined in the enumeration. If an underlying type is specified, it must be Byte, Short, Integer or Long. If no underlying type is explicitly specified, the underlying type is Integer.

EnumTypeName ::= QualifiedIdentifier
EnumDeclaration ::=
[ EnumModifier+ ] Enum [ Attributes ] Identifier [ As IntegralTypeName ] LineTerminator
EnumMemberDeclaration+
End Enum LineTerminator
EnumModifier ::= AccessModifier | ShadowsModifier


7.3.1 Enumeration members

The members of an enumeration are the enumerated values declared in the enumeration and the members inherited from class System.Enum.

The scope of an enumeration member is from the textual position of its declaration to the end of the enumeration declaration body. This means that outside of an enumeration declaration, an enumeration member must always be qualified (unless the type is specifically imported into a namespace through a namespace import).

Declaration order for enumeration member declarations is significant when constant expression values are omitted. Enumeration members implicitly have public access; no access modifiers are allowed on enumeration member declarations.

EnumMemberName ::= QualifiedIdentifier
EnumMemberDeclaration ::= [ Attributes ] Identifier [ = ConstantExpression ] LineTerminator


7.3.2 Enumeration values

The identifiers in an enumeration member list are declared as constants, and can appear wherever constants are required. An enumeration member definition with "=" gives the associated enumeration member the value indicated by the constant expression. The constant expression must evaluate to an integral type and must be within the range of values that can be represented by the underlying type. The constant expression may not directly or indirectly use the value of its own associated enumeration member (that is, circularity in the constant expression is not allowed). Because the scope of a member only begins at the point of declaration, a constant expression may not reference members that occur textually later in the declaration.

If the first enumerator has no initializer, the value of the corresponding constant is zero. An enumeration member definition without an initializer gives the enumerator the value obtained by increasing the value of the previous enumeration member by one. This increased value must be within the range of values that can be represented by the underlying type.


7.4 Structures

Structure types are value types. A structure is implicitly final and inherits from System.ValueType.

StructureTypeName ::= QualifiedIdentifier
StructDeclaration ::=
[ StructModifier+ ] Structure [ Attributes ] Identifier LineTerminator
[ TypeImplementsClause+ ]
[ StructMemberDeclaration+ ]
End Structure LineTerminator
StructureModifier ::= AccessModifier | ShadowsModifier


7.4.1 Structure interface implementations

A structure declaration may declare that it implements a set of interface types through one or more Implements clauses. All the types specified in the Implements clause must be interfaces, and all members of the interfaces must be implemented by the structure. Declaring that a structure implements an interface in and of itself does not declare anything in the declaration space of the structure. Thus, it is perfectly legal to implement two interfaces with a method by the same name.

TypeImplementsClause ::= Implements Implements LineTerminator
Implements ::=
InterfaceTypeName |
Implements , InterfaceTypeName


7.4.2 Structure members

The members of a structure consist of the members introduced by its structure member declarations and the members inherited from System.ValueType.

Every structure implicitly has a public parameterless instance constructor that produces the default value of the structure. As a result, it is not possible for a structure type declaration to declare a parameterless instance constructor. A structure type is, however, permitted to declare parameterized instance constructors.

A structure member declaration may have public, friend, or private access. When a structure member declaration does not include an access modifier, the declaration defaults to public access. The scope of a member declared by a structure is the structure body in which the declaration occurs.

StructMemberDeclaration ::=
NonModuleDeclarataion
DataMemberDeclaration |
ConstantMemberDeclaration |
EventMemberDeclaration |
MethodMemberDeclaration |
PropertyMemberDeclaration |
SharedConstructorDeclaration


7.5 Classes

Classes are reference types. There is one special class that is referenced by a keyword, String. String is an alias for System.String, which represents a sequence of Unicode characters.

ClassTypeName ::= QualifiedIdentifier | String
ClassDeclaration ::=
[ ClassModifier+ ] Class [ Attributes ] Identifier LineTerminator
[ ClassBase ]
[ TypeImplementsClause+ ]
[ ClassMemberDeclaration+ ]
End Class LineTerminator


7.5.1 Class modifiers

There are two special modifiers on a class, MustInherit and NotInheritable. It is illegal to specify them both. The MustInherit modifier indicates that the class is abstract, while the NotInheritable modifier indicates that the class is final.

ClassModifier ::= AccessModifier | ShadowsModifier | MustInherit | NotInheritable


7.5.2 Class base specification

A class declaration may include a class base specification that defines the direct base class of the class. If a class declaration has no explicit class base, the direct base class is implicitly Object.

Every class has exactly one direct base class, and no circularity in derivation is permitted. It is not possible to derive from a final class, and the accessibility domain of the base class must be the same as or a superset of the accessibility domain of the class itself.

ClassBase ::= Inherits ClassTypeName LineTerminator


7.5.3 Class interface implementations

A class declaration may declare that it implements a set of interface types through one or more Implements clauses. All the types specified in the Implements clause must be interfaces, and the class must implement all members of the interfaces.

Declaring that a class implements an interface in and of itself does not declare anything in the declaration space of the class. Thus, it is perfectly legal to implement two interfaces with a method by the same name.


7.5.4 Class members

The members of a class consist of the members introduced by its class member declarations and the members inherited from its direct base class.

A class member declaration may have public, protected, friend, protected friend or private access. It is an error to specify protected access in a final class. When a class member declaration does not include an access modifier, the declaration defaults to public access, unless it is a data member, which defaults to private access.

The scope of a class member is the class body in which the declaration occurs. If the member has friend access, its scope extends to the class body of any derived class in the same program, and if the member has public, protected, or protected friend access, its scope extends to the class body of any derived class in any program.

ClassMemberDeclaration ::=
NonModuleDeclarataion |
EventMemberDeclaration |
DataMemberDeclaration |
ConstantMemberDeclaration |
MethodMemberDeclaration |
PropertyMemberDeclaration |
ConstructorMemberDeclaration


7.6 Standard Modules

A standard module is an uninstantiable non-inheritable type whose members are implicitly shared and scoped to the declaration space of the standard module's containing namespace, rather than just to the standard module declaration itself. A member of a standard module has two fully qualified names – one without the standard module name in it, and one with the standard module name in it. More than one standard module in a namespace may define a member with a particular name; unqualified references to the name outside of either module are ambiguous. A module may only be declared in a namespace and may not be nested in another type. It is illegal to declare a variable of a standard module type. Standard modules may not implement interfaces, and have only shared constructors.

ModuleTypeName ::= QualifiedIdentifier
ModuleDeclaration ::=
[ ModuleModifier+ ] Module [ Attributes ] Identifier LineTerminator
 [ ModuleMemberDeclaration+ ]
End Module LineTerminator
ModuleModifier ::= AccessModifier | ShadowsModifier


7.6.1 Standard module members

The members of a standard module consist of the members introduced by its member declarations and the members inherited from Object. Standard modules may have any type of member except instance constructors. All standard module type members are implicitly shared.

A standard module member declaration may have public, friend, or private access. When a standard module member declaration does not include an access modifier, the declaration defaults to public access, unless it is a data member, which defaults to private access. As previously noted, the scope of a standard module member is the declaration containing the standard module declaration. Members inherited from Object are not included in this special scoping; those members have no scope and must always be qualified with the name of the module. If the member has friend access, its scope extends only to namespace members declared in the same program.

ModuleMemberDeclaration ::=
NonModuleDeclarataion |
DataMemberDeclaration |
ConstantMemberDeclaration |
EventMemberDeclaration |
MethodMemberDeclaration |
PropertyMemberDeclaration |
 SharedConstructorDeclaration


7.7 Interfaces

Interfaces are abstract reference types that other types implement to guarantee that they support certain operations. An interface is never directly created and has no actual representation – other types must be converted to an interface type.

InterfaceTypeName ::= QualifiedIdentifier
InterfaceDeclaration ::=
[ InterfaceModifier+ ] Interface [ Attributes ] Identifier LineTerminator
[ InterfaceBases+ ]
[ InterfaceMemberDeclaration+ ]
End Interface LineTerminator
InterfaceModifier ::= AccessModifier | ShadowsModifier


7.7.1 Interface inheritance

The base interfaces of an interface are the explicit base interfaces and their base interfaces. In other words, the set of base interfaces is the complete transitive closure of the explicit base interfaces, their explicit base interfaces, and so on. If an interface declaration has no explicit interface base, the direct base interface is implicitly Object.

If an interface appears more than once in the transitive closure of the base interfaces, it only contributes its members to the derived interface once. A type implementing the derived interface only has to implement the methods of the multiply defined base interface once.

The accessibility domain of a base interface must be the same as or a superset of the accessibility domain of the interface itself.

InterfaceBase ::= Inherits InterfaceBases LineTerminator
InterfaceBases ::=
InterfaceTypeName
InterfaceBases , InterfaceTypeName


7.7.2 Interface members

The members of an interface consist of the members introduced by its member declarations and the members inherited from its base interfaces.

Only methods, properties and events may be members of an interface, and they must be abstract. Interface members are implicitly public and may not specify an access modifier. Interface members have no scope, and they must always be qualified.

InterfaceMemberDeclaration ::=
EventMemberDeclaration |
MethodMemberDeclaration |
PropertyMemberDeclaration


7.8 Arrays

An array is a reference type that contains variables accessed through computed indices. The variables contained in an array, also called the elements of the array, are all of the same type, and this type is called the element type of the array. The elements of an array come into existence when an array instance is created, and cease to exist when the array instance is destroyed. Each element of an array is initialized to the default value of its type. The type System.Array is the abstract base type of all array types. Every array type inherits the members declared by the System.Array type and is convertible to it (and Object).

An array has a rank that determines the number of indices associated with each array element. The rank of an array is also referred to as the number of dimensions of the array. An array with a rank of one is called a single-dimensional array, and an array with a rank greater than one is called a multi-dimensional array.

Each dimension of an array has an associated length. The dimension lengths are not part of the type of the array, but rather are established when an instance of the array type is created at runtime. The length of a dimension determines the valid range of indices for that dimension: for a dimension of length N, indices can range from 0 to N – 1, inclusive. If a dimension is of length zero, then there are no valid indices for that dimension. The total number of elements in an array is the product of the lengths of each dimension in the array. If one or more of the dimensions of an array have a length of zero, the array is said to be empty. The element type of an array can be any type except an array type.

Array types are specified by adding a modifier to an existing type name. The modifier consists of a left parenthesis, a set of zero or more commas, and a close parenthesis. The type modified is the element type of the array, and the number of dimensions is the number of commas, plus one. A variable may also be declared to be of an array type by putting an array type modifier or an array initialization modifier on the variable name. In that case, the array element type is the type given in the declaration, and the array dimensions are determined by the variable name modifier. Since an array may not have an array type as its element type, it is not legal to have an array type modifier on both a variable name and a type name in the same declaration.

ArrayTypeName ::= TypeName ArrayTypeModifier
ArrayTypeModifier ::= ( [ RankList ] )
RankList ::=
, |
RankList ,
ArrayNameModifier ::= ArrayTypeModifier | ArrayInitializationModifier


7.9 Delegates

A delegate is a reference type that refers to a shared method of a type or to an instance method of an object. The closest equivalent of a delegate in other languages is a function pointer, but whereas a function pointer can only reference shared functions, a delegate can reference both shared and instance methods. In the latter case, the delegate stores not only a reference to the method's entry point, but also a reference to the object instance with which to invoke the method.

Any attributes specified in the method declaration apply to the delegate itself. The method declaration may not have a body or an End construct. The accessibility domain of the return type and parameter types must be the same as or a superset of the accessibility domain of the delegate itself.

The members of a delegate are the members inherited from class System.Delegate. A delegate also contains a set of constructors and methods defined by the system. As these are specified and implemented by the NGWS Runtime, they are not listed here.

DelegateTypeName ::= QualifiedIdentifier
DelegateTypeDeclaration ::=
[ DelegateModifier+ ] Delegate ProcedureDeclaration
DelegateModifier ::= AccessModifier | ShadowsModifier


8. Type Members

Type members can be methods, constructors, events, constants, data members and properties.

MemberName ::=
EnumMemberName |
MethodMemberName |
EventMemberName |
ConstantMemberName |
Data memberMemberName |
PropertyMemberName


8.1 Methods

Methods contain the executable statements of a program.

MethodMemberName ::= QualifiedIdentifier
MethodMemberDeclaration ::= MethodDeclaration | ExternalMethodDeclaration


8.1.1 Regular method declarations

There are two types of methods: subroutines, which do not return values, and functions, which do. The body and End construct of a method may only be omitted if the method is abstract. If no return type is specified on a function, it is implicitly Object. The accessibility domain of the return type and parameter types of a method must be the same as or a superset of the accessibility domain of the method itself.

ProcedureDeclaration ::= SubDeclaration | FunctionDeclaration
SubDeclaration ::=
[ ProcedureModifier+ ] Sub [ Attributes ] Identifier [ ( [ FormalParameterList ] ) ]
[ HandlesOrImplements ] LineTerminator
[ Block ]
[ End Sub LineTerminator ]
FunctionDeclaration ::=
[ ProcedureModifier+ ] Function [ Attributes ] Identifier [ ( [ FormalParameterList ] ) ]
[ As TypeName ] [ HandlesOrImplements ] LineTerminator
[ Block ]
[ End Function LineTerminator ]
ProcedureModifier ::=
AccessModifier |
ShadowsModifier |
Shared |
Overridable |
NotOverridable |
MustOverride |
Overrides |
Overloads
HandlesOrImplements ::= HandlesClause | MethodImplementsClause


8.1.2 External method declarations

An external method declaration introduces a new method whose implementation is provided external to the program. Because an external method declaration provides no actual implementation, it has no method body or End construct. External methods are implicitly shared and may not handle events or implement interface members. If no return type is specified on a function, it is implicitly Object. The accessibility domain of the return type and parameters types of an external method must be the same as or a superset of the accessibility domain of the external method itself.

The library clause of an external method declaration specifies the name of the external file that implements the method. The optional alias clause is a string that specifies the ordinal or name of the method in the external file. A single character set modifier may also be specified, which governs the character set used to marshal strings during a call to the external method. Unicode marshals all strings to Unicode values, Ansi marshals all strings to ANSI values, Auto marshals the strings according to the NGWS Runtime rules based on the name of the method (or the alias name, if specified). If no modifier is specified, Auto is assumed.

ExternalMethodDeclaration ::= ExternalSubDeclaration | ExternalFunctionDeclaration
ExternalSubDeclaration ::=
[ ExternalMethodModifier+ ] Declare [ CharsetModifier ] Sub [ Attributes ] Identifier
LibraryClause [ AliasClause ] [ ( [ FormalParameterList ] ) ] LineTerminator
ExternalFunctionDeclaration ::=
[ ExternalMethodModifier+ ] Declare [ CharsetModifier ] Function [ Attributes ] Identifier
LibraryClause [ AliasClause ] [ ( [ FormalParameterList ] ) ] [ As TypeName ]
LineTerminator
ExternalMethodModifier ::=
AccessModifier |
ShadowsModifier |
Overloads
CharsetModifier ::= Ansi | Unicode | Auto
LibraryClause ::= Lib StringLiteral
AliasClause ::= Alias StringLiteral


8.1.3 Method modifiers

Method modifiers are used in the following ways:

  • The Shared modifier indicates the method is a shared method. A shared method does not operate on a specific instance of a type. Other than within standard modules, a method declared without a Shared modifier is called an instance method. An instance method operates on a given instance of a type. A shared method may not be overridable and may not specify Overridable, NotOverridable, MustOverride or Overrides.
  • The Overridable modifier indicates the method is overridable. A overridable method may not specify Shared, or NotOverridable and may not be combined with MustOverride or Overrides (which both imply Overridable). Methods in final classes may not be declared overridable and overridable functions may not be Private.
  • The NotOverridable modifier indicates a method is final. A method that specifies NotOverridable must also specify Overrides and may not specify Shared, Overridable or MustOverride. Final methods may not be Private (it is redundant).
  • The MustOverride modifier indicates the method is abstract. An abstract method may not include a method body or an End construct, may not override another method and may only appear in an abstract type. An abstract method may not specify Shared, Overridable, NotOverridable or Overrides. Abstract methods may not be Private.
  • The Overrides modifier indicates a method overrides a base type overridable method with the same signature. An overriding method may not specify Shadows, Shared, Overridable or MustOverride. If there is no matching method to override, an error occurs.
  • The Overloads modifier indicates a method overloads another method in the type. The signature of the method must be unique amongst the set of overloaded methods, else there is an error.

The only modifier that a method declared in a standard module may specify is Overloads.


8.1.4 Method parameters

The parameters of a method, if any, are declared by the method's formal parameter list. The formal parameter list consists of zero or more formal parameters, separated by commas. If no type is specified, it is implicitly Object. However, if one parameter includes an As clause, all parameters must specify them.. A parameter which does not specify either ByRef or ByVal defaults to ByVal.

Formal parameter names are scoped to the entire body of the method and are always publicly accessible. A method invocation creates a copy, specific to that invocation, of the formal parameters, and the argument list of the invocation assigns values or variable references to the newly created formal parameters.

FormalParameterList ::=
FormalParameter |
FormalParameterList , FormalParameter
FormalParameter ::=
ParameterModifier+ [ Attributes ] Identifier [ As TypeName ] [ = ConstantExpression ]
ParameterModifier ::= ByRef | ByVal | Optional | ParamArray


8.1.4.1 Value parameters

A parameter declared with an explicit ByVal modifier is a value parameter. If the ByVal modifier is used, the ByRef modifier may not be specified. A value parameter comes into existence upon invocation of the member to which the parameter belongs, and is initialized with the value of the argument given in the invocation. A value parameter ceases to exist upon return of the member.

A method is permitted to assign new values to a value parameter. Such assignments only affect the local storage location represented by the value parameter — they have no effect on the actual argument given in the method invocation.


8.1.4.2 Reference parameters

A parameter declared with a ByRef modifier is a reference parameter. If the ByRef modifier is specified, the ByVal modifier may not be used. A reference parameter does not create a new storage location. Instead, a reference parameter represents the variable given as the argument in the method or constructor invocation. Conceptually, the value of a reference parameter is always the same as the underlying variable.

It is important to note that Visual Basic 7.0 may use copy-in/copy-out semantics when passing a variable to a reference parameter. In general, this happens when there is either no storage location to pass a reference to (for example, the argument is a property), or when the type of a storage location is not the same as the parameter type (for example, passing an instance of a base class to a byref derived class parameter). Thus, a reference parameter may not necessarily contain a reference to the exact storage of the variable, and any changes to the reference parameter may not be reflected in the variable until the method exits.


8.1.4.3 Optional parameters

A parameter declared with an Optional modifier is an optional parameter. All arguments that textually follow an optional parameter in the formal parameter list must be optional as well. An optional parameter must specify a constant expression to be used as a replacement value if no argument is specified. This is the only situation in which an initializer on a parameter is legal. The initialization is always done as a part of the invocation expression, not within the method body itself.


8.1.4.4 Paramarray parameters

A parameter declared with a ParamArray modifier is a paramarray parameter. If the ParamArray modifier is present, the ByVal modifier must be specified and no other parameter may use the ParamArray modifier. A paramarray parameter's type must be a single-dimensional array and it must be the last parameter in the formal parameter list.

A paramarray parameter represents an indeterminate number of formal parameters of the type of the paramarray. If the type of the paramarray is Object, then each of these pseudo-parameters is optional with a default value of Nothing. Within the method itself, a paramarray parameter is treated as its declared type and has no special semantics. A paramarray parameter is implicitly optional with a default value of Nothing.


8.1.4.5 External procedure parameters

The parameters of an external procedure are marshaled out of the NGWS Runtime using the default NGWS Runtime data type marshalling rules, with one exception. Value String parameters are by default marshaled to the Automation BSTR type rather than a LPSTR. Also, the value is marshaled by reference, so changes to the string in the external procedure are reflected in the argument passed, even though the parameter is declared as being a value parameter. Reference String parameters are marshaled to a pointer to a Automation BSTR rather than a pointer to a LPSTR.


8.1.5 Interface implementation

Methods can implement interface methods. To implement an interface method, a method declaration specifies the Implements keyword and references the name of the interface member. The method is implicitly final unless it is declared to be abstract or overridable. It is an error for a member implementing an interface member to be shared. A method's accessibility has no effect on its ability to implement methods. Like a non-abstract type, an abstract type must provide implementations of all members of the interfaces that are listed in the base type list of the type, but these methods may be abstract.

For an interface implementation to be valid, the containing type must name an interface in its implements list that contains a member whose fully qualified name, type, and parameter types exactly match those of the interface member implementation. A single member can implement multiple matching interface members.

The name of an interface member in the implements list must include a reference to the name of an interface in the implements list. The only exception is if the implemented method is unavailable all of the interfaces in the implements list because of multiple inheritance. In this case the implementing method must explicitly reference a base interface the method is available in, not the derived interface. That is to say, if I1 and I2 contain a member M, and I3 inherits from I1 and I2, then a type implementing I3 will implement I1.M and I2.M. If an interface shadows multiply inherited members, then an implementing type will have to implement the inherited members and the member(s) shadowing them.

MethodImplementsClause ::= [ Implements MethodMemberNameList ]
MethodMemberNameList ::=
MethodMemberName |
MethodMemberNameList , MethodMemberName


8.1.6 Event handling

Methods can declaratively handle events raised by objects in non-shared data members. To handle an event, a method declaration specifies the Handles keyword and references the name of the event. The name of the event must be the name of an event member of a non-shared data member in the method's containing type, although the event itself may be shared. A method's accessibility has no effect on its ability to handle events.

For a handler to be valid, the handled event's parameter types must exactly match those of the event handler. A single member can handle multiple matching events. The data member that raises the event must be declared with the WithEvents modifier, otherwise an error results.

A type inherits all event handlers provided by its base type. A derived type cannot in any way alter the event mappings it inherits from its base types, but when an event method is handled by a overridable method, it is possible for derived types to override the overridable method and alter the handling of the event. Also note that if a type does not handle events raised by a WithEvents data member, then it is not possible for any derived class to handle the event.

HandlesClause ::= [ Handles EventMemberNameList ]
EventMemberNameList ::=
EventMemberName |
EventMemberNameList , EventMemberName


8.1.6.1 Events in sub-objects

Methods may also handle events on objects contained within WithEvents data members. If a data member's type contains a parameterless read-only property marked with the System.ComponentModel.PersistContentsAttribute attribute, then the property may be referenced in a Handles clause.


8.1.7 Flow of execution

Execution of a program begins in a shared method determined by the compilation environment. When the method terminates, the program terminates.

A method is executed by first initializing all of its parameter and locals to their correct values. After parameter and local initialization has been done, the method body block is executed. Once the method block has been executed, execution returns to the caller of the method.


8.2 Constructors

Constructors are special methods that are run after the program begins or when an instance of a type is created and allow control over initialization. Unlike other members, constructors are not inherited and do not introduce a name into a type's declaration space. Constructors may only be invoked by object creation expressions or by the NGWS Runtime; they may never be directly invoked.

ConstructorMemberDeclaration ::= InstanceConstructorDeclaration | SharedConstructorDeclaration


8.2.1 Instance Constructors

Instance constructors initialize instances of a type and are run by the runtime environment when an instance is created. The formal parameter list of a constructor is subject to the same rules as the formal parameter list of a method. Constructors may be overloaded using the Overloads keyword.

All constructors (except for the constructors of type Object) must explicitly invoke another constructor as the first statement in the constructor method body. The statement can either invoke another of the type's instance constructors (that is, Me.New(…)), or it may invoke an instance constructor of the type's base type (that is, MyBase.New(…)). It is illegal for a constructor to invoke itself.

When a constructor's first statement is of the form MyBase.New(…), the constructor implicitly performs the initializations specified by the variable initializers of the instance data members declared in the type. This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor and before the invocation of the direct base type constructor. The variable initializers are executed in the textual order they appear in the type declaration.

When a type declares only private constructors it is not possible for other types to derive from the type or create instances of the type (an exception being types nested within the type). Private constructors are commonly used in types that contain only shared members.

If a type contains no instance constructor declarations, a default constructor is automatically provided. The default constructor simply invokes the parameterless constructor of the direct base type. If the direct base type does not have an accessible parameterless constructor, an error occurs.

InstanceConstructorDeclaration ::=
[ InstanceConstructorModifier+ ] Sub [ Attributes ] New
  [ ( [ FormalParameterList ] ) ] LineTerminator
[ Block ]
End Sub LineTerminator
InstanceConstructorModifier ::= AccessModifier | Overloads


8.2.2 Shared constructors

Shared constructors initialize a type's shared data members and are run after the program begins executing, but before any reference to any member of the type. Shared constructors do not overload instance constructors, and may not be overloaded themselves.

Unlike instance constructors, shared constructors are implicitly public, have no parameters and may not call other constructors. Before the first statement in a shared constructor, the shared constructor implicitly performs the initializations specified by the variable initializers of the shared data members declared in the type. This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor. The variable initializers are executed in the textual order they appear in the type declaration.

SharedConstructorDeclaration ::=
Shared Sub [ Attributes ] New [ ( ) ] LineTerminator
[ Block ]
End Sub LineTerminator


8.3 Events

Events are declared using event declarations. An event declaration consists of either an identifier and a delegate type or a method declaration. The method declaration, if specified, must be a subroutine (that is, no return type) and must not have a body or an End construct. Attributes specified on the method declaration apply to the event itself. If a delegate type is specified, the delegate type may not have a return type. The accessibility domain of the parameter types must be the same as or a superset of the accessibility domain of the event itself.

In addition to the member name added to the type's declaration space, an event declaration implicitly declares several other members. Given an event named E, the following members are added to the declaration space:

  • If the form of the declaration is a method declaration, a nested delegate class named EEventHandler is introduced whose declaration matches the method declaration and which has the same accessibility as the event.
  • A private instance data member typed as the delegate, named EEvent.
  • A method named add_E, which takes the delegate type and has the same accessibility as the event.
  • A method named remove_E, which takes the delegate type and has the same accessibility as the event.
  • A method named raise_E, which takes the delegate type and has the same accessibility as the event.

If a type attempts to declare a name that matches one of the above names, an error will result. It is not possible to override or overload any of the introduced members, although it is possible to shadow them in derived types. Events may be shared.

EventMemberName ::= QualifiedIdentifier
EventMemberDeclaration ::=
[ EventModifiers+ ] Event EventOrDelegate [ EventImplementsClause ] LineTerminator
EventOrDelegate ::=
[ Attributes ] Identifier [ ( [ FormalParameterList ] ) ] |
[ Attributes ] Identifier As DelegateTypeName
EventModifiers ::= AccessModifiers | ShadowsModifier | Shared


8.3.1 Interface event implementation

Events can implement interface events. To implement an interface event, an event declaration specifies the Implements keyword and references the name of the interface event. It is an error for a private event to implement an interface event in a non-final class.

For an interface implementation to be valid, the containing type must name an interface in its implements list that contains an event whose fully qualified name, type, and parameter types exactly match those of the interface event implementation. A single event can implement multiple matching interface events. The name of an interface event in the implements list must follow the same rules as a method's implements list.

EventImplementsClause ::= [ Implements EventMemberNameList ]
EventMemberNameList ::=
EventMemberName |
EventMemberNameList , EventMemberName


8.4 Constants

A constant is a constant value that is a member of a type. Constants are implicitly shared. If the declaration contains an As clause, then the clause specifies the type of the member introduced by the declaration; if the type is omitted, the type is implicitly the type of the constant expression. The accessibility domain of the type of the constant must be the same as or a superset of the accessibility domain of the constant itself. The constant expression must yield a value of the constant's type or of a type that is implicitly convertible to the constant's type. The constant expression may not be circular; that is, a constant may not be defined in terms of itself.

When a symbolic name for a constant value is desired, but the type of the value is not permitted in a constant declaration or when the value cannot be computed at compile time by a constant expression, a ReadOnly data member may be used instead.

ConstantMemberName ::= QualifiedIdentifier
ConstantMemberDeclaration ::=
[ ConstantModifier+ ] Const [ Attributes ] Identifier [ As TypeName ] =
ConstantExpression LineTerminator
ConstantModifier ::= AccessModifiers | ShadowsModifier


8.5 Data members

A data member is a variable that is a member of a type. The Dim modifier is equivalent to the default access modifier for the declaration and must be specified if no access modifier is specified. Each data member declarator introduces a new member. If an initializer is specified, only one data member may be declared by the data member declaration.

If the declarator contains an As clause, then the clause specifies the type of the members introduced by the declaration; if the type is omitted, the type of the members is implicitly Object. The accessibility domain of a data member's type or array element type must be the same as or a superset of the accessibility domain of the data member itself.

DataMemberName ::= QualifiedIdentifier
DataMemberDeclaration ::=
DataModifier+ DataMemberDeclarator LineTerminator
DataMemberModifier ::= AccessModifiers | ShadowsModifier | Shared | Dim
DataMemberDeclarator ::=
DataMemberIdentifiers [ As TypeName ]
DataMemberIdentifier [ As [ New ] TypeName [ ( FormalParameterList ) ] ] [ = VariableInitializer ]
DataMemberIdentifiers ::=
DataMemberIdentifier |
DataMemberIdentifiers , DataMemberIdentifier
DataMemberIdentifier ::= [ DataMemberType ] [ Attributes ] Identifier [ ArrayNameModifier ]
DataMemberType ::= ReadOnly | WithEvents


8.5.1 Shared data members

A data member declared with the Shared modifier is a shared data member. A shared data member identifies exactly one storage location. No matter how many instances of a type are created, there is only ever one copy of a shared data member. A shared data member comes into existence when a program begins executing, and ceases to exist when the program terminates. A shared data member is initialized to the default value of its type.

A data member declared without the Shared modifier is called an instance data member. Every instance of a class contains a separate copy of all instance data members of the class. An instance data member is initialized to the default value of its type. An instance data member of a reference type comes into existence when a new instance of that type is created, and ceases to exist when there are no references to that instance and the Finalize method has executed. An instance data member of a value type has exactly the same lifetime as the variable to which it belongs. In other words, when a variable of a value type comes into existence or ceases to exist, so do the instance data members of the value type.


8.5.2 Read-only data members

When a data member declaration includes a ReadOnly modifier, assignments to the data members introduced by the declaration may only occur as part of the declaration or in a constructor in the same class. Specifically, assignments to a read-only data member are permitted only in the following contexts:

  • In the data member declaration that introduces the data member (by including a variable initializer in the declaration).
  • For an instance data member, in the instance constructors of the class that contains the data member declaration, or for a shared data member, in the shared constructor of the class that contains the data member declaration.

A shared read-only data member is useful when a symbolic name for a constant value is desired, but when the type of the value is not permitted in a constant declaration or when the value cannot be computed at compile time by a constant expression.

Constants and read-only data members have different binary versioning semantics. When an expression references a constant, the value of the constant is obtained at compile time, but when an expression references a read-only data member, the value of the data member is not obtained until runtime.


8.5.3 WithEvents data members

A type can declare that it handles some set of events raised by one of its data members. It does so by declaring the data member that raises the events with the WithEvents modifier. This causes the data member to be renamed with a leading underscore and replaced with a property of the same name. If the data member's name is F, then it is renamed to _F and a property F is implicitly declared. If there is a collision between the data member's new name and another declaration, an error will be reported.

The implicit property takes care of hooking and unhooking the relevant event handlers. When a value is assigned to the data member, the property first calls the remove method for the event on the instance currently in the variable (unhooking the existing event handler, if any). Then the assignment is made, and the property calls the add method for the event on the new instance in the variable (hooking up the new event handler).

If a type declares a data member as WithEvents, all events raised by that data member must be handled within the type itself. It is not possible in a derived type to handle events not handled by a base type on an inherited WithEvents data member.


8.5.4 Variable initializers

Data member declarations may include variable initializers. For shared data members, variable initializers correspond to assignment statements that are executed after the program begins executing but before the shared data member is first referenced. For instance data members, variable initializers correspond to assignment statements that are executed when an instance of the class is created.

All data members are initialized to their default values, including data members that have variable initializers. Thus, when a program begins executing, all shared data members are first initialized to their default values before any shared data member initializers are executed. Likewise, when an instance of a class is created, all instance data members are first initialized to their default values, and then the instance data member initializers are executed. Each variable initializer must yield a value of the data member's type or of a type that is implicitly convertible to the data member's type. The variable initializer may be circular, even though such an initializer is of dubious value.

There are four forms of variable initializers: regular initializers, array element initializers, array size initializers and object initalizers. The first two forms appear after an equals sign that follows the type name, the latter two are part of the declaration itself. Only one form of initializer may be used on any particular declaration, with the exception that an array size initializer and an array element initializer may be used together.

VariableInitializer ::= RegularInitializer | ArrayElementInitializer


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

8.5.4.1 Regular initializers

A regular initializer is just an expression.

RegularInitializer ::= Expression


8.5.4.2 Array element initializers

An array initializer consists of a sequence of variable initializers, enclosed by curly brace tokens and separated by comma tokens. Each variable initializer is an expression or, in the case of a multi-dimensional array, a nested array initializer. Array element initializers may also be used in array creation expressions.

The context in which an array initializer is used determines the type of the array being initialized. In an array creation expression, the array type immediately precedes the initializer. In a data member or variable declaration, the array type is the type of the data member or variable being declared. When an array initializer is used in a data member or variable declaration it is simply shorthand for an equivalent array creation expression.

In an array initializer, the outermost nesting level corresponds to the leftmost dimension and the innermost nesting level corresponds to the rightmost dimension. The initializer must have as many levels of nesting as there are dimensions in the array. All of the elements in the innermost nesting level must be implicitly convertible to the element type of the array. The number of elements in each nested array initializer must always be consistent with the size of the other array initializers at the same level.

If the array creation expression specifies the bounds of the dimensions, then the number of elements at any particular level must be the same as the size of the corresponding dimension. If the bounds are unspecified, then the length of each dimension is the number of elements in the corresponding level of nesting.

An empty array initializer (that is,. one that contains curly braces but no initializer list) is always legal regardless of the number of dimensions of the array. If the size of the dimensions of the array being initialized is known, then the empty array initializer represents an array instance of the specified size where all the elements have been initialized to the element type's default value. If the dimensions of the array being initialized are not known, then the empty array initializer represents an array instance in which all dimensions are size zero.

At runtime, the expressions in an array initializer are evaluated in textual order from left to right.

ArrayElementInitializer ::= { [ VariableInitializerList ] }
VariableInitializerList ::=
VariableInitializer |
VariableInitializerList , VariableInitializer
VariableInitializer ::= Expression | ArrayElementInitializer


8.5.4.3 Array size initializers

An array size initializer is a modifier on the name of the variable that gives a set of bounds denoted by constant expressions. The set of bounds are equivalent to a variable initializer of an array creation expression with the given bounds. For example, "x(i, j) As T(,)" is equivalent to "x As T(,) = new T(i, j) {}". If an array element initializer is specified, each argument in the argument list must be a constant and the rank and dimension lengths specified by the expression list must match those of the array initializer.

If a variable declaration includes an array type modifier on its type and an array size initializer, the number of dimensions given in the two modifiers must match. If no array type modifier is used, then the number of dimensions of the array type is inferred from the array size initializer.

ArrayInitializationModifier ::= ( InitializationRankList )
InitializationRankList ::=
Expression |
InitializationRankList , Expression


8.5.4.4 Object initializers

An object initializer is specified using the New keyword before the type name and an optional formal parameter list after the type name. An object initializer is equivalent to a regular initializer of the form "= New T(A)", where T is the type name and A is the supplied formal parameter list, if any.


8.5.5 System.MarshalByRefObject classes

Classes that derive from the abstract class System.MarshalByRefObject are marshaled across NGWS Runtime context boundaries using proxies (that is, by reference) rather than through copying (that is, by value). This means that an instance of such a class may not be a true instance but instead may just be a stub that marshals data member accesses and method calls across a context boundary.

As a result, it is not possible to create a reference to the storage location of data members defined on such classes. This means that data members of classes derived from System.MarshalByRefObject can not be passed to reference parameters, and methods and data members of data members typed as value types may not be accessed. To mitigate these restrictions, Visual Basic 7.0 treats data members defined on such classes as if they were properties (since the restrictions are the same on properties).


8.6 Properties

Properties are a natural extension of data members — both are named members with associated types, and the syntax for accessing data members and properties is the same. However, unlike data members, properties do not denote storage locations. Instead, properties have accessors that specify the statements to execute in order to read or write their values.

If no type is specified, the type of a property is implicitly Object. A property declaration may contain either a getter, which retrieves the value of the property, a setter, which stores the value of the property, or both. Because a property implicitly declares methods, a property may be declared with the same modifiers as a method. If the property is abstract, the property body and the End statement must be omitted.

The index parameter list makes up the signature of the property, and so properties may be overloaded on index parameters but not on the type of the property. There is one special exception to this rule: because there may be ambiguity in an index expression between a parameterless property that returns an array (or a value with an indexed property) and an indexed property, it is not legal to overload a non-indexed property with an indexed property. The index parameter list is the same as for a regular method, with the exception that none of the parameters may be decorated with the ByRef modifier.

A property may be declared as follows:

  • If the property specifies no property type modifier, the property must have both a getter and a setter. The property is said to be a read-write property.
  • If the property specifies the ReadOnly modifier, the property must have a getter and may not have a setter. The property is said to be read-only property. It is an error for a read-only property to be the target of an assignment.
  • If the property specifies the WriteOnly modifier, the property must have a setter and may not have a getter. The property is said to be write-only property. Except as the target of an assignment, it is an error to reference a write-only property in an expression.

When a derived type shadows a property, the derived property hides the shadowed property with respect to both reading and writing. The accessibility domain of the return type or parameter types must be the same as or a superset of the accessibility domain of the property itself. A property may only have one setter and one getter.

PropertyMemberName ::= QualifiedIdentifier
PropertyMemberDeclaration ::=
PropertyModifier+ Property [ Attributes ] Identifier [ ( [ FormalParameterList ] ) ]
[ As TypeName ] [ MethodImplementsClause ] LineTerminator
PropertyAccessorDeclaration+
[ End Property LineTerminator ]
PropertyModifier ::= ProcedureModifier | Default | ReadOnly | WriteOnly
PropertyAccessorDeclaration ::= PropertyGetDeclaration | PropertySetDeclaration


8.6.1 Getter declarations

A getter is declared using a property get declaration. A property get declaration consists of the keyword Get followed by a block. Given a property named P, a getter declaration implicitly declares a method with the name get_P with the same modifiers, type and parameter list as the property. If the type contains a declaration with that name, an error results.

A special local is implicitly declared in the getter body's declaration space with the same name as the property representing the return value of the property. The local has special semantics when used in expressions: if the local is used in a non-variable expression, then the name will bind to the property rather than to the local. For example, given a property P, the expression P = 1 references the property return local, while x = P is a recursive load of P. When control flow leaves the getter body, the value of the local is passed back to the access expression.

PropertyGetDeclaration ::=
Get [ Attributes ] LineTerminator
[ Block ]
End Get


8.6.2 Setter declarations

A setter is declared using a property set declaration. A property set declaration consists of the keyword Set followed by a block. Given a property named P, a setter declaration implicitly declares a method with the name set_P with the same modifiers and parameter list as the property. If the type contains a declaration with that name, an error results.

A local variable named Value is implicitly declared within the block of a property set declaration. This variable represents the value being assigned to the property.

PropertySetDeclaration ::=
Set [ Attributes ] LineTerminator
[ Block ]
End Set


8.6.3 Default properties

A property that specifies the modifier Default is called a default property. Any type that allows properties may have a default property, including interfaces. Default properties have several restrictions:

  • A type may only contain one member that is a default property. This includes members inherited from a base type.
  • A property that has no indexers may not be a default property.
  • A default property may not be shared or private.
  • If a property specifies Default, then all properties overloaded on that name must also specify Default.

The default property may be referenced without having to qualify the instance with the name of the property. Thus I(A) is syntactically equivalent to I.P(A), where P is a default property of I that takes argument list A. This is covered in more detail in the Expressions chapter.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

9. Statements

Statements represent executable code.


9.1 Blocks

Statements are organized into blocks, which are made up of labeled lines. Each labeled line begins with an optional label declaration, followed by zero or more statements delimited by colons.

A method has a single declaration space for labels, and the scope of a label is the body of the method. Names referenced in GoTo statements are resolved in this space. The label declaration space is not nested in any other declaration space. Note that because both labels and statements are delimited with colons, it is possible for a label declaration to look like a statement; label declaration always takes precedence in any ambiguous situation. Labels may be either identifiers or integer literals.

Execution of a block begins with the first statement in the block. Once a statement has been executed, the next statement is lexical order is executed, unless a statement transfers execution elsewhere or an exception occurs.

Block ::= [ LabeledLine+ ]
LabeledLine ::= [ LabelName : ] [ Statements ] LineTerminator
LabelName ::= Identifier | IntLiteral
Statements ::=
[ Statement ] |
Statements [ Statement ]


9.1.1 Locals

Each block in a method creates a declaration space for local variables. Names are introduced into this declaration space through local variable declarations in the method body and the formal parameter list of the method, which introduces names into the outermost block's declaration space. Blocks do not allow shadowing of names through nesting – once a name has been declared in a block, the name may not redeclared in any nested blocks.

A method invocation creates a copy, specific to that invocation, of the local variables of the method. A local variable comes into existence when control enters the method body that contains the local variable declaration and ceases to exist when control leaves the method. All locals are initialized to their type's default value. Local variables are always publicly accessible. It is an error to refer to the local variable in a textual position that precedes its declaration.

When the method is a function, a special local is implicitly declared in the method body's declaration space with the same name as the method representing the return value of the function. The local has special semantics when used in expressions: if the local is used in a non-variable expression, then the name will bind to the function rather than to the local. For example, given a function F, the expression F = 1 references the function return local, while x = F(1) is a recursive call to F. The use of parenthesis can cause ambiguous situations (such as F(1) where F is a function whose return type is a one-dimensional array); in all ambiguous situations, the name binds to the function rather than the local. When control flow leaves the method body, the value of the local is passed back to the invocation expression. If the method is a subroutine, there is no such implicit local and control simply returns to the invocation expression.

If explicit local declaration is specified by the compilation environment or Option Explicit, then all local variables must be explicitly declared. Otherwise, local variables may be implicitly declared simply by using them in a statement, with the first textual appearance of the identifier considered its "declaration." The one exception to this rule is that local variables may not be explicitly declared in function invocation or indexing expressions. Implicitly declared locals are always scoped to the entire method body. In the case of implicit declaration, the type of the variable is Object if no type character was attached to the implicit declaration; otherwise the type of the variable is the type of the type character.


9.2 Statement categories

Statements are grouped into two general groups: "embeddable" statements and "non-embeddable" statements. Embeddable statements may be used in any context that requires a statement. A non-embeddable statement may not be used in contexts where a statement is contained within another statement (for example, the line If statement). The only non-embeddable statement is the local declaration statement.

Note that for the sake of readability, statement productions that involve multiple sub-statements will be treated as a single production, even though the sub-statements may each be contained by themselves on a labeled line.

Statement ::=
LocalDeclarationStatement |
EmbeddedStatement
EmbeddedStatement ::=
WithStatement |
SyncLockStatement |
EventStatement |
AssignmentStatement |
InvocationStatement |
ConditionalStatement |
LoopStatement |
ErrorHandlingStatement |
ControlFlowStatement |
ArrayHandlingStatement |
IOStatement
StatementTerminator ::= LineTerminator | :


9.3 Local declaration statement

A local declaration statement declares a new local variable. Its syntax is the same as a data member or constant declaration, with the exception that a local variable declaration must always specify a modifier.

There are three types of locals. Constant locals are equivalent to type member constants and are specified with the Const modifier. Regular locals are declared using the Dim modifier. Static locals are declared using the Static modifier. Static locals are locals that retain their value across invocations of the method. Static locals declared within non-shared methods are per-instance; each instance of the type that contains the method has its own copy of the static local. Static locals declared within shared methods are per-type; there is only one copy of the static local for all instances. It is not legal to put an initializer of any kind on a Static local.

Variable initializers on locals are equivalent to assignment statements placed at the textual location of the declaration. Thus, if execution branches over the local declaration, the variable initializer will not be executed. If the local declaration is executed more than once, then the variable initializer will be executed an equal number of times. It is important to note that locals are only initialized to their type's default value once, upon entry into the method. Initializers are not allowed on static locals.

Local variables are scoped to the statement block in which they are declared.

LocalDeclarationStatement ::= LocalModifier LocalDeclarator StatementTerminator
LocalModifier ::= Static | Dim | Const
LocalDeclarator ::=
LocalIdentifiers [ As TypeName ]
Identifier [ ArrayNameModifier ]
[ As [ New ] TypeName [ ( [ ArgumentList ] ) ] ] [ = VariableInitializer ]
LocalIdentifiers ::=
Identifier [ ArrayNameModifier ] |
LocalIdentifiers , Identifier [ ArrayNameModifier ]
LocalVariableName ::= Identifier


9.4 With statement

The With statement allows multiple references to an expression's members without having to specify the expression multiple times. The expression is evaluated once, upon entry to the block. Within the With statement block, an expression starting with a dot or an exclamation point is evaluated as if the expression preceded it.

WithStatement ::=
With Expression StatementTerminator
[ Block ]
End With StatementTerminator


9.5 SyncLock statement

The SyncLock statement is a statement that allows statements to be synchronized on an expression. This ensures that multiple threads of execution do not execute the same statements at the same time. The expression is evaluated once, upon entry to the block. When entering the SyncLock block, the shared method System.CriticalSection.Enter is called on the specified expression, which blocks until the thread of execution has an exclusive lock on the object returned by the expression. The type of the expression in a SyncLock statement must be a reference type.

The SyncLock block is implicitly contained by a Try statement whose finally block calls the shared method System.CriticalSection.Exit on the expression. This ensures the lock is freed even when an exception is thrown.

SyncLockStatement ::=
SyncLock Expression StatementTerminator
[ Block ]
End SyncLock StatementTerminator


9.6 Event statements

Event statements enable raising events and doing dynamic event handling.

EventStatement ::=
RaiseEventStatement |
AddHandlerStatement |
RemoveHandlerStatement


9.6.1 RaiseEvent statement

The RaiseEvent statement notifies event handlers that a particular event has occurred. The argument to a RaiseEvent statement must be a member event of the type that contains the method raising the event. If the event takes arguments, they must be specified. If there are no arguments, the parenthesis may be omitted.

The RaiseEvent statement is processed as a call to the Invoke method of the event's delegate using the supplied parameters, if any.

RaiseEventStatement ::= RaiseEvent EventMemberName
[ ( [ ArgumentList ] ) ] StatementTerminator


9.6.2 AddHandler and RemoveHandler statements

Although most event handlers are automatically hooked up through WithEvents data members, it may be necessary to dynamically add and remove event handlers at runtime. The AddHandler and RemoveHandler statements do this.

Each statement takes two parameters: an event expression and an expression that must evaluate to a delegate instance of the appropriate type for the event hookup. Given an event E, the statement either calls the relevant add_E or remove_E method on the instance to add or remove the delegate as a handler for the event. The parameters are always evaluated left to right at runtime.

AddHandlerStatement ::= AddHandler HandlerArguments StatementTerminator
RemoveHandlerStatement ::= RemoveHandler HandlerArguments StatementTerminator
HandlerArguments ::= EventExpression , ArgumentExpression


9.7 Assignment statements

An assignment statement assigns the value of an expression to a variable. In general, if the variable being assigned to is a property, the property must be read-write or write-only, otherwise there is an error. If the variable is a read-only data member, the assignment must take place in a constructor appropriate for the type of the data member (that is, shared or not shared), otherwise there is an error.

AssignmentStatement ::=
SimpleAssignmentStatement |
DelegateAssignmentStatement |
CompoundAssignmentStatement |
MidAssignmentStatement


9.7.1 Simple assignment

The assignment statement stores the result of an expression in a variable. The type of the expression must be implicitly convertible to the type of the variable. At runtime, the expression on the right hand side of the assignment is evaluated first, then the variable expression. If the variable being assigned into is an array element of a reference type, a runtime check will be performed to ensure that the expression is compatible with the array element type. If the value being assigned is a Single or a Double and floating point error checking is on, then if the value is infinite or NaN at runtime, a System.NotFiniteNumberException will be thrown.

It is important to note that the semantics of the assignment depend on the type of the variable being assigned to. If the variable being assigned to is a value type, then the assignment copies the value of the expression into the variable. If the variable being assigned to is a reference type, then the assignment copies the reference into the variable, not the value itself. If the type of the variable is Object, the assignment semantics are determined by whether the expression is a value type or a reference type.

RegularAssignmentStatement ::= VariableExpression = Expression StatementTerminator
VariableExpression ::= Expression


9.7.2 Delegate assignment

If an assignment statement includes the keyword AddressOf, then the expression on the right hand side of the assignment must be an invocation target and the variable must be typed as a delegate whose signature is compatible with the invocation target. A delegate assignment statement "D = E" is transformed into "D = New T(E)", where T is the delegate type of D.

DelegateAssignmentStatement ::=
VariableExpression = AddressOf InvocationTargetExpression StatementTerminator


9.7.3 Compound assignment

If the assignment operator is a compound assignment operator (an equals sign preceded by a binary operator), then "V OP= E" (where OP is a valid binary operator) is transformed into "V = V OP E". Unlike the fully expanded expression, however, the variable on the left hand side of a compound assignment is only evaluated once. This means that at runtime, the variable expression is evaluated first, then the expression on the right hand side of the assignment.

CompoundAssignmentStatement ::= VariableExpression CompoundBinaryOperator =
  Expression StatementTerminator
CompoundBinaryOperator ::= ^ | * | / | \ | + | - | &


9.7.4 Mid assignment

The Mid assignment statement assigns a string into another string. The left hand side of the assignment has the same syntax as a call to the function Microsoft.VisualBasic.Strings.Mid – the first parameter is the string (whose type must be implicitly convertible to and from String), the second is the one-based start position (whose type must be implicitly convertible to Integer) and the optional third parameter is the length (whose type must be implicitly convertible to Integer). The right hand side is a string whose type must be implicitly convertible to String. The right hand side is truncated to the length parameter (if any) and replaces the characters in the left hand side string, starting at the start position.

At runtime, the right hand side of the assignment is evaluated first, then the arguments to Mid are evaluated from left to right. If the variable is a property, it must have a property getter and a property setter, otherwise an error occurs. Note that Mid is not a reserved word.

MidAssignmentStatement ::= Mid [ $ ] ( VariableExpression , Expression [ , Expression ] ) =
  Expression StatementTerminator


9.8 Invocation statement

The invocation statement invokes a method, optionally preceded by the keyword Call. The invocation statement is processed in the same way as the function invocation expression.

InvocationStatement ::= [ Call ] InvocationExpression StatementTerminator


9.9 Conditional statements

Conditional statements allow conditional execution of statements based on expressions evaluated at runtime.

ConditionalStatement ::= IfStatement | SelectStatement


9.9.1 If statements

An If statement is the basic conditional statement. Each expression must be implicitly convertible to Boolean. If the expression in an If statement is True, then the statements enclosed by the If block are executed. If the expression is False, then each of the ElseIf expressions is evaluated. If one of the expressions evaluates to True, then the corresponding block is executed. If no expression evaluates to True and there is an Else block, the Else block is executed. Once a block finishes executing, execution passes to the end of the If statement.

There is also a line version of the If statement which has a single set of statements to be executed if the If expression is True and an optional set of statements to be executed if the expression is False.

IfStatement ::= BlockIfStatement | LineIfThenStatement
BlockIfStatement ::=
If BooleanExpression [ Then ] StatementTerminator
[ Block ]
[ ElseIfStatement+ ]
[ ElseStatement ]
End If StatementTerminator
ElseIfStatement ::=
ElseIf BooleanExpression [ Then ] StatementTerminator
[ Block ]
ElseStatement ::=
Else StatementTerminator
[ Block ]
LineIfThenStatement ::= If BooleanExpression Then [ EmbeddedStatements ]
[ Else EmbeddedStatements ] StatementTerminator
EmbeddedStatements ::=
[ EmbeddedStatement ] |
EmbeddedStatements : [ EmbeddedStatement ]
BooleanExpression ::= Expression


9.9.2 Select statement

A Select statement executes statements based on the value of an expression.

When a Select statement is executed, the select expression is evaluated and the Case statements are evaluated in order of textual declaration. The first Case statement that evaluates to True has its block executed. If no Case statement evaluates to True and there is a Case Else statement, then that block is executed. Once a block has finished executing, execution passes to the end of the Select statement – there is no fall-through.

A Case clause may take two forms. One form is an optional Is keyword, a relational operator and an expression. If the Select expression is E, the relational operator Op and the Case expression E1, then the Case is evaluated as "E OP E1". There must be a valid operator given the types of the two expressions, else an error occurs.

The other form is an expression with an optional keyword To and an optional second expression. If the Select expression is E, the first Case expression E1 and the second Case expression E2, then the Case is evaluated either as "E = E1" (if no E2 is specified) or "(E >= E1) And (E <= E2)". The operators must be valid for the types of the two expressions, else an error occurs.

SelectStatement ::=
Select [ Case ] Expression StatementTerminator
[ CaseStatement+ ]
[ CaseElseStatement ]
End Select StatementTerminator
CaseStatement ::=
Case CaseClauses StatementTerminator
[ Block ]
CaseClauses ::=
CaseClause |
CaseClauses , CaseClause
CaseClause ::=
[ Is ] RelationalOperator Expression |
Expression [ To Expression ]
CaseElseStatement ::=
Case Else StatementTerminator
[ Block ]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

9.10 Loop statements

Loop statements allow repeated execution of statements.

LoopStatement ::=
DoLoopStatement |
ForStatement |
ForEachStatement


9.10.1 Do loop statement

A Do loop statement loops based on a boolean expression.

An expression may be placed after the Do keyword or after the Loop keyword, but not after both. It is also legal to specify no expression at all; in that case, the loop will never exit. If the expression is placed after the Do, then it will be evaluated before the loop block is executed on each iteration. If the expression is placed after the Loop, then it will be evaluated after the loop block has executed on each iteration. The conditional expression must be prefixed with either a While keyword or an Until keyword. The former breaks the loop if the condition evaluates to False, the latter when the condition evaluates to True.

DoLoopStatement ::=
Do [ WhileOrUntil BooleanExpression ] StatementTerminator
[ Block ]
Loop [ WhileOrUntil BooleanExpression ] StatementTerminator
WhileOrUntil ::= While | Until


9.10.2 For statement

A For loop statement loops based on a set of bounds. A For loop specifies a lower bound, an upper bound and an optional step value. The variable of a For statement must be of a type that supports the greater than operator, the less than operator and the addition operator, otherwise there is an error.

At the beginning of the loop, the three expressions are evaluated in order: the lower bound, the upper bound and the step value. If the step value is omitted, it is implicitly the literal 1. All three expressions must be implicitly convertible to the type of the variable. If the For loop variable is of type Object, then at runtime at least one of the expressions must be of a numeric type and all three expressions must be coercible to the widest numeric type amongst them.

The lower bound expression is assigned to the variable and the variable is then compared to see if it is greater than the upper bound if the step expression is positive, or less than the upper bound is the step expression is negative. If it is, the For loop terminates, otherwise the loop block executes. At the Next statement, the step value is added to the variable and execution returns to the top of the loop. If a variable is specified after the Next keyword, it must be the same as the one used after the For keyword.

If the loop control variable is a property, the property must have both a property getter and a property setter, otherwise there is an error. If the loop control variable is a ReadOnly data member, the loop must take place in a constructor appropriate for the type of the data member (that is, shared or not shared), otherwise there is an error.

ForStatement ::=
For VariableExpression = Expression To Expression [ Step Expression ] StatementTerminator
[ Block ]
Next [ VariableExpression ] StatementTerminator


9.10.3 For Each statement

The For Each loop statement loops based on the elements in an expression. The type of the value returned by the expression in the For Each statement must be a collection type (defined below) and an implicit conversion must exist from the element type of the collection to the type of the iteration variable.

A type C is said to be a collection type if all of the following are true:

  • C contains a public instance method with the signature GetEnumerator() that returns a type E.
  • E contains a public instance method with the signature MoveNext() and the return type Boolean.
  • E contains a public instance property named Current that has a getter. The type of this property is said to be the element type of the collection type.

Before the loop begins, the expression is evaluated, GetEnumerator is called on the expression and the returned value stored in a temporary. Then at the beginning of each loop, MoveNext is called on the temporary. If it returns False, the loop terminates. If it returns True, the Current property is retrieved, coerced to the type of the iterator variable (regardless of whether the conversion is implicit or explicit) and assigned to the iterator variable. Then the loop block is executed. When the Next statement is reached, execution returns to the top of the loop. If a variable is specified after the Next keyword, it must be the same as the first variable after the For Each.

If the loop control variable is a property, the property must be read-write, otherwise there is an error. If the loop control variable is a read-only data member, the loop must take place in a constructor appropriate for the type of the data member (that is, shared or not shared), otherwise there is an error.

Note that the System.Array type is a collection type, and since all array types derive from System.Array, any array type expression is permitted in a For Each statement. For single-dimensional arrays, the For Each statement enumerates the array elements in increasing index order, starting with index 0 and ending with index Length - 1. For multi-dimensional arrays, the indices of the rightmost dimension are increased first.

ForEachStatement ::=
For Each VariableExpression In Expression StatementTerminator
[ Block ]
Next [ VariableExpression ] StatementTerminator


9.11 Error handling statements

Visual Basic 7.0 supports two styles of handling error conditions in the language: structured exception handling and unstructured error handling. Only one style of error handling may be used in a method. If a method uses both, then a compile time error results.

ErrorHandlingStatement ::=
StructuredErrorStatement |
UnstructuredErrorStatement


9.11.1 Structured error handling statements

A program indicates that an error condition has occurred by executing a Throw statement. The statement "throws" an object of a type derived from System.Exception that provides information about the error that has occurred. If the expression does not evaluate to an instance of a type derived from System.Exception, then an error occurs at compile time. If at runtime the expression evaluates to Nothing, then a System.NullReferenceException object instance is thrown instead.

Structured error handling is done through a Try statement. Exceptions thrown by the Throw statement can be "caught" in a Try statement. Execution of a Try statement begins with the first statement in the try block. It is illegal to explicitly transfer execution into a try block except from a catch block.

A Throw statement may omit the expression within a catch block of a Try statement. In that case, the statement "rethrows" the current exception currently being handled within the catch block.

StructuredErrorStatement ::=
ThrowStatement |
TryStatement
ThrowStatement ::= Throw [ Expression ] StatementTerminator
TryStatement ::=
Try StatementTerminator
[ Block ]
[ CatchStatement+ ]
[ FinallyStatement ]
End Try StatementTerminator


9.11.1.1 Finally blocks

When execution leaves any part of the Try statement, the finally block is always guaranteed to be executed. No explicit action is required to make the finally block execute – when execution leaves the Try statement, the system will execute the finally block and then transfer execution to its intended destination. Executing the finally block occurs regardless of the method in which the Try statement is left: reaching the end of the try block, reaching the end of a catch block, executing an Exit Try statement, a GoTo statement or not handling a thrown exception.

It is illegal to transfer execution out of a finally block except through an exception or to explicitly transfer execution into a finally block.

FinallyStatement ::=
Finally StatementTerminator
[ Block ]


9.11.1.2 Catch blocks

If an exception occurs while processing the try block, each Catch statement is examined in textual order to determine if it handles the exception. The identifier specified in a catch clause represents the exception that has been thrown. The identifier is considered to be declared within the catch block's locals declaration space.

A Catch clause with no identifier will catch all exceptions derived from System.Exception. A catch clause with an identifier will only catch exceptions whose types are the same as or derived from the type of the identifier. The type must be System.Exception or a type derived from System.Exception. A catch clause with a When clause will only catch exceptions when the expression evaluates to True.The type of the expression must be implicitly convertible to Boolean. A when clause is only applied after checking the type of the exception and the expression may refer to the identifier representing the exception.

If a catch clause handles the exception, then execution transfers to the catch block. At the end of the catch block, execution transfers to the first statement following the Try statement. The Try statement will not handle any exceptions thrown in a catch block. If no catch clause handles the exception, execution transfers to a location determined by the NGWS Runtime. It is illegal to explicitly transfer execution into a catch block.

CatchStatement ::=
Catch [ Identifier As TypeName ] [ When BooleanExpression ] StatementTerminator
[ Block ]


9.11.2 Unstructured error handling statements

Unstructured error handling is implemented using three statements: the Error statement, the On Error statement and the Resume statement.

When a method uses unstructured error handling, a single error handler is established for the entire method that catches all thrown exceptions. The method then keeps track of the "current" error handler location and the "current" exception that has been thrown. At entry to the method, the current error handler and the current exception are both set to Nothing.

When an exception is thrown in a method that uses unstructured error handling, a reference to the exception object is stored in the object returned by the function Microsoft.VisualBasic.Information.Err.

UnstructuredErrorStatement ::=
ErrorStatement |
OnErrorStatement |
ResumeStatement


9.11.2.1 Error statement

The Error statement throws an exception based on an error number. The expression must be implicitly convertible to Integer.

ErrorStatement ::= Error Expression StatementTerminator


9.11.2.2 On Error statement

The On Error statement modifies the current error handling state. It may be used in one of four ways:

  • On Error Goto -1 resets the "current" exception to Nothing.
  • On Error Goto 0 resets the "current" error handler location to Nothing
  • On Error Goto LabelName establishes the label as the "current" error handler location.
  • On Error Resume, with an optional Next, establishes the Resume behavior as the "current" error handler location.
OnErrorStatement ::= On Error ErrorClause StatementTerminator
ErrorClause ::=
Resume [ Next ] |
GoTo - 1 |
GoTo 0 |
GotoStatement


9.11.2.3 Resume statement

The Resume statement returns execution to the statement that caused the "current" exception. If the Next modifier is specified, execution returns to the statement that would have been executed after the statement that caused "current" exception. If a label name is specified, then execution returns to the label.

In all cases, when a Resume statement is executed, the "current" exception is set to Nothing. If a Resume statement is executed with no "current" exception, then an error occurs at runtime.

ResumeStatement ::= Resume [ ResumeClause ] StatementTerminator
ResumeClause ::= Next | LabelName


9.12 Control flow statements

Control flow statements modify the flow of execution in a method. There are five control flow statements:

  • A GoTo statement causes execution to transfer to the specified label in the method.
  • An Exit statement transfers execution to the next statement after the end of the immediately containing block statement of the specified kind. If the block is the method block, then execution is transferred back to the expression that invoked the method. If the Exit statement is not contained within the kind of block specified in the statement, a compile time error occurs.
  • The Stop statement causes a debugger exception to occur.
  • The End statement causes the program to terminate. End is equivalent to throwing an uncatchable exception. This statement may not be used in programs that are not executable (for example, DLLs).
  • The Return statement returns execution to the expression that invoked the method. If the method is a subroutine, the statement is equivalent to an Exit Sub statement and no expression may be supplied. If the method is a function, an expression must be supplied that is implicitly convertible to the return type of the function; this form is equivalent to assigning to the function return local and then executing an Exit Function statement.
ControlFlowStatement ::=
GotoStatement |
ExitStatement |
StopStatement |
EndStatement |
ReturnStatement
GotoStatement ::= GoTo LabelName StatementTerminator
ExitStatement ::= Exit ExitKind StatementTerminator
ExitKind ::= Do | For | Sub | Function | Property | Try
StopStatement ::= Stop StatementTerminator
EndStatement ::= End StatementTerminator
ReturnStatement ::= Return [ Expression ]


9.13 Array handling statements

There are two statements that simplify working with arrays: ReDim and Erase.

If the variable being referenced in either statement is a property, the property must be read-write or write-only, otherwise there is an error. If the variable is a read-only data member, the assignment must take place in a constructor appropriate for the type of the data member (that is, shared or not shared), otherwise there is an error.

ArrayHandlingStatement ::=
RedimStatement |
EraseStatement


9.13.1 ReDim statement

The ReDim statement instantiates a new array. Each clause in the statement must be a variable whose type is an array type or Object and a list of array bounds. The number of the bounds must be consistent with the type of the variable. At runtime, going from left to right, an array is instantiated with the specified bounds and then assigned to each variable. If the variable type is Object, the number of dimensions is the number of dimensions specified, and the array element type is Object. If the given number of dimensions is incompatible with the variable at runtime, a System.InvalidCastException will be thrown.

If the Preserve keyword is specified, then the new size for each dimension except for the rightmost one must be the same as the size of the existing array's. The values in the existing array are copied into the new array: if the new array is smaller, the existing values are discarded; if the new array is bigger, the extra elements will be initialized to the default value of the element type of the array. If the existing array reference is null, then a System.ArgumentNullException will be thrown. If the size of one of the non-rightmost dimensions changes, then a System.ArrayTypeMismatchException will be thrown.

RedimStatement ::= ReDim [ Preserve ] RedimClauses+ StatementTerminator
RedimClauses ::=
RedimClauses |
RedimClause , RedimClauses
RedimClause ::= VariableExpression ArrayInitializationModifier


9.13.2 Erase statement

The Erase statement sets each of the array variables or properties specified in the statement to Nothing. At runtime, the assignments are done from left to right.

EraseStatement ::= Erase VariableExpressions StatementTerminator
VariableExpressions ::=
VariableExpression |
VariableExpressions , VariableExpression


10. Expressions

An expression is a sequence of operators and operands that specifies a computation. In the general case, an expression evaluates to a value at runtime.

Expression ::=
SimpleExpression |
InvocationExpression |
MemberAccessExpression |
IndexExpression |
NewExpression |
CastExpression |
TypeOfExpression |
OperatorExpression


10.1 Special expression types

There are three special types of expressions that do not evaluate to values at runtime: constant expressions, variable expressions and event expressions.


10.1.1 Constant expressions

A constant expression is expressions whose value can be fully evaluated at compile time. The type of a constant expression can be one of the following: Byte, Short, Integer, Long, Char, Single, Double, Decimal, Boolean, String, any enumeration type, or the null type. The following constructs are permitted in constant expressions:

  • Literals (including the null literal Nothing).
  • References to constant members of types.
  • References to members of enumeration types.
  • Parenthesized sub-expressions.
  • Coercion expressions, provided the target type is one of the types listed above.
  • The +, –, BitNot and Not unary operators.
  • The +, –, *, ^, Mod, /, \, &, BitAnd, BitOr, BitXor, And, Or, =, <, >, <>, <=, and => binary operators, provided each operand is of a type listed above.
  • The runtime functions Microsoft.VisualBasic.Strings.Chr and Microsoft.VisualBasic.Strings.Asc

Constant expressions permit a constant expression of type Integer to be implicitly converted to Byte and Short and a constant expression of type Double to be implicitly converted to Single, provided the value of the constant expression is within the range of the destination type. This is done regardless of whether permissive or strict semantics are being used.

ConstantExpression ::= Expression


10.1.2 Variable expressions

A variable expression is an expression that results in a variable – a data member, a property, a local or an array element. Variable expressions have the same form as value expressions, except that instead of evaluating the variable as the final step, the result of the expression is the variable itself. If the expression does not result in a variable, then it is an error.

VariableExpression ::= Expression


10.1.3 Event expressions

Event expressions are expressions that result in an event member rather than a value. Event expressions are legal only when used with the AddHandler and RemoveHandler statements. An event expression consists of either an event name, or an optional expression, followed by an optional period and an identifier.

If an event name is specified, the event must be shared. If an expression is given, the identifier must specify an event in the declaration space of the expression's type. If no expression is specified, an implicit Me is assumed.

EventExpression ::=
Expression . IdentifierOrKeyword |
[ MeExpression . ] IdentifierOrKeyword |
EventMemberName


10.2 Simple expressions

Simple expressions are literals, parenthesized expressions, Me expressions, meta-type expressions and local variable expression.

SimpleExpression ::=
LiteralExpression |
ParenthesizedExpression |
MeExpression |
MetaTypeExpression |
LocalVariableExpression


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

10.2.1 Literal expressions

Literal expressions evaluate to the value represented by the literal.

LiteralExpression ::= Literal


10.2.2 Parenthesized expressions

A parenthesized expression consists of an expression enclosed in parentheses. The value of the parenthesized expression is the value of the expression within the parentheses.

ParenthesizedExpression ::= ( Expression )


10.2.3 Me expressions

The keyword Me represents a read-only variable whose type is the type of the variable containing the method or property accessor and whose value is either a reference to the variable holding the instance of the type being executed (for value types) or a direct reference to the instance of the type being executed (for reference types). Me may only be used within the body block of a non-shared method or property accessor; any other usage is an error.

MeExpression ::= Me


10.2.4 Meta-type expressions

A meta-type expression consists of the keyword GetType and the name of a type. The value of the meta-type expression is the NGWS Runtime reflection class that represents that type.

MetaTypeExpression ::= GetType ( TypeName )


10.2.5 Local variable expressions

A local variable consists of the name of a local variable. The value of a local variable is the value stored in the local.

LocalVariableExpression ::= LocalVariableName


10.3 Invocation expressions

An invocation expression consists of an invocation target, followed by an open parenthesis, followed by an optional argument list, and followed by a close parenthesis. If there are no arguments, the parenthesis may be omitted. The invocation target must either be:

  • A delegate expression that evaluates to a value of a delegate type.
  • An identifier preceded by an optional value expression and period. The identifier must match the name of accessible method or methods in the declaration space of the type of the preceding value expression. If a period is specified with no expression, the expression from the immediately containing With statement is assumed. If there is no containing With statement, an error occurs. If no period or expression is specified, an implicit Me. is assumed. If Me is not legal in the expression context, an error occurs.
  • The keyword MyClass followed by a period and an identifier. MyClass is equivalent to Me, but all method invocations on it are non-virtual. Thus, the method called will not be affected by the runtime type of the value the method is being called on. It may not be used in shared methods.
  • The keyword MyBase followed by a period and an identifier. MyBase represents a variable whose type is the base type of the type containing the expression and whose value is the instance of the type being executed. It may be used in shared methods as a way of getting at shadowed members. It is illegal to call abstract base methods using MyBase.
  • A method member name. The method or methods referred to by the name must be shared, otherwise an error occurs.

Given a set of one or more methods referred to by an invocation target, overload resolution is applied to pick a single method applicable to the given argument list. If no method is applicable, an error occurs. The value of an invocation expression is the value returned from the method. The method must be a function unless the invocation expression is the argument to an invocation statement.

At runtime, the argument list will be evaluated first, then the invocation target expression. If the invocation target expression references a shared method, the expression will not be evaluated as it is unnecessary.

InvocationExpression ::= InvocationTargetExpression [ ( [ ArgumentList ] ) ]
InvocationTargetExpression ::=
DelegateExpression |
[ [ Expression ] . ] IdentifierOrKeyword |
MyClass . IdentifierOrKeyword |
MyBase . IdentifierOrKeyword |
MethodMemberName
DelegateExpression ::= Expression


10.3.1 Conditional methods

If the method referred to by an invocation target has the System.Diagnostics.ConditionalAttribute attribute set one or more times on it on it, then evaluation of the expression depends on the conditional compilation constants defined at that point in the source file. Each instance of the attribute specifies a string which names a conditional compilation constant. Each conditional compilation constant is evaluated as if it was part of a conditional compilation statement; if the constant evaluates to True, then the expression is evaluated normally at runtime, if the constant evaluates to False, then the expression is not evaluated at all at runtime.

Note that the attribute is not legal on functions or interface methods and is ignored if specified on either kind of method. Thus, conditional methods will only appear in invocation statements.


10.3.2 Argument lists

A regular argument list has two sections: positional arguments and named arguments. Positional arguments must precede any named arguments. Preceding an argument with an identifier and := makes the argument a named argument. At runtime, the argument list is evaluated from left to right. If an argument is omitted from the argument list, the corresponding parameter must be optional. The value given in the optional parameter's declaration is substituted in the place of the omitted argument. Named arguments may not match paramarray parameters.

If an argument is a property, the property must be read-write or read-only, otherwise an error occurs. If the argument being passed is a Single or a Double and floating point error checking is on, then if at runtime the value is infinite or NaN, a System.NotFiniteNumberException will be thrown.

ArgumentList ::=
PositionalArgumentList , NamedArgumentList |
PositionalArgumentList |
NamedArgumentList
PositionalArgumentList ::=
ArgumentExpression |
PositionalArgumentList , [ ArgumentExpression ]
NamedArgumentList ::=
Identifier : = ArgumentExpression |
NamedArgumentList , Identifier : = ArgumentExpression
ArgumentExpression ::= Expression | DelegateArgumentExpression


10.3.2.1 Delegate argument expressions

If an argument includes the keyword AddressOf, then the argument must be an invocation target and the parameter it corresponds to must be typed as a delegate whose signature is compatible with the argument. A delegate argument "AddressOf E" is transformed into "New T(E)", where T is the delegate type of the argument. Note that during overload resolution, a delegate argument expression may match more than one type of delegate (assuming they all have the same delegate signature). In that case, the overload resolution will fail.

DelegateArgumentExpression ::= AddressOf InvocationTargetExpression


10.3.3 Applicable function member

Given a method and a set of positional arguments and named arguments, it is possible to determine if the method is applicable to the arguments through the following algorithm:

  • First, match each positional argument in order to the list of method parameters. If there are more positional arguments than parameters and the last parameter is not a paramarray, the method is not applicable. Otherwise, each additional positional argument is matched to a pseduo-parameter of the element type of the paramarray. If a positional argument is omitted and the type of the paramarray is not Object, the method is not applicable.
  • Next, match each named argument to a parameter with the given name. If one of the named arguments fails to match, or matches an argument already matched with another argument (positional or named), the method is not applicable.
  • Finally, if there are parameters that have not been matched that are not optional, then the method is not applicable. Otherwise, the default value specified in the optional parameter declaration is matched to the parameter.

Once a set of arguments have been matched to parameters, each match must be checked for type compatibility. The following algorithm determines if an argument is compatible with a parameter:

  • If the parameter is a value parameter and the value of the argument is implicitly convertible to the type of the parameter, then they are compatible.
  • If the parameter is a reference parameter and the type of the argument is the same or implicitly convertible to and from the type of the parameter, then they are compatible.
  • Otherwise, the argument and parameter are not compatible.


10.3.4 Overloaded method resolution

Given the set of methods overloaded on a name, the following algorithm determines the applicable method to an argument list:

  • Eliminate all inaccessible members from the set.
  • Eliminate all members from the set that are not applicable to the argument list. If the set is empty, an error results. If only one member remains in the set, then that is the applicable member.
  • Eliminate all members from the set that require narrowing coercions to be applicable to the argument list. If the set is empty, an error results. If only one member remains in the set, then that is the applicable member.
  • Given any two members of the set, M and N, if M is "more applicable" than N to the argument list, then eliminate N from the set. If the set is empty or contains more than one member, an error results. If only one member remains in the set, then that is the applicable member..

A member M is considered more applicable than N if and only if for each formal parameter Mj and Nj that match an actual parameter Aj:

  • Mj and Nj have identical types, or
  • There exists a widening conversion from the type of Mj to the type Nj.

Note that because of the named parameter syntax, the ordering of the actual and formal parameters may not be the same. It is important to note that overload resolution is done on signatures, not on the original method declaration. This means that optional parameters and paramarrays play no part in the process, having already been factored into a method's signature.


10.3.5 Reference parameter passing

In general, an argument passed to a reference parameter denotes the actual storage location of the argument. However, Visual Basic 7.0 in several cases will use copy-in/copy-out semantics to permit passing arguments to reference parameters when the types do not exactly match or the argument has no storage location. Copy-in/copy-out semantics are accomplished by coercing the value to the parameter type, storing the value to a temporary of the appropriate type and passing a reference to the temporary. On the return from the method, the value in the temporary is coerced back to the type of the original value and stored in the original location.

The three cases when copy-in/copy-out is used are:

  1. If the argument is a property. If there is no setter, then no copy-out is done.
  2. If the argument's type is not the same as the parameter type, but is implicitly convertible to and from it. Note that the value is never copied out if the argument is a value or read-only data member. An implication of this is that any type may be passed to a reference parameter of type Object.
  3. If the call is being made late-bound.


10.4 Member access expressions

A member access expression results in the value of a variable or a constant. A member access expression consists of either a data member, property, constant or enumeration value name, or an optional expression, followed by an optional period and an identifier.

If a data member or property name is specified, the member must be shared. If an expression is given, the identifier must specify a data member, property, constant or enumeration value in the declaration space of the expression's type. If a period is specified with no expression, the expression from the immediately containing With statement is assumed. If there is no containing With statement, an error occurs. If no period or expression is specified, an implicit Me. is assumed. If Me is not legal in the expression context, an error occurs.

The value of a data member, constant or enumeration value is the value of the member. The value of a property is obtained by invoking the getter of the property. If the property is write-only or the property has indexers and the expression is not part of an index expression, an error occurs.

Note that if the member being accessed is a shared member, any expression on the left hand side of a period will not be evaluated (because it is unnecessary).

MemberAccessExpression ::=
[ [ Expression ] . ] IdentifierOrKeyword |
Data memberMemberName |
PropertyMemberName |
ConstantMemberName |
EnumMemberName |
DictionaryAccessExpression


10.4.1 Dictionary member access

If the member access expression uses an exclamation point as a qualifier instead of a period, the member access is a dictionary access. A dictionary access is processed as a normal member access, with the exception that if the target has no matching member, the target must have a default property indexed by a single String parameter. Then the expression E!I is transformed into the expression E.D("I"), where D is the default property of E.

If an exclamation point is specified with no expression, the expression from the immediately containing With statement is assumed. If there is no containing With statement, an error occurs.

DictionaryAccessExpression ::= [ Expression ] ! IdentifierOrKeyword


10.5 Index expressions

An index expression results in the value of an array element or an indexed property. An index expression consists of an expression, followed by an open parenthesis, followed by an index argument list, followed by a close parenthesis. The expression must result in a value whose type is an array, in a value whose type has a set of overloaded default properties or in a set of overloaded properties.

If the expression results in overloaded properties or a value with default properties, the overload resolution rules are used to determine whether one of the properties is applicable to the index argument list. If no properties are applicable, then an error occurs. Otherwise, a function member invocation is performed on the getter with the index arguments and the result of the invocation becomes the value of the index expression. If the property is write-only, an error occurs.

If expression results in a value of an array type, the number of arguments in the argument list must be the same as the rank of the array type and may not include any named arguments. Each expression must be implicitly convertible to type Integer. The value of the index expression is the variable at the specified index.

At runtime, the argument list is evaluated first, and then the expression. If any of the indexes are invalid at runtime, a System.IndexOutOfRangeException exception is thrown.

IndexExpression ::= Expression ( ArgumentList )


10.6 New expressions

The New operator is used to create new instances of types. There are three forms of New expressions:

  • Object creation expressions are used to create a new instances of class types and value types.
  • Array creation expressions are used to create new instances of array types.
  • Delegate creation expressions are used to create new instances of delegate types.

The New operator implies creation of an instance of a type, but does not necessarily imply dynamic allocation of memory. In particular, instances of value types require no additional memory beyond the variables in which they reside, and no dynamic allocations occur when New is used to create instances of value types.

NewExpression ::=
ObjectCreationExpression |
ArrayCreationExpression |
DelegateCreationExpression


10.6.1 Object creation expressions

An object creation expression is used to create a new instance of a class type or a structure type. The type of an object creation expression must be a class type or a structure type and cannot be an abstract. Given an object creation expression of the form New T(A), where T is a non-abstract class type or structure type and A is an optional argument list, overload resolution is used to determine the correct constructor of T to call. If no constructor is callable, then an error occurs, otherwise the expression results in the creation of a new instance of T using the chosen constructor. If there are no arguments, the parenthesis may be omitted.

ObjectCreationExpression ::= New TypeName [ ( [ ArgumentList ] ) ]


10.6.2 Array creation expressions

An array creation expression is used to create a new instance of an array type. There are two forms of array creation expressions: one specifies a non-array type name and a list of expressions in parenthesis, the other specifies just an array type name.

An array creation expression of first form allocates an array instance of the type that results from deleting each of the individual arguments from the argument list. The type may not be an array type, and each argument in the argument list must be implicitly convertible to the type Integer and may not be a named argument. The value of each argument determines the length of the corresponding dimension in the newly allocated array instance. If the array element initializer in the expression is not empty, each argument in the argument list must be a constant and the rank and dimension lengths specified by the expression list must match those of the array element initializer.

In an array creation expression of the second form, the rank of the specified array type must match that of the array element initializer. The individual dimension lengths are inferred from the number of elements in each of the corresponding nesting levels of the array element initializer. If the array element initializer is empty, then the length of each dimension is zero.

At runtime, the argument list (if any) is evaluated first and then the array element initializer. The result of evaluating an array creation expression is a reference to the newly allocated array instance. The type of the result is an array type whose rank and length of each dimension are constant for the entire lifetime of the instance. In other words, it is not possible to change the rank of an existing array instance, nor is it possible to resize its dimensions. Elements of arrays created by array creation expressions are always initialized to their default value.

ArrayCreationExpression ::=
New TypeName ( ArgumentList ) ArrayElementInitializer |
New ArrayTypeName ArrayElementInitializer


10.6.3 Delegate creation expressions

A delegate creation expression is used to create a new instance of a delegate type. The argument of a delegate creation expression must be an invocation target. If the argument is a method or a set of overloaded methods, it identifies the method and, for an instance method, the object for which to create a delegate. If the argument is a value of a delegate type, it identifies a delegate instance of which to create a copy.

If the invocation target is a method or set of overloaded methods, one of the method's signature must exactly match the signature of the delegate. If the invocation target is a delegate expression, the signature of the type of the delegate expression must exactly match the signature of the delegate. Otherwise, an error occurs. Note that if the invocation target is a shared method, any expression on the left hand side of a period will not be evaluated (because it is unnecessary). Also note that if the expression on the left hand side of a period results in a value type, the value type will be boxed at runtime when the delegate is created.

The method and object to which a delegate refers are determined when the delegate is instantiated and then remain constant for the entire lifetime of the delegate. In other words, it is not possible to change the target or object of a delegate once it has been created. It is not possible to create a delegate that refers to a constructor or property. If a conditional attribute is set on the invocation target of a delegate creation expression, it is ignored.

DelegateCreationExpression ::= New DelegateTypeName ( InvocationTargetExpression )


10.7 Cast expressions

A cast expression is used to coerce an expression to a given type. There are specific cast keywords which coerce expressions into the primitive types. There is also a general cast keyword, CType, which coerces an expression into any type. If no conversion exists from the type of the expression to the specified type, an error occurs. Otherwise, the result is the value produced by the conversion.

CastExpression ::=
CType ( Expression , TypeName ) |
CastTarget ( Expression )
CaseTarget ::=
CBool | CByte | CChar | CDate | CDec | CDbl |
CInt | CLng | CObj | CShort | CSng | CStr


10.8 Late binding expressions

When the target of a member access expression, invocation expression or index expression is of type Object, the processing of the expression may be deferred until runtime. This deferral is called "late binding," and it allows Object variables to be used in a "typeless" way, where all binding of members is based on the actual runtime type of the value in the variable. If strict semantics are specified by the compilation environment or Option Strict, then late binding causes an error. Note that, unlike the early bound case, invoking or accessing a shared member late bound will cause the invocation target to be evaluated at runtime.


10.8.1 Late bound invocation expressions

When the type of an invocation target is Object, and the method being invoked is not a member of Object., the processing of an invocation expression is deferred until runtime. Late binding also occurs when overload resolution of an invocation target fails solely because one or more arguments were typed as Object (thus eliminating a method because of a narrowing conversion).

In either of the two cases, all invocation processing including overload resolution is deferred until runtime and the method is late bound. At runtime, normal overload resolution rules are applied to determine the correct method to call. If overload resolution fails at runtime a System.MissingMethodException exception is thrown.

It is important to note that late bound invocation is done solely off the runtime type of the invocation target and arguments. If an argument's compile time type is Base, but its runtime type is Dervied (which derives from Base), overload resolution will use Derived as the type used in resolution. It is also important to note that an object's runtime type will never be an interface. Therefore, it is impossible to invoke interface methods in a late bound invocation expression.


10.8.2 Late bound index expressions

When type of an index target is Object or System.Array, the processing of the index expression is deferred until runtime and the indexing is done late bound. At runtime, normal indexing rules are applied to determine the correct indexed property or array element to access. If the index target is an array and no such element exists at runtime a System.IndexOutOfRange exception is thrown. If the index target is not an array, then a System.MissingMethodException exception is thrown.


10.8.3 Late bound member access expressions

The type of the member access target is Object the processing of the member access expression is deferred until runtime and the data member is late bound. At runtime, normal member access rules are applied to determine the correct member to access. If no such data member exists at runtime a System.MissingData memberException exception is thrown.


10.9 Special member access and invocation

Because properties appear to be data members, yet have no storage location, several special situations arise:

  • When passing a property by reference, the property will be passed copy-in/copy-out.
  • When invoking a non-virtual method on a property whose type is a value type, the property value will be fetched using copy-in/copy-out semantics.
  • When accessing a data member of a property whose type is a value type, the property value will be fetched using copy-in/copy-out semantics.

The last two points bear some discussion. When a non-virtual method invocation or data member access is done on a value type, the operation is done on the value itself, not a reference. This means that the actual storage location of the value type is passed to the method invoke or data member access. Since properties have no storage location, the value of the property is fetched from the getter and then copied to a temporary, which is the storage location used for the invocation or data member access. Once the invocation or data member access is done, setting the value from the temporary back to the property propagates the changes from the temporary back to the property. This means that in the example c.p.f = 10, where c is a class instance, p is a property whose type is a value type, and f is a data member of the value type, the property itself is modified and not just a temporary which is thrown away.


11. Conversions

The process of changing a value from one type to another type is called conversion. Conversions may either be widening or narrowing: widening conversions can be accomplished with no loss of information and will never fail, while narrowing conversions involve some kind of loss of information and may fail.

Reference conversions, widening or narrowing, never change the referential identity of the object being converted. In other words, while a reference conversion may change the type of a value, it never changes the value itself. Value conversions, on the other hand, may change the value itself.


11.1 Implicit and explicit conversions

Conversions can either be implicit or explicit. Implicit conversions may be done without any special syntax. Explicit conversions, on the other hand, must be done using the cast operators. Attempting to do an explicit conversion on a value without a cast operator produces an error.

The set of implicit conversions depends on the compilation environment and the Option Strict statement. If strict semantics are being used, only widening conversions may be done implicitly. If permissive semantics are being used, all widening and narrowing conversions may be done implicitly. String conversions (other than those listed as being widening or narrowing) are always explicit, unless done as a part of a conceatenation operation, in which case they are always implicit.


11.2 Array covariance

For any two reference types A and B, if A is a derived type of B, then a conversion exists from an array of type A to a compatible (that is, rank and type of array) array of type B. This relationship is known as array covariance. Array covariance in particular means that an element of an array whose element type is B may actually be an element of an array whose element type is A, provided both A and B are reference types and B is a base type of A.

Because of array covariance, assignments to elements of reference type arrays include a runtime check that ensures that the value being assigned to the array element is actually of a permitted type. Array covariance specifically does not extend to arrays of value types.


11.3 String conversions

Several special conversions exist from String to the primitive types. As noted above, these conversions must always be done explicitly except when used in a concatenation operation. The following conversions exist between String and primitive types:

  • Boolean. The literal True converts to and from the string "True"; the literal False converts to and from the string "False".
  • Byte, Short, Integer, Long, Decimal, Single and Double. The numeric types are converted to and from strings at runtime using the current runtime culture information.
  • Date. Date values are converted to and from strings at runtime using the current runtime culture information.


11.4 Widening conversions

Widening conversions always succeed and never cause information to be lost. The following conversions are classified as widening conversions:

  • From any type to the same type. This conversion exists only such that a name that already has a required type can be said to be convertible to that type.
  • From any derived type to one of its base types.
  • Numeric types widen in the following progression, from left to right: Byte, Short, Integer, Long, Decimal, Single, Double. Conversions from Integer to Single, Long to Single or Double or Decimal to Single or Double may cause a loss of precision, but will never cause a loss of magnitude. The other widening numeric conversions never lose any information.
  • From the literal Nothing to any numeric type. Nothing converts to the literal 0. This is useful for math operations involving Object.
  • From Nothing to any reference type.
  • From the literal 0 to any enumerated type
  • From any enumerated type to its underlying type or any type its underlying type has a widening conversion to.
  • From any type (reference or value) to an interface type it implements. Note that converting a value of a value type to an interface consists of allocating an object instance and copying the value type value into that instance.
  • From an array type S with an element type SE to a covariant array type T with an element type TE, provided all of the following are true:
    • S and T differ only in element type
    • Both SE and TE are reference types
    • A widening reference conversion exists from SE to TE
  • From Char to String
  • From a constant expression of type Long, Integer, Short or Byte to a narrower type, provided the value of the constant expression is within the range of the destination type.


11.5 Narrowing conversions

Narrowing conversions are conversions that cannot be proved to always succeed, conversions that are known to possibly lose information, and conversions across domains of types sufficiently different to merit narrowing notation. The following conversions are classified as narrowing conversions:

  • From any type to a more derived type.
  • Numeric types narrow in the following progression, from left to right: Double, Single, Decimal, Long, Integer, Short, Byte. See the section below on how narrowing numeric conversions are performed.
  • From Boolean to any numeric type. The literal True converts to the literal 1. The literal False converts to the literal 0.
  • From any numeric type to Boolean. A zero value converts to the literal False. Any other value converts to the literal True.
  • From any numeric type to any enumerated type.
  • From any enumerated type to any type its underlying type has a narrowing conversion to.
  • From any enumerated type to any other enumerated type. A narrowing enumeration conversion between two types is processed by treating any participating enumerated type as the underlying type of that enumerated type, and then performing an widening or narrowing numeric conversion between the resulting types.
  • From any class type to any interface type, provided the class type is not final and does not implement the interface type.
  • From any interface type to any type, provided the type is not final or the type implements the interface type. Note that converting an interface to a value type consists of copying the value in the interface instance to the target variable (which may be a temporary).
  • From any interface type to any other interface type, provided there is no inheritance relationship between the two types.
  • From an array type S with an element type SE to a covariant array type T with an element type TE, provided all of the following are true:
    • S and T differ only in element type
    • Both SE and TE are reference types
    • An narrowing reference conversion exists from SE to TE
  • From String to Char
  • From String to Char() and Char() to String
  • From any interface type to any value type that implements the interface type.


11.5.1 Narrowing numeric conversions

Narrowing numeric conversions are those numeric conversions that possibly cause a loss of information. It is important to note that a loss of precision is not considered to be a loss of information. Thus, conversions to Single or Double are not considered narrowing. An narrowing numeric conversion is processed as follows:

  • For a conversion from an integral type to a smaller integral type, or from Single, Double or Decimal to an integral type, the effect depends on whether the compiler option to generate exceptions on integer overflow conditions is specified:
    • If the option is specified:

      If the source is an integral type, the conversion succeeds if the source argument is within the range of the destination type, but throws a System.OverflowException exception if the source argument is outside the range of the destination type

      If the source is Single, Double or Decimal, the source value is rounded up or down to the nearest integral value, and this integral value becomes the result of the conversion. If the source value is equally close to two integral values, the value is rounded to the value that has an even number in the least significant digit position. If the resulting integral value is outside the range of the destination type, a System.OverflowException exception is thrown

    • If the option is not specified:

      If the source is an integral type, the conversion always succeeds, and simply consists of discarding the most significant bits of the source value

      If the source is Single, Double or Decimal, the conversion always succeeds, and simply consists of rounding the source value towards the nearest integral value. If the source value is equally close to two integral values, the value is always rounded to the value that has an even number in the least significant digit position.

  • For a conversion from Double to Single, the effect depends on whether the compiler option to generate exceptions on floating point overflow conditions is specified:
    • If the option is specified:

      The Double value is rounded to the nearest Single value. If the Double value is too small to represent as a Single, the result becomes positive zero or negative zero. If the Double value is too large to represent as a Single, a System.Overflow exception is thrown.

    • If the option is not specified:

      The Double value is rounded to the nearest Single value. If the Double value is too small to represent as a Single, the result becomes positive zero or negative zero. If the Double value is too large to represent as a Single, the result becomes positive infinity or negative infinity. If the Double value is NaN, the result is also NaN.

  • For a conversion from Single or Double to Decimal, the source value is converted to decimal representation and rounded to the nearest number after the 28th decimal place if required. If the source value is too small to represent as a decimal, the result becomes zero. If the source value is NaN, infinity, or too large to represent as a decimal, a System.OverflowException exception is thrown.
  • For a conversion from Decimal to Single or Double, the decimal value is rounded to the nearest Double or Single value. While this conversion may lose precision, it never causes an exception to be thrown.


11.5.2 Narrowing reference conversions

For a narrowing conversion to a reference type to succeed at runtime, the value of the source argument must be Nothing or the actual type of the object referenced by the source argument must be a type that can be converted to the destination type by an widening conversion. If an narrowing conversion fails, a System.InvalidCastException exception is thrown.


11.5.3 Narrowing value type conversions

Doing a narrowing conversion of an interface type to a value type consists of first checking that the object instance is a value of the given value type, and then copying the value out of the instance. For the conversion to succeed at runtime, the value must be a reference to an interface that was previously created by a converting a value of that value type. If the source argument is Nothing or a reference to an incompatible object, a System.InvalidCastException exception is thrown.


12. Operators

Operator expressions are constructed from operands and operators. The operators of an operator expression indicate which operations to apply to the operands. There are two types of operators:

  • Unary operators. The unary operators take one operand and use prefix notation (for example, –x).
  • Binary operators. The binary operators take two operands and use infix notation (for example, x + y). At runtime, the left hand side of the operator is always evaluated first.

The order of evaluation of operators in an expression is determined by the precedence and associativity of the operators.

OperatorExpression ::= UnaryOperatorExpression | BinaryOperatorExpression
BinaryOperatorExpression ::=
ArithmeticOperatorExpression |
ShiftOperatorExpression |
RelationalOperatorExpression |
ConcatenationOperatorExpression |
BitwiseOperatorExpression |
LogicalOperatorExpression


12.1 Operator precedence and associativity

When an expression contains multiple operators, the precedence of the operators controls the order in which the individual operators are evaluated. For example, the expression x + y * z is evaluated as x + (y * z) because the * operator has higher precedence than the + operator. The following table gives all operators in order of precedence from highest to lowest:

Category | Operators
Primary | All non-operator expressions
Exponentiation | ^
Unary negation | +, -
Multiplicative | *, /
Integer division | \
Modulus | Mod
Additive | +, -
Bitwise NOT | BitNot
Bitwise AND | BitAnd
Bitwise OR | BitOr
Bitwise XOR | BitXor
Concatenation | &
Relational | =, <>, <, >, <=, >=, TypeOf…Is, Is, Like
Conditional NOT | Not
Conditional AND | And
Conditional OR | Or
Conditional XOR | Xor

When an operand occurs between two operators with the same precedence, the associativity of the operators controls the order in which the operations are performed. All binary operators are left-associative, meaning that operations are performed from left to right. Precedence and associativity can be controlled using parenthetical expressions.


12.2 Numeric promotion

An operator for a specific type always takes that type as operands and produces a value of the same type. When a binary operation is performed on two numeric values of different types, both operands are implicitly promoted (converted) to the wider of the two operand types type which, in case of the non-relational operators, also becomes the result type of the operation.


12.3 Unary operators

The unary operators are: +, -, BitNot, and Not.

UnaryOperatorExpression ::=
UnaryPlusExpression |
UnaryMinusExpression |
UnaryLogicalNotExpression |
 UnaryBitwiseComplementExpression


12.3.1 Unary plus operator

The unary plus operator results in the value of the operand. The operator is defined for the Byte, Short, Integer, Long, Single, Double and Decimal types.

UnaryPlusExpression ::= + Expression


12.3.2 Unary minus operator

The negation operators is defined for:

  • Short, Integer and Long. The result is computed by subtracting the operand from zero. If integer overflow checking in on and the value of the operand is the maximum negative Short, Integer or Long, a System.OverflowException exception is thrown. Otherwise, if the value of the operand is the maximum negative Short, Integer or Long, the result is that same value and the overflow is not reported.
  • Single and Double. The result is the value of the operand with its sign inverted. If the operand is NaN, the result is also NaN.
  • Decimal. The result is computed by subtracting the operand from zero.
UnaryMinusExpression ::= - Expression


12.3.3 Logical negation operator

The logical negation operator is defined for Boolean and computes the logical negation of the operand.

UnaryLogicalNotExpression ::= Not Expression


12.3.4 Bitwise complement operator

The bitwise complement operator results in the bitwise complement of the operand. The operator is defined for the Byte, Short, Integer and Long types.

UnaryBitwiseComplementExpression ::= BitNot Expression


12.4 Arithmetic operators

The *, /, \, ^, Mod, +, and – binary operators are called the arithmetic operators.

It is important to note that floating-point arithmetic operations may be performed with higher precision than the result type of the operation. For example, some hardware architectures support an "extended" or "long double" floating-point type with greater range and precision than the Double type, and implicitly perform all floating-point operations using this higher precision type. Only at excessive cost in performance can such hardware architectures be made to perform floating-point operations with less precision, and rather than require an implementation to forfeit both performance and precision, Visual Basic 7.0 allows a higher precision type to be used for all floating-point operations. Other than delivering more precise results, this rarely has any measurable effects. However, in expressions of the form x * y / z, where the multiplication produces a result that is outside the double range, but the subsequent division brings the temporary result back into the double range, the fact that the expression is evaluated in a higher range format may cause a finite result to be produced instead of an infinity.

ArithmeticOperatorExpression ::=
MultiplicationOperatorExpression |
DivisionOperatorExpression |
ModuloOperatorExpression |
ExponentOperatorExpression |
AdditionOperatorExpression |
SubtractionOperatorExpression


12.4.1 Multiplication operator

The arithmetic multiplication operator computes the product of two operands. The multiplication operator is defined for:

  • Byte, Short, Integer and Long. If integer overflow checking in on and the product is outside the range of the result type, a System.OverflowException exception is thrown. Otherwise, overflows are not reported and any significant high-order bits of the result are discarded.
  • Single and Double. The product is computed according to the rules of IEEE 754 arithmetic.
  • Decimal. If the resulting value is too large to represent in the decimal format, a System.OverflowException exception is thrown. If the result value is too small to represent in the decimal format, the result is zero.
MultiplicationOperatorExpression ::= Expression * Expression


12.4.2 Division operator

The division operator computes the quotient of two operands. There are two division operators: the regular division operator and the integer division operator.

  • The integer division operator is defined for Byte, Short, Integer and Long. If the value of the right operand is zero, a System.DivideByZeroException exception is thrown. The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs. If the left operand is the maximum negative Short, Integer or Long and the right operand is –1, an overflow occurs. If integer overflow checking in on, this causes a System.OverflowException exception to be thrown. Otherwise, the overflow is not reported and the result is instead the value of the left operand.

The regular division operator is defined for:

  • Single and Double. The quotient is computed according to the rules of IEEE 754 arithmetic.
  • Decimal. If the value of the right operand is zero, a System.DivideByZeroException exception is thrown. If the resulting value is too large to represent in the decimal format, a System.OverflowException exception is thrown. If the result value is too small to represent in the decimal format, the result is zero.

According to normal numeric promotion rules, regular division purely between operands of types Byte, Short, Integer and Long would be illegal. However, in this specific situation, those types are treated specially and both operands are promoted to Double. The promotion happens to Double instead of Decimal because Double division is more performant than Decimal division on the NGWS Frameworks and Runtime.

DivisionOperatorExpression ::= RegularDivisionOperatorExpression | IntegerDivisionOperatorExpression
RegularDivisionOperatorExpression ::= Expression / Expression
IntegerDivisionOperatorExpression ::= Expression \ Expression


12.4.3 Modulo operator

The modulo operator computes the remainder of the division between two operands. The modulo operator is defined for Byte, Short, Integer and Long. The result of x Mod y is the value produced by x – (x / y) * y. If y is zero, a System.DivideByZeroException exception is thrown. The modulo operator never causes an overflow.

ModuloOperatorExpression ::= Expression Mod Expression


12.4.4 Exponentiation operator

The exponentiation operator computes the first operand raised to the power of the second operand. The exponentiation operator is defined for Double. The value is computed according to the rules of IEEE 754 arithmetic.

ExponentOperatorExpression ::= Expression ^ Expression


12.4.5 Addition operator

For numeric and enumeration types, the addition operator computes the sum of the two operands. The addition operator is defined for:

  • Byte, Short, Integer and Long. If integer overflow checking in on and the sum is outside the range of the result type, a System.OverflowException exception is thrown. Otherwise, overflows are not reported and any significant high-order bits of the result are discarded.
  • Single and Double. The sum is computed according to the rules of IEEE 754 arithmetic.
  • Decimal. If the resulting value is too large to represent in the decimal format, a System.OverflowException exception is thrown. If the result value is too small to represent in the decimal format, the result is zero.
  • Enumerated types. The addition operator is done on the underlying type of the enumerated type, but the return type is the enumerated type.
  • String and Char. Both operands must be one of the two types. Both operands are widened to string and the two strings are concatenated together, with the first operand first and the second operand second. The result is String.
AdditionOperatorExpression ::= Expression + Expression


12.4.6 Subtraction operator

The subtraction operator subtracts the second operand from the first operand. The subtraction operator is defined for:

  • Byte, Short, Integer and Long. If integer overflow checking in on and the difference is outside the range of the result type, a System.OverflowException exception is thrown. Otherwise, overflows are not reported and any significant high-order bits of the result are discarded.
  • Single and Double. The difference is computed according to the rules of IEEE 754 arithmetic.
  • Decimal. If the resulting value is too large to represent in the decimal format, a System.OverflowException exception is thrown. If the result value is too small to represent in the decimal format, the result is zero.
  • Enumerated types. The subtraction operator is done on the underlying type of the enumerated type, but the return type is the enumerated type.
SubtractionOperatorExpression ::= Expression - Expression


12.5 Relational operators

The relational operators compare values in relation to one other. The comparison operators are =, <>, <, >, <=, >=. There are also three other relational operators, TypeOf…Is, Is and Like, which have specialized behaviors. All of the relational operators result in a Boolean value.

RelationalOperatorExpression ::=
ComparisonOperatorExpression |
TypeOfIsOperatorExpression |
IsOperatorExpression |
LikeOperatorExpression


12.5.1 Comparison operators

The comparison operators have the following general meaning:

  • The = operator tests whether the two operands are equal
  • The <> operator tests whether the two operands are not equal
  • The < operator tests whether the first operand is less than the second operand
  • The > operator tests whether the first operand is greater than the second operand
  • The <= operator tests whether the first operand is less than or equal to the second operand
  • The >= operator tests whether the first operand is greater than or equal to the second operand

The comparison operators are defined for the following types:

  • Byte, Short, Integer and Long. The operators compare the numeric values of the two integral operands.
  • Single and Double. The operators compare the operands according to the rules of the IEEE 754 standard.
  • Decimal. The operators compare the numeric values of the two decimal operands.
  • Enumerated types. The operators compare enumerated types as if they were their underlying types.

Only the equality (=) and inequality (<>) operators are defined for the following types:

  • Boolean. The = operator returns True if both operands are True or both operands are False. The <> operator returns False if both operands are True or both operands are False.
  • All reference types. The operators return the result of comparing the two references for equality or non-equality. Note that for two reference types to be compared using the operators, one type must be implicitly converitible to the other.
  • Char and String. The operators return the result of comparing the two values using either a binary comparison or a text comparison. The comparison used is determined by the compilation environment and the Option Compare directive. A binary comparison compares if the numeric Unicode value of the characters, or each character in each string, is the same. A text comparison does a Unicode text comparison based on the current culture in use on the NGWS Frameworks and Runtime. When doing a string comparison, a Nothing value is equivalent to the string literal "".
ComparisonOperatorExpression ::=
Expression = Expression |
Expression < > Expression |
Expression < Expression |
Expression > Expression |
Expression < = Expression |
Expression > = Expression


12.5.2 TypeOf...Is operator

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

12.5.2 TypeOf…Is operator

The TypeOf…Is operator is used to check whether the runtime type of an object is compatible with a given type. The first operand must be a reference type, and the second operand must be a type name. The operator returns True if a conversion from the runtime type of the operand to the type exists.

TypeOfIsOperatorExpression ::= TypeOf Expression Is TypeName


12.5.3 Is operator

The Is operator is used to do a reference comparison. The operands must both be reference types. This operator is useful to force a reference comparison when the type Object is involved.

IsOperatorExpression ::= Expression Is Expression


12.5.4 Like operator

The Like operator determines whether a string matches a given pattern. Both operands must be of type String. The first operand is the string being matched, the second operand is the pattern to match against. The pattern is made up of Unicode characters. The following character sequences have special meanings:

  • The character ? matches any single character.
  • The character * matches zero or more characters.
  • The character # matches any single digit (0–9).
  • A list of characters surrounded by brackets ([ab…]) matches any single character in the list.
  • A list of character surrounded by brackets and prefixed by an exclamation point ([!ab…]) matches any single character not in the character list.

Two characters in a character list separated by a hyphen (-) specifiy a range of Unicode characters starting with the first character and ending with the second character. If the second character is not later in the sort order than the first character, a runtime error occurs. A hypen that appears at the beginning or end of a character list specifies itself.

Note that to match the special characters left bracket ([), question mark (?), number sign (#), and asterisk (*), they must be enclosed in brackets. The right bracket (]) can not be used within a group to match itself, but it can be used outside a group as an individual character. The character sequence [] is considered to be the string literal "".

Also note that character comparisons and ordering for character lists are dependent on the type of comparisons being used. If binary comparisons are being used, then character comparisons and ordering are based on the numeric Unicode values. If text comparisons are being used, then character comparisons and ordering are based on the current locale being used on the NGWS Frameworks and Runtime.

In some languages, there are special characters in the alphabet that represent two separate characters. For example, several languages use the character "æ" to represent the characters "a" and "e" when they appear together. When using text comparisons, the Like operator recognizes that the single special character and the two individual characters are equivalent. In that case, an occurrence of the single special character in either pattern or string matches the equivalent 2-character sequence in the other string. Similarly, a single special character in pattern enclosed in brackets (by itself, in a list, or in a range) matches the equivalent 2-character sequence in the string.

LikeOperatorExpression ::= Expression Like Expression


12.6 Concatenation operator

The concatenation operator is only defined for the String type. A concatenation operation results in a string that is the concatenation of the two operands in order from left to right. As noted in the Conversions chapter, the operands will be implicitly converted to String if they are of a type that has a conversion to String. Also, there is a special case in that the null type Nothing is treated in concatenation expressions as if it was an empty string literal "".

ConcatenationOperatorExprsesion ::= Expression & Expression


12.7 Bitwise operators

The BitAnd, BitOr and BitXor operators are called the bitwise operators and perform the specified bit operation on the two operands. No overflows are possible from these operations. The bitwise operators are specified on Byte, Short, Integer, Long and all enumerated types. The enumerated type operators do the bitwise operation on the underlying type of the enumerated type, but the return value is the enumerated type.

BitwiseOperatorExpression ::=
Expression BitAnd Expression |
Expression BitOr Expression |
Expression BitXor Expression


12.8 Conditional logical operators

The And, Or and Xor operators are called the conditional logical operators. They are only defined on the type Boolean and short-circuit, which is to say in certain situations the second operand will not be evaluated at runtime.

The conditional logical operators are evaluated as follows:

  • If the first operand in an And operation evaluates to False, then the expression returns False. Otherwise, a logical AND operation is performed on its two operands.
  • If the first operand in an Or operation evaluates to True, then the expression returns True. Otherwise, a logical OR operation is performed on its two operands.
  • The Xor operator always performs a logical exclusive-OR operation on its two operands.

Note that in the case of And and Or the first operand is only ever evaluated once, and the second operand is either not evaluated or evaluated exactly once.

LogicalOperatorExpression ::=
Expression And Expression |
Expression Or Expression |
Expression Xor Expression


Visual Basic Compiler Options

The compiler produces executable (.exe) files or dynamic-link libraries (DLLs).

Every compiler option is available in two forms: -option and /option. The documentation only shows the /option form.

To find a particular compiler option, see one of the following lists:

  • Visual Basic Compiler Options Listed Alphabetically
  • Visual Basic Compiler Options Listed by Category

See Also

Building from the Command Line


Building From the Command Line

Microsoft Visual Studio provides a command line compiler for Visual Basic as an alternative to compiling a Visual Basic program from within Visual Studio.

When to use the Command Line Compiler

The Visual Basic command line compiler is designed for situations when the rich environment provided by Visual Studio is not required. Application developers that prefer to work in the MS-DOS environment may wish to use a simple text editor and the command line compiler to build projects. The command line compiler is also useful when you want to automate the build process or when using computers with limited system memory.

Invoking the Compiler

The compiler can be invoked by typing the name of its executable (vbc.exe) on the command line. You may need to adjust your path if you want vbc.exe to be invoked from any subdirectory on your computer.

Visual Basic Compiler Options

The Visual Basic command line compiler supports a complete set of compiler options that control input files, output files, assemblies, debug and preprocessor options.

Sample Command Lines

  • Compiles File.vb producing File.exe:
    vbc File.vb
  • Compiles File.vb producing File.dll:
    vbc /target:library File.vb
  • Compiles File.vb but no executable is created (useful for simply checking syntax):
    vbc /nooutput File.vb
  • Compiles File.vb and creates My.exe:
    vbc /out:My.exe File.vb
  • Compiles all of the VB files in the Microsoft\WFC\UI and Microsoft\WFC\Util directories and creates a Microsoft.WFC.UI.dll:
    vbc /target:library /out:Microsoft.WFC.UI.dll Microsoft\WFC\UI\*.vb Microsoft\WFC\Util\*.vb
  • Compiles all of the VB files in the current directory, importing metadata from Microsoft.WFC.UI.dll and Microsoft.WFC.InterOp.dll into File2.exe (a debug version of the executable is produced):
    vbc /debug /out:File2.exe /reference:Microsoft.WFC.UI.dll;Microsoft.WFC.InterOp.dll *.vb
  • Compiles all of the VB files in the current directory, with optimizations on and defines the DEBUG symbol. The output is File2.exe:
    vbc /define:DEBUG=1 /optimize /out:File2.exe *.vb
  • Compiles all of the VB files in the current directory producing a debug version of File2.dll. No logo and no warnings are displayed:
    vbc /target:library /out:File2.dll /warn:0 /nologo /debug *.vb
  • Compiles all of the VB files in the current directory to Something.xyz (a DLL):
    vbc /target:library /out:Something.xyz *.vb

See Also

Visual Basic Compiler Options Listed Alphabetically | Visual Basic Compiler Options Listed by Category


Visual Basic Compiler Options Listed Alphabetically

The following compiler options are sorted alphabetically.

Option | Purpose
@ | Specify a response file.
/? | Display compiler options. No compilation will occur.
/assembly.keycontainer | Specify the originator of an assembly.
/assembly.keyfile | Specify a file with a key pair to make a shareable component.
/assembly.version | Create an assembly and modify the Version field in the metadata.
/baseaddress | Specify the base address of a DLL.
/bugreport | Create a file that contains information that makes it easy to report a bug.
/cls | Turn on Common Language Subset (CLS) checking.
/debug | Produce debugging information
/define | Define preprocessor symbols.
/help | Display compiler options. No compilation will occur.
/import | Import a namespace from a specified assembly.
/linkresource | Link a NGWS runtime resource to an assembly rather than directly embedding it.
/main | Specify the class that contains the Sub Main procedure to use at startup.
/nologo | Suppress compiler banner information.
/nooutput | Compile but do not create an output file.
/nostdlib | Do not import the standard libraries Mscorlib.dll and Microsoft.VisualBasic.dll.
/optimize | Enable/disable code optimization.
/optioncompare | Determines whether string comparisons should be binary or use locale specific text semantics.
/optionexplicit | Require explicit declaration of variables.
/optionstrict | Enforce strict language semantics.
/out | Specify output file.
/recurse | Search subdirectories for source files to compile.
/reference | Import metadata from a file that contains an assembly.
/removefpchecks | Disable floating point error checking.
/removeintchecks | Disable integer overflow checking.
/resource | Embed a specified NGWS runtime resource into the output file.
/target | Specify the format of the output file using one of four options: /target:exe /target:library /target:module /target:winexe
/Time | Output total compilation time.
/verbose | Output extra information during compilation.
/warn | Set warning level.
/warnaserror | Promote warnings to errors.
/win32icon | Insert a .ico file into the output file.
/win32resource | Insert a Win32 resource into the output file.

See Also

Visual Basic Compiler Options Listed by Category | Building from the Command Line


Visual Basic Compiler Options Listed by Category

The following compiler options are sorted by category.

Optimization

Option | Purpose
/optimize | Enable/disable optimizations.

Output Files

Option | Purpose
/out | Specify output file.
/nooutput | Compile but do not create an output file.
/target | Specify the format of the output file using one of four options: /target:exe /target:library /target:module /target:winexe

NGWS runtime Assemblies

Option | Purpose
/assembly.keycontainer | Specify the originator of an assembly.
/assembly.keyfile | Specify a file with a key pair to make a shareable component.
/assembly.version | Create an assembly and modify the Version field in the metadata.
/nostdlib | Do not import the standard libraries Mscorlib.dll and Microsoft.VisualBasic.dll.
/reference | Import metadata from a file that contains an assembly.

Debugging/Error Checking

Option | Purpose
/bugreport | Create a file that contains information that makes it easy to report a bug.
/cls | Turn on Common Language Subset (CLS) checking.
/debug | Emit debugging information.
/removefpchecks | Disable floating point error checking.
/removeintchecks | Disable integer overflow checking.
/warn | Set warning level.
/warnaserror | Promote warnings to errors.

Preprocessor

Option | Purpose
/define | Define preprocessor symbols.

Resources

Option | Purpose
/linkresource | Link a NGWS runtime resource to an assembly.
/resource | Embed a specified NGWS runtime resource into the output file.
/win32icon | Insert a .ico file into the output file.
/win32resource | Insert a Win32 resource into the output file.

Miscellaneous

Option | Purpose
@ | Specify a response file.
/? | Displays the compiler options. This command is the same as specifying the /help option.
/baseaddress | Specify the base address of a DLL.
/help | Displays the compiler options. This command is the same as specifying the /? option.
/main | Specify the class that contains the Sub Main procedure to use at startup.
/nologo | Suppress compiler banner information.
/optionexplicit | Require explicit declaration of variables.
/optionstrict | Enforce strict type semantics.
/optioncompare | Determines whether string comparisons should be binary or use locale specific text semantics.
/recurse | Search subdirectories for source files to compile.
/Time | Output total compilation time.

See Also

Visual Basic Compiler Options Listed Alphabetically | Building from the Command Line


@ (Specify Response File)

Lets you specify a file that contains compiler options and source code files to compile. @response_file

Arguments

response_file
A file that lists compiler options or source code files to compile.

Remarks

The compiler processes the compiler options and source code files specified in a response file as if they had been specified on the command line.

To specify more than one response file in a compilation, specify multiple response file options. For example:

@file1.rsp @file2.rsp

In a response file, multiple compiler options and source code files can appear on one line. A single compiler option specification must appear on one line (cannot span multiple lines). Response files can have comments that begin with the # symbol.

Specifying compiler options from within a response file is just like issuing those commands on the command line.

You can combine options specified on the command line with options specified in one or more response files. The compiler processes the command options as they are encountered. Therefore, command line arguments can override previously listed options in response files. Conversely, options in a response file will override options listed previously on the command line or in other response files.

This option is not available from within the development environment; it is only available when compiling from the command line.

Example

The following are a few lines from a sample response file:

# build the first output file
/target:exe
/out:MyExe.exe
source1.vb
source2.vb

See Also

Visual Basic Compiler Options | Building from the Command Line


/assembly.keyfile (Specify Key File)

Specifies a file containing a key pair to make a shareable component. /assembly.keyfile:"file"

-or-

/a.keyfile:"file"

Arguments

keyfile:file
File that contains the key. Place the string in double quotation marks (" ") if there is a space in file.

Remarks

The compiler inserts the public key into the assembly manifest and then signs the final assembly with the private key. Use sn -k file (at the command line) to generate a key file.

The key information appears in the Originator Blob field of the assembly.

If you compile with /target:module, information about the key file will be held in the module and incorporated into the assembly that will be created when you compile an application with /reference.

/a.keyfile is the short form of /assembly.keyfile.

Example

Compile source file input.vb and specify a key file:

vbc /assembly.keyfile:myfile.sn input.vb

See Also

Visual Basic Compiler Options | /assembly.keycontainer | /assembly.version


/assembly.keycontainer (Specify Key Container)

EnterDescription

/assembly.keycontainer:"container"

-or-

/a.keycontainer:"container

Arguments

keyname:container
Container that contains the key. Place the string in double quotation marks (" ") if there is a space in container

Remarks

The compiler creates the sharable component by inserting a public key into the assembly manifest and signing the final assembly with the private key. Use sn -k file (at the command line) to generate a key file.

The key information appears in the Originator Blob field of the assembly.

/a.keycontainer is the short form of /assembly.keycontainer.

Example

Compile source file input.vb and specify a key container:

vbc /assembly.keycontainer:key1 input.vb

See Also

Visual Basic Compiler Options | /assembly.keyfile | /assembly.version


/assembly.version (Modify Version Field in Metadata)

Modifies the Major Version, Minor Version, Revision Number, and Build Number fields in the assembly metadata. /assembly.version:[major[.minor[.revision[.build]]]

-or-

/a.version:[major[.minor[.revision[.build]]]

Arguments

version:[major[.minor[.revision[.build]]]
The major, minor, revision, and build version number that you want to appear in this assembly. The default version for these fields is zero. You can specify version numbers between 0 and 65534.

Remarks

If you compile with /target:module, version information will be held in the module and incorporated into the assembly that will be created when you compile an application with /reference.

/a.version is the short form of /assembly.version.

Example

Compile source file input.vb and customize the Version field of the assembly:

vbc /assembly.version:1.2 input.vb

See Also

Visual Basic Compiler Options | /assembly.keyfile | /assembly.keycontainer


/baseaddress (Specify Base Address of DLL)

Specifies a default base address when creating a DLL.

/baseaddress:address

Arguments

address
The base address for the DLL. This address must be specified as a hexadecimal number.

Remarks

The default base address for a DLL is set by the NGWS runtime.

Be aware that the lower-order word in this address will be rounded. For example, if you specify 0x11110001, it will be rounded to 0x11110000.

To complete the signing process for a DLL, use –R of SN.EXE.

This option is ignored if the target is not a DLL.

See Also

Visual Basic Compiler Options | /target


/bugreport (Report a Problem)

Creates a file that can be used when filing a bug report. /bugreport:file

Arguments

file
The name of the file that you want to contain your bug report.

Remarks

The following information is placed in file:

  • A copy of all source code files in the compilation.
  • A listing of the compiler options used in the compilation.
  • Version information about your compiler, runtime, and operating system.
  • Compiler output, if any.
  • A description of the problem, which you will be prompted for.
  • A description of how you think the problem should be fixed, which you will be prompted for.

Because a copy of all source code files will be placed in file, you may want to reproduce the (suspected) code defect in the shortest possible program.

Example

Compile t2.vb and put all bug reporting information in the file problem.txt:

vbc /bugreport:problem.txt t2.vb

See Also

Visual Basic Compiler Options | /debug


/cls (Verify Common Language Specification Compliance)

Turns on or off common language specification compliance checking.

/cls[+ | -]

Remarks

By default, the compiler checks common language specification compliance, just as if you specified /cls+ or /cls. Specify /cls- to turn off common language specification checking.

Example

Check common language specification compliance of the file test.vb:

vbc /cls test.vb

See Also

Visual Basic Compiler Options


/debug (Emit Debugging Information)

Causes the compiler to generate debugging information and place it in the output file(s). /debug[+ | -]

Remarks

Use this option to create debug builds. If /debug (or /debug+) is not specified, you will not be able to debug the output file of your program.

By default, debugging information is not emitted (/debug-). To emit debugging information, specify /debug or /debug+.

Example

Place debugging information in output file app.exe:

vbc /debug /out:app.exe test.vb

See Also

Visual Basic Compiler Options | /bugreport


/define (Preprocessor Definition)

Defines conditional compiler constants.

/define:name=value[,name=value]

-or-

/d:name=value[,name=value]

Arguments

name
The name of one or more symbols that you want to define.
value
The value to assign to the symbol.

Remarks

The /define option has the same effect as using a #Const preprocessor directive in your source file.

You can use symbols created by this option with the #If...Then...#Else Directive to compile source files conditionally.

/d is the short form of /define.

You can define multiple symbols with /define by using a comma to separate symbol names.

Example

Define two conditional compiler constants:

Vbc /define:DEBUGMODE=True,TRAPERRORS=False test.vb

Use the two constants:

Sub mysub()
   #If debugmode Then
      '. Place debug statements here.
       MsgBox("debug mode")
   #Else
      '. Place default statements here.
      '.
   #End If
End Sub

See Also

Visual Basic Compiler Options | #If...Then...#Else Directive


/help, /? (Compiler Command-Line Help)

Displays the compiler options. /help

-or-

/?

Remarks

If this option is included in a compilation, no output file will be created and no compilation will take place.

This option is not available from within the development environment; it is only available when compiling from the command line.

Example

Display help from the command line:

vbc /help

See Also

Visual Basic Compiler Options


/import (Import a Namespace From a Specified Assembly)

Imports a namespace from a specified assembly.

/import:namespace[,namespace]

Parameters

namespace
The namespace to be imported

Remarks

The /import option will import any namespace defined within the current set of source files or from any referenced assembly.

Example

Compile in.vb and import the namespace mynamespace:

vbc /import:mynamespace in.vb

See Also

Visual Basic Compiler Options | References and the Imports Statement


/linkresource (Link to NGWS Runtime Resource)

Creates a link to a NGWS runtime resource. /linkresource:filename[,identifier]

-or-

/linkres:filename[,identifier]

Arguments

filename
The NGWS runtime resource file to which you want to link from the assembly.
identifier (optional)
The logical name for the resource; the name used to load the resource. The default is the name of the file name.

Remarks

The /linkresource option does not embed the resource file in the output file. Use the /resource option to embed a resource file in the output file.

/linkresource requires one of the /target options other than /target:module.

NGWS runtime resources can be accessed with members in the System.Resources namespace.

/linkres is the short form of /linkresource.

Example

Compile in.vb and link to resource file rf.resource:

vbc /linkresource:rf.resource in.vb

See Also

Visual Basic Compiler Options


/main (Specify Location of Sub Main Procedure)

Specifies the class or module that contains the Sub Main procedure. /main:namespace.location

Arguments

namespace.location
This argument can be either the name of a module or a class that contains the Sub Main procedure.

Remarks

Use this option when creating an executable or Windows executable program. If the /main option is omitted, the compiler will search for a valid Shared Sub Main in all public classes and modules.

Example

Compile t2.vb and t3.vb, specifying that the Sub Main procedure will be found in the Test2 class:

vbc t2.vb t3.vb /main:Test2

See Also

Visual Basic Compiler Options | /target:winexe | /target:exe


/nologo (Suppress Banner Information)

Suppresses display of the copyright banner and the display of informational messages during compiling. /nologo[+ | -]

Remarks

If you specify /nologo+ or /nologo, a copyright banner will not be displayed by the compiler. The default for this option is /nologo-.

This option is not available from within the development environment; it is only available when compiling from the command line.

Example

Compile t2.vb and do not display a copyright -banner:

vbc /nologo+ t2.vb

See Also

Visual Basic Compiler Options


/nooutput (Do Not Create Output File)

Compiles without creating output files. /nooutput[+ | -]

Remarks

The /nooutput option lets you see any compilation errors or warnings.

On the command line, specify /nooutput in front of the source code file names. If you do not specify /nooutput, an output file will be created and the result is the same as specifying /nooutput - . Specifying /nooutput is the same as specifying /nooutput +.

Note The /nooutput option has not yet been implemented in the Visual Basic command line compiler.

Example

Compile t2.vb but do not create an output file and compile t3.vb into t3.exe:

vbc /nooutput t2.vb /out:t3.exe t3.vb

See Also

Visual Basic Compiler Options


/nostdlib (Do Not Import Standard Library)

Prevents the import of Mscorlib.dll and Microsoft.VisualBasic.dll. /nostdlib[+ | -]

Remarks

Mscorlib.dll defines the entire System namespace. Use this option if you want to define or create your own System namespace and objects.

If you specify /nostdlib or /nostdlib+, the standard libraries mscorlib.dll and Microsoft.VisualBasic.dll will not be imported into your program and you must manually add references to MSCorLib.dll and Microsoft.VisualBasic.dll using the /reference option. The default for this option is /nostdlib -.

Example

Compile t2.vb but do not load standard libraries:

vbc t2.vb /nostdlib

See Also

Visual Basic Compiler Options


/optimize (Enable/disable Optimizations)

Enables or disables compiler optimizations. /optimize[+ | -]

Remarks

Compiler optimizations make your output file smaller, faster, and more efficient but can make debugging difficult. By default, /optimize is in effect. Specifying /optimize is the same as specifying /optimize+.

To prevent an optimized output file, specify /optimize-.

It is possible to combine the /optimize and /debug options.

Example

Compile t2.vb and enable compiler optimizations:

vbc t2.vb /optimize

See Also

Visual Basic Compiler Options


/optioncompare (Specify How Strings are Compared)

Specifies how string comparisons will be made. The /optioncompare compiler option can be specified in one of two forms:
/optioncompare:binary
Use binary string comparisons.
/optioncompare:text
Use text string comparisons.

Remarks

/optioncompare:text is the default for this option.

See Also

Visual Basic Compiler Options


/optioncompare:binary (Use Binary String Comparisons)

Causes strings to be compared based on their binary representations.

/optioncompare:binary

Remarks

In Microsoft Windows, the code page being used determines the binary sort order. A typical binary sort order is shown in the following example:

A < B < E < Z < a < b < e < z < À < Ê < Ø < à < ê < ø

Example

Compile myfile.vb and use binary string comparisons:

vbc /optioncompare:binary myfile.vb

See Also

Visual Basic Compiler Options


/optioncompare:text (Use Text String Comparisons)

Causes strings to be compared based on their text representations.

/optioncompare:text

Remarks

Text based string comparisons are based on a case-insensitive text sort order determined by your system's locale. A typical text sort order is shown in the following example:

(A=a) < ( À=à) < (B=b) < (E=e) < (Ê=ê) < (Z=z) < (Ø=ø)

Example

Compile myfile.vb and use text based string comparisons:

vbc /optioncompare:text myfile.vb

See Also

Visual Basic Compiler Options


/optionexplicit (Require Explicit Declaration of Variables)

Causes the compiler to report errors if variables are not declared prior to use.

/optionexplicit[+ | -]

Remarks

The default for this option is /optionexplicit+ which is the same as /optionexplicit. Specify /optionexplicit- if you want to use implicitly declared variables.

Example

Compile in.vb and check for undeclared variables:

vbc /optionexplicit in.vb

See Also

Visual Basic Compiler Options


/optionstrict (Enforce Strict Type Semantics)

Enforces strict type semantics to restrict implicit type conversions.

/optionstrict [+ | -]

Remarks

The default for this option is /optionstrict+ or /optionstrict. Only widening type conversions can be done implicitly when strict type semantics are being enforced. Implicit narrowing type conversions, such as assigning a Decimal type object to an integer type object will be reported as an error. Specify /optionstrict- if you want to use permissive type semantics.

Example

Compile test.vb using strict type semantics:

vbc /optionstrict+ test.vb

See Also

Visual Basic Compiler Options


/out (Set Output Filename)

Specifies the name of the output file. /out:filename

Arguments

filename
The name of the output file created by the compiler.

Remarks

The compiler expects to find one or more source code files following the /out option.

If you do not specify the name of the output file:

  • A .exe will take its name from the source code file that contains the Sub Main procedure.
  • A .dll will take its name from the first source code file.

On the command line, it is possible to specify multiple output files for your compilation. All source code files specified after an /out option will be compiled into the output file specified by that /out option. A source code file used to compile one output file cannot be used in the same compilation for the compilation of another output file.

Specify the full name and extension of the file you want to create.

Example

Compile t2.vb and create output file t2.exe:

vbc t2.vb /out:t3.exe

See Also

Visual Basic Compiler Options


/recurse (Find Source Files in Subdirectories)

Compiles source code files in all child directories of either the specified directory (dir) or of the project directory /recurse:[dir\]file

Arguments

dir (optional)
The directory in which you want the search to begin. If this is not specified, the search begins in the project directory.
file
The file(s) to search for. Wildcard characters are allowed.

Remarks

You can use wildcards in a file name to compile all matching files in the project directory without using /recurse. If no output file name is specified, the compiler will base the output file name on the first input file processed. This will generally be first file in the list of files compiled when viewed alphabetically. For this reason, it is best to specify an output file by using the /out option.

Example

Compiles all VB files in the current directory:

vbc *.vb

Compiles all of the Visual Basic files in the Microsoft\WFC directory and any directories below it and generates Microsoft.WFC.dll:

vbc /target:library /out:Microsoft.WFC.dll /recurse:Microsoft\WFC\*.vb

See Also

Visual Basic Compiler Options


/reference (Import Metadata)

Causes the compiler to make Public type information in the specified files available to the project you are currently compiling. /reference:file[;file2]

Arguments

file[;file2]
One or more files that contains an assembly manifest. To import more than one file, separate file names with either a comma or a semicolon. The compiler will look for file anywhere specified by the PATH environment variable.

Remarks

The file(s) you import must contain a manifest; the output file must have been compiled with one of the /target options other than /target:module.

/r is the short form of /reference.

Example

Compile source file input.vb and import metadata from metad1.dll and metad2.dll to produce out.exe:

vbc /reference:metad1.dll;metad2.dll /out:out.exe input.vb

See Also

Visual Basic Compiler Options


/removefpchecks (Remove Floating-Point Error Checks)

Turns on or off the error checking for floating-point operations.

/removefpchecks [+| -]

Remarks

The default for this option is /removefpchecks-, which causes the compiler to check all floating point calculations for errors such as overflow or division by zero.

Specifying /removefpchecks or /removefpchecks+ prevents error checking and can make floating-point calculations faster. However, without error checking, incorrect results may be stored without raising an error if data type capacities are overflowed.

Example

Compile test.vb and turn off floating-point error checking:

vbc /removefpchecks+ test.vb

See Also

Visual Basic Compiler Options | /removeintchecks


/removeintchecks (Remove Integer-Overflow Checks)

Turns on or off overflow error checking for integer operations

/removeintchecks [+ | -]

Remarks

The default for this option is /removeintchecks-, which causes the compiler to check all integer calculations for errors such as overflow or division by zero.

Specifying / removeintchecks or / removeintchecks + prevents error checking and can make integer calculations faster. However, without error checking, incorrect results may be stored without raising an error if data type capacities are overflowed.

Example

Compile test.vb and turn off integer overflow error checking:

vbc /removeintchecks+ test.vb

See Also

Visual Basic Compiler Options | /removefpchecks


/resource (Embed Resource File to Output)

Embeds a resource to the output file in an assembly. /resource:filename[,identifier]

-or-

/res:filename[,identifier]

Arguments

filename
The resource file you want to embed in the output file.
identifier (optional)
The logical name for the resource; the name used to load the resource. The default is the name of the file name.

Remarks

Use the /linkresource option to link a resource to an assembly and not place the resource file in the output file.

/resource requires one of the /target options other than /target:module.

NGWS runtime resources can be accessed with members in the System.Resources namespace.

Example

Compile in.vb and attach resource file rf.resource:

vbc /res:rf.resource in.vb

See Also

Visual Basic Compiler Options | /win32resource


/target (Specify Output File Format)

Specifies the format of compiler output. The /target compiler option can be specified in one of four forms:
/target:exe
Create an .exe console application.
/target:library
Create a code library (DLL file).
/target:module
Create a module.
/target:winexe
Create a Windows program. This is the default if you do not specify the target option.

Unless you specify /target:module, /target causes a NGWS runtime Assembly manifest to be placed in an output file.

The assembly manifest is placed in the first .exe output file in the compilation or in the first .dll, if there is no .exe output file. For example, in the following command line, the manifest will be placed in 1.exe:

vbc /out:1.exe t1.vb /out:2.exe t2.vb

The compiler creates only one assembly manifest per compilation. Information about all files in a compilation is placed in the assembly manifest. All output files except those created with /target:module can contain an assembly manifest. When producing multiple output files at the command line, only one assembly manifest can be created and it must go into the first output file specified on the command line. If the first output file is an exe (/target:exe or /target:winexe) or code library (/target:library), then any other output files produced in the same compilation must be modules (/target:module).

See Also

Visual Basic Compiler Options


/target:exe (Create Console Application)

Causes the compiler to create an executable (EXE) console application. /target:exe

-or-

/t:exe

Remarks

The executable file will be created with the .exe extension.

Use /target:winexe/target:winexe to create a Windows program executable.

Unless otherwise specified with the /out option, the output file name takes the name of the input file that contains the Sub Main procedure.

When specified at the command line, all files up to the next /out, /target:winexe, or /target:library option are used to create the .exe. The /target:exe option is in effect for all files since the previous /out or /target:library option.

Only one Sub Main procedure is required in the source code files that are compiled into an .exe. The /main compiler option lets you specify which class contains the Sub Main procedure.

Example

Each of the following command lines will compile in.vb, creating a Windows program called in.exe:

vbc /target:winexe in.vb
vbc in.vb

See Also

/target (Specify Output File Format) | Visual Basic Compiler Options


/target:library (Create a Code Library)

Causes the compiler to create a DLL rather than an executable file (EXE). /target:library

-or-

/t:library

Remarks

The DLL will be created with the .dll extension.

Unless otherwise specified with the /out option, the output file name takes the name of the first input file.

When specified at the command line, all files up to the next /out, /target:winexe/target:winexe, or /target:exe option are used to create the .dll.

When building a .dll, a Sub Main procedure is not required.

Example

Compile in.vb, creating in.dll:

vbc /target:library in.vb

See Also

/target (Specify Output File Format) | Visual Basic Compiler Options


/target:module (Create Module to Add to Assembly)

Causes the compiler to generate a module that can be added to an assembly. /target:module

-or-

/t:module

Remarks

The output file will have an extension of .dll.

A file that does not have an assembly cannot be loaded by the NGWS runtime runtime. However, such a file can be incorporated into the assembly manifest of an assembly via /reference.

If more than one module is created in a single compilation, internal types in one module will be available to other modules in the compilation. When code in one module references internal types in another module, then both modules must be incorporated into an assembly manifest, via /reference.

Example

Compile in.vb, creating in.dll:

vbc /target:module in.vb

See Also

/target | Visual Basic Compiler Options


/target:winexe (Create a Windows Program)

Causes the compiler to create an executable (EXE) Windows program. /target:winexe

-or-

/t:winexe

Remarks

The target:winexe option is the default when no target option is specified. The executable file will be created with the .exe extension. A Windows program is one that provides a user interface from either the Services Framework class library or with the Win32 APIs.

Use /target:exe to create a console application.

Unless otherwise specified with the /out option, the output file name takes the name of the input file that contains the Sub Main procedure.

When specified at the command line, all files until the next /out or /target option are used to create the Windows program.

Only one Sub Main procedure is required in the source code files that are compiled into a .exe. The /main compiler option lets you specify which class contains the Sub Main procedure, in cases where your code has more than one class with a Sub Main procedure.

Example

Compile in.vb into a Windows program:

vbc /target:winexe in.vb

See Also

/target | Visual Basic Compiler Options


/Time (Display Elapsed Compilation Time)

Causes the compiler to display the amount time the compiler spent compiling a project.

/time [+ -]

Remarks

Use this option when evaluating the impact of various compiler options on compilation speed.

See Also

/optimize | Visual Basic Compiler Options | /verbose


/verbose (Display Verbose Messages)

Causes the compiler to produce verbose status and error messages.

/verbose [+ -]

Remarks

The default for this option is \verbose-.

Specifying \verbose is the same as specifying \verbose+.

Example

Compile in.vb and have the compiler display verbose status information:

vbc /verbose in.vb

See Also

Visual Basic Compiler Options


/warn (Specify Warning Level)

Specifies the warning level, which controls how warnings are displayed. /warn:option

Arguments

option
The minimum warning level you want displayed for the build. Valid values are 0-4:

Warning level | Meaning
0 | Turns off emission of all warning messages.
1 | Displays severe warning messages.
2 | Displays level 1 warnings plus certain, less-severe warnings, such as warnings about hiding class members.
3 | Displays level 2 warnings plus certain, less-severe warnings, such as warnings about expressions that always evaluate to true or false.
4 | Displays all level 3 warnings plus informational warnings. This is the default warning level at the command line.

Remarks

Use /warnaserror to treat all warnings as errors.

/w is the short form of /warn.

Note The /warn option has not yet been implemented in the Visual Basic command line compiler.

Example

Compile in.vb and have the compiler only display level 1 warnings:

vbc /warn:1 in.vb

See Also

Visual Basic Compiler Options | /warnaserror


/warnaserror (Treat Warnings as Errors)

Directs the compiler to treat all warnings as errors. /warnaserror[+ | -]

Remarks

Any messages that would ordinarily be reported as warnings are instead reported as errors, and the build process is halted (no output files are built).

By default, /warnaserror- is in effect, which causes warnings to not prevent the generation of an output file. /warnaserror, which is the same as /warnaserror+, causes warnings to be treated as errors.

Use /warn to specify the level of warnings that you want the compiler to display.

Note The /warnaserror option has not yet been implemented in the Visual Basic command line compiler.

Example

Compile in.vb and have the compiler display no warnings:

vbc /warnaserror in.vb

See Also

Visual Basic Compiler Options | /warn


/win32icon (Import a .ico File)

Inserts a .ico file in the output file, which gives the output file the desired appearance in the Windows Explorer. /win32icon:filename

Arguments

filename
The .ico file that you want to add to your output file.

Remarks

A .ico file can be created with the Resource Compiler. The Resource Compiler is invoked when you compile a Visual C++ program; a .ico file is created from the .rc file. The /win32icon and the /win32resource options are mutually exclusive.

See /linkresource (to reference) or /resource (to attach) a NGWS runtime resource file. See /win32resource to import a .res file.

Example

Compile in.vb and attach a .ico file rf.ico to produce in.exe:

vbc /win32icon:rf.ico in.vb

See Also

Visual Basic Compiler Options


/win32resource (Import a Win32 Resource File)

Inserts a Win32 resource in the output file. /win32resource:filename

Arguments

filename
The resource file that you want to add to your output file.

Remarks

A Win32 resource file can be created with the Resource Compiler. The Resource Compiler is invoked when you compile a Visual C++ program; a .res file is created from the .rc file.

A Win32 resource can contain version or bitmap (icon) information that would help identify your application in the Windows Explorer. If you do not specify /win32resorce, the compiler will generate version information based on the assembly version. The /win32resource and /win32icon options are mutually exclusive.

See /linkresource (to reference) or /resource (to attach) a NGWS runtime resource file.

Example

Compile in.vb and attach a Win32 resource file rf.res to produce in.exe:

vbc /win32resource:rf.res in.vb

See Also

Visual Basic Compiler Options


Topic Not Found

No matching topic was found. Some possible reasons and remedies are as follows:

Reason | Remedy
Destination topic is not in the selected active subset. | Set active subset to an appropriate subset or to (Entire Collection).
Link is out-of-date. | Use the index or search function instead.
Link was authored incorrectly. | Use the index or search function instead.
Problems with the MSDN installation. | Uninstall the MSDN Library and then rerun Setup.

See MSDN Library Help for information on subsets, search, the index, and installation.


ActiveX object <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

ActiveX object

An object that is exposed to other applications or programming tools through Automation interfaces.


ANSI Character Set <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

ANSI Character Set

American National Standards Institute (ANSI) 8-bit character set used to represent up to 256 characters (0–255) using your keyboard. The first 128 characters (0–127) correspond to the letters and symbols on a standard U.S. keyboard. The second 128 characters (128–255) represent special characters, such as letters in international alphabets, accents, currency symbols, and fractions.


argument <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

argument

A constant, variable, or expression passed to a procedure.


array <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

array

A set of sequentially indexed elements having the same intrinsic data type. Each element of an array has a unique identifying index number. Changes made to one element of an array don't affect the other elements.


ASCII Character Set <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

ASCII Character Set

American Standard Code for Information Interchange (ASCII) 7-bit character set used to represent letters and symbols found on a standard U.S. keyboard. The ASCII character set is the same as the first 128 characters (0–127) in the ANSI character set.


bitwise comparison <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

bitwise comparison

A bit-by-bit comparison between identically positioned bits in two numeric expressions.


Boolean expression <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Boolean expression

An expression that evaluates to either True or False.


Boolean data type <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Boolean data type

A data type with only two possible values, True (-1) or False (0). Boolean variables are stored as 16-bit (2-byte) numbers.


break mode <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

break mode

Temporary suspension of program execution in the development environment. In break mode, you can examine, debug, reset, step through, or continue program execution. You enter break mode when you:
  • Encounter a breakpoint during program execution.
  • Press CTRL+BREAK+BREAK during program execution.
  • Encounter a Stop statement or untrapped run-time error during program execution.
  • Add a Break When True watch expression. Execution stops when the value of the watch changes and evaluates to True.
  • Add a Break When Changed watch expression. Execution stops when the value of the watch changes.


breakpoint <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

breakpoint

A selected program line at which execution automatically stops. Breakpoints are not saved with your code.


by reference <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

by reference

A way of passing the address of an argument to a procedure instead of passing the value. This allows the procedure to access the actual variable. As a result, the variable's actual value can be changed by the procedure to which it is passed. Unless otherwise specified, arguments are passed by reference.


Byte data type <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Byte data type

A data type used to hold positive integer numbers ranging from 0–255. Byte variables are stored as single, unsigned 8-bit (1-byte) numbers.


by value <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

by value

A way of passing the value of an argument to a procedure instead of passing the address. This allows the procedure to access a copy of the variable. As a result, the variable's actual value can't be changed by the procedure to which it is passed.


character code <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

character code

A number that represents a particular character in a set, such as the ANSI ASCII character set.


class <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

class

The formal definition of an object. The class acts as the template from which an instance of an object is created at run time. The class defines the properties of the object and the methods used to control the object's behavior.


collection <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

collection

An object that contains a set of related objects. An object's position in the collection can change whenever a change occurs in the collection; therefore, the position of any specific object in the collection can vary.


command line <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

command line

The path, file name, and argument information provided by the user to run a program.


comment <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

comment

Text added to code that explains how the code works. In Visual Basic, a comment line can start with either an apostrophe (') or with the Rem keyword followed by a space.


comparison operator <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

comparison operator

A character or symbol indicating a relationship between two or more values or expressions. These operators include less than (<), less than or equal to (<=), greater than (>), greater than or equal to (>=), not equal (<>), and equal (=). Additional comparison operators include Is and Like. Note that Is and Like can't be used as comparison operators in a Select Case statement.


compile time <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

compile time

The period during which source code is translated to executable code.


conditional compiler constant <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

conditional compiler constant

A Visual Basic identifier that is defined using the #Const compiler directive or defined in the host application and used by other compiler directives to determine when or if certain blocks of Visual Basic code are compiled.


constant <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

constant

A named item that retains a constant value throughout the execution of a program. A constant can be a string or numeric literal, another constant, or any combination that includes arithmetic or logical operators except Is and exponentiation. Each host application can define its own set of constants. Additional constants can be defined by the user with the Const statement. You can use constants anywhere in your code in place of actual values.


control array <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

control array

A group of controls that share a common name, type, and event procedures. Each control in an array has a unique index number that can be used to determine which control recognizes an event.


Returns for CStr

If expression is | CStr returns
Boolean | A string containing True or False
Date | A string containing a date in the short date format of your system
Null | A run-time error
Empty | A zero-length string ("")
Error | A string containing the word Error followed by the error number
Other numeric | A string containing the number

See Also


data type <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

data type

The characteristic of a variable that determines what kind of data it can hold. Data types include Byte, Boolean, Integer, Long, Currency, Decimal, Single, Double, Date, String, Object, Variant (default), and user-defined types, as well as specific types of objects.


Date data type <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Date data type

A data type used to store dates and times as a real number. Date variables are stored as 64-bit (8-byte) numbers. The value to the left of the decimal represents a date, and the value to the right of the decimal represents a time.


date expression <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

date expression

Any expression that can be interpreted as a date, including date literals, numbers that look like dates, strings that look like dates, and dates returned from functions. A date expression is limited to numbers or strings, in any combination, that can represent a date from January 1, 100 – December 31, 9999.

Dates are stored as part of a real number. Values to the left of the decimal represent the date; values to the right of the decimal represent the time. Negative numbers represent dates prior to December 30, 1899.


date literal <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

date literal

Any sequence of characters with a valid format that is surrounded by number signs (#). Valid formats include the date format specified by the locale settings for your code or the universal date format.

For example, #12/31/92# is the date literal that represents December 31, 1992, where English-U.S. is the locale setting for your application. Use date literals to maximize portability across national languages.


date separators <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

date separators

Characters used to separate the day, month, and year when date values are formatted. The characters are determined by system settings or by the Format function.


DBCS <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

DBCS

A character set that uses 1 or 2 bytes to represent a character, allowing more than 256 characters to be represented.


Decimal data type <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Decimal data type

A data type that contains decimal numbers scaled by a power of 10. For zero-scaled numbers, that is, numbers with no decimal places, the range is +/-79,228,162,514,264,337,593,543,950,335. For numbers with 28 decimal places the range is +/-7.9228162514264337593543950335. The smallest non-zero number that can be represented as a Decimal is 0.0000000000000000000000000001.

Note that at this time the Decimal data type can only be used within a Variant. You cannot declare a variable to be of type Decimal. You can, however, create a Variant whose subtype is Decimal using the CDec function.


declaration <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

declaration

Nonexecutable code that names a constant, variable, or procedure, and specifies its characteristics, such as data type. For DLL proceduresexternal declarations, declarations specify names, libraries, and arguments.


design time <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

design time

The time during which you build an application in the development environment by adding controls, setting control or form properties, and so on. In contrast, during run time, you interact with the application like a user.


development environment <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

development environment

The part of the application where you write code, create controls, set control and form properties, and so on. This contrasts with running the application.


dynamic-link library (DLL) <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

dynamic-link library (DLL)

A library of routines loaded and linked into applications at run time. DLLs are created with other programming languages such as C, MASM, or FORTRAN.


Double data type <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Double data type

A data type that holds double-precision floating-point numbers as 64-bit numbers in the range -1.79769313486231E308 to -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values. The number sign (#) type-declaration character represents the Double in Visual Basic.


Empty <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Empty

Indicates that no beginning value has been assigned to a Variant variable. An Empty variable is represented as 0 in a numeric context or a zero-length string ("") in a string context.


error number <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

error number

A whole number in the range 0 – 65,535 that corresponds to the Number property setting of the Err object. When combined with the Description property setting of the Err object, this number represents a particular error message.


executable file <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

executable file

An Windows-based application that can run outside the development environment. An executable file has an .exe file name extension.


expression <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

expression

A combination of keywords, operators, variables, and constants that yields a string, number, or object. An expression can be used to perform a calculation, manipulate characters, or test data.


file number <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

file number

Number used in the Open statement to open a file. Use file numbers in the range 1–255, inclusive, for files not accessible to other applications. Use file numbers in the range 256–511 for files accessible from other applications.


form <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

form

A window or dialog box. Forms are containers for controls. A multiple-document interface (MDI) form can also act as a container for child forms and some controls.


form module <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

form module

A file in a Visual Basic project with an .frm file name extension that can contain graphical descriptions of a form; its controls and their property settings; form-level declarations of constants, variables, and external procedures; and event and general procedures.


Function procedure <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Function procedure

A procedure that performs a specific task within a program and returns a value. A Function procedure begins with a Function statement and ends with an End Function statement.


host application <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

host application

Any application that supports the use of Visual Basic for Applications, for example, Microsoft Excel, Microsoft Project, and so on.


identifier <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

identifier

An element of an expression that refers to a constant or variable.


Integer data type <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Integer data type

A data type that holds integer variables stored as 2-byte whole numbers in the range -32,768 to 32,767. The Integer data type is also used to represent enumerated values. The percent sign (%) type-declaration character represents an Integer in Visual Basic.


keyword <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

keyword

A word or symbol recognized as part of the Visual Basic programming language; for example, a statement, function name, or operator.


line label <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

line label

Used to identify a single line of code. A line label can be any combination of characters that starts with a letter and ends with a colon (:). Line labels are not case sensitive and must begin in the first column.


line number <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

line number

Used to identify a single line of code. A line number can be any combination of digits that is unique within the module where it is used. Line numbers must begin in the first column.


locale <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

locale

The set of information that corresponds to a given language and country. The code locale setting affects the language of terms such as keywords and defines locale-specific settings such as the decimal and list separators, date formats, and character sorting order.

The system locale setting affects the way locale-aware functionality behaves, for example, when you display numbers or convert strings to dates. You set the system locale using the Control PanelControl Panels utilities provided by the operating system.

Although the code locale and system locale are generally set to the same setting, they may differ in some situations. For example, in Visual Basic, Standard Edition and Visual Basic, Professional Edition, the code is not translated from English-U.S. The system locale can be set to the user's language and country, but the code locale is always set to English-U.S. and can't be changed. In this case, the English-U.S. separators, format placeholders, and sorting order are used.


Long data type <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Long data type

A 4-byte integer ranging in value from -2,147,483,648 to 2,147,483,647. The ampersand (&) type-declaration character represents a Long in Visual Basic.


member <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

member

An element of a collection, object, or user-defined type.


method <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

method

A procedure that acts on an object.


module <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

module

A set of declarations followed by procedures.


module level <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

module level

Describes code in the Declarations section of a module. Any code outside a procedure is referred to as module-level code. Declarations must be listed first, followed by procedures.


named argument <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

named argument

An argument that has a name that is predefined in the object library. Instead of providing a value for each argument in a specified order expected by the syntax, you can use named arguments to assign values in any order. For example, suppose a method accepts three arguments:

DoSomeThing namedarg1, namedarg2, namedarg3

By assigning values to named arguments, you can use the following statement:

DoSomeThing namedarg3 := 4, namedarg2 := 5, namedarg1 := 20

Note that the named arguments don't have to appear in the normal positional order in the syntax.


Null <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Null

A value indicating that a variable contains no valid data. Null is the result of an explicit assignment of Null to a variable or any operation between expressions that contain Null.


numeric data type <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

numeric data type

Any intrinsic numeric data type (Byte, Boolean, Integer, Long, Currency, Single, Double, or Date).


numeric expression <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

numeric expression

Any expression that can be evaluated as a number. Elements of an expression can include any combination of keywords, variables, constants, and operators that result in a number.


numeric type <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

numeric type

Any intrinsic numeric data type (Byte, Boolean, Integer, Long, Currency, Single, Double, or Date) or any Variant numeric subtype (Empty, Integer, Long, Single, Double, Currency, Decimal, Date, Error, Boolean, or Byte).


object <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

object

A combination of code and data that can be treated as a unit, for example, a control, form, or application component. Each object is defined by a class.


Object Browser <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Object Browser

A dialog box in which you can examine the contents of an object library to get information about the objects provided.


Object data type <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Object data type

A data type that represents any Object reference. Object variables are stored as 32-bit (4-byte) addresses that refer to objects.


object expression <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

object expression

An expression that specifies a particular object and can include any of the object's containers. For example, an application can have an Application object that contains a Document object that contains a Text object.


object library <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

object library

A file with the .olb extension that provides information to Automation controllers (like Visual Basic) about available objects. You can use the Object Browser to examine the contents of an object library to get information about the objects provided.


object type <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

object type

A type of object exposed by an application through Automation, for example, Application, File, Range, and Sheet. Use the Object Browser or refer to the application's documentation for a complete listing of available objects.


object variable <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

object variable

A variable that contains a reference to an object.


OLE Automation object <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Automation object

An object that is exposed to other applications or programming tools through Automation interfaces.


parameter <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

parameter

Variable name by which an argument passed to a procedure is known within the procedure. This variable receives the argument passed into the procedure. Its scope ends when the procedure ends.


pi <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

pi

A mathematical constant equal to approximately 3.1415926535897932.


print zone <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

print zone

Print zones begin every 14 columns. The width of each column is an average of the width of all characters in the point size for the selected font.


Private <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Private

Variables that are visible only to the module in which they are declared.


procedure <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

procedure

A named sequence of statements executed as a unit. For example, Function, Property, and Sub are types of procedures. A procedure name is always defined at module level. All executable code must be contained in a procedure. Procedures can't be nested within other procedures.


Procedure box <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Procedure box

A list box at the upper-right corner of the Code window and the Debug window that displays the procedures recognized for the object displayed in the Object box.


procedure level <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

procedure level

Describes statements located within a Function, Property, or Sub procedure. Declarations are usually listed first, followed by assignments and other executable code.

Note that module-level code resides outside a procedure block.


project <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

project

A set of modules.


property <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

property

A named attribute of an object. Properties define object characteristics such as size, color, and screen location, or the state of an object, such as enabled or disabled.


Public <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Public

Variables declared using the Public statement are visible to all procedures in all modules in all applications unless Option Private Module is in effect. In that case, the variables are public only within the project in which they reside.


registry <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

registry

In Microsoft Windows version 3.1, OLE registration information and file associations are stored in the registration database, and program settings are stored in Windows system initialization (.ini) files. In Microsoft Windows 95, the Windows registry serves as a central configuration database for user, application, and computer-specific information, including the information previously contained in both the Windows version 3.1 registration database and .ini files. On the Macintosh, a registration database that is saved in the Preferences folder stores files that contain data about program and application settings.


run-time error <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

run-time error

An error that occurs when code is running. A run-time error results when a statement attempts an invalid operation.


run time <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

run time

The time during which code is running. During run time, you can't edit the code.


scope <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

scope

Defines the visibility of a variable, procedure, or object. For example, a variable declared as Public is visible to all procedures in all modules in a directly referencing project unless Option Private Module is in effect. When Option Private Module is in effect, the module itself is private and therefore not visible to referencing projects. Variables declared in a procedure are visible only within the procedure and lose their value between calls unless they are declared Static.


seed <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

seed

An initial value used to generate pseudorandom numbers. For example, the Randomize statement creates a seed number used by the Rnd function to create unique pseudorandom number sequences.


Single data type <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Single data type

A data type that stores single-precision floating-point variables as 32-bit (4-byte) floating-point numbers, ranging in value from -3.402823E38 to -1.401298E-45 for negative values, and 1.401298E-45 to 3.402823E38 for positive values. The exclamation point (!) type-declaration character represents a Single in Visual Basic.


sort order <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

sort order

A sequencing principle used to order data, for example, alphabetic, numeric, ascending, descending, and so on.


standard module <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

standard module

A module containing only procedure, type, and data declarations and definitions. Module-level declarations and definitions in a standard module are Public by default. A standard module is referred to as a code module in earlier versions of Visual Basic.


statement <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

statement

A syntactically complete unit that expresses one kind of action, declaration, or definition. A statement generally occupies a single line, although you can use a colon (:) to include more than one statement on a line. You can also use a line-continuation character (_) to continue a single logical line onto a second physical line.


string comparison <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

string comparison

A comparison of two sequences of characters. Use Option Compare to specify binary or text comparison. In English-U.S., binary comparisons are case sensitive; text comparisons are not.


String data type <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

String data type

A data type consisting of a sequence of contiguous characters that represent the characters themselves rather than their numeric values. A String can include letters, numbers, spaces, and punctuation. The String data type can store fixed-length strings ranging in length from 0 to approximately 63K characters and dynamic strings ranging in length from 0 to approximately 2 billion characters. The dollar sign ($) type-declaration character represents a String in Visual Basic.


string expression <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

string expression

Any expression that evaluates to a sequence of contiguous characters. Elements of a string expression can include a function that returns a string, a string literal, a string constant, a string variable, a string Variant, or a function that returns a string Variant (VarType 8).


string literal <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

string literal

Any expression consisting of a sequence of contiguous characters surrounded by quotation marks that is literally interpreted as the characters within the quotation marks.


type library <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

type library

A file or component within another file that contains standard descriptions of exposed objects, properties, and methods that are available for Automation. Object library files (.olb) contain type libraries.


Unicode <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Unicode

International Standards Organization (ISO) character standard. Unicode uses a 16-bit (2-byte) coding scheme that allows for 65,536 distinct character spaces. Unicode includes representations for punctuation marks, mathematical symbols, and dingbats, with substantial room for future expansion.


universal date format <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

universal date format

The universal date format is #yyyy-mm-dd hh:mm:ss#. However, both the date component (#yyyy-mm-dd#) and the time component (#hh:mm:ss#) can be represented separately.


user-defined type <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

user-defined type

Any data type defined using the Type statement. User-defined data types can contain one or more elements of any data type. Arrays of user-defined and other data types are created using the Dim statement. Arrays of any type can be included within user-defined types.


variable <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

variable

A named storage location that can contain data that can be modified during program execution. Each variable has a name that uniquely identifies it within its scope. A data type can be specified or not.

Variable names must begin with an alphabetic character, must be unique within the same scope, can't be longer than 255 characters, and can't contain an embedded period or type-declaration character.


Variant data type <definition>

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Variant data type

A special data type that can contain numeric, string, or date data as well as user-defined types and the special values Empty and Null. The Variant data type has a numeric storage size of 16 bytes and can contain data up to the range of a Decimal, or a character storage size of 22 bytes (plus string length), and can store any character text. The VarType function defines how the data in a Variant is treated. All variables become Variant data types if not explicitly declared as some other data type.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CBool Function

[Topic intentionally blank - content coming in later builds]


CBool Function Example

This example uses the CBool function to convert an expression to a Boolean. If the expression evaluates to a nonzero value, CBool returns True; otherwise, it returns False.

Dim A, B, Check
A = 5: B = 5   ' Initialize variables.
Check = CBool(A = B)   ' Check contains True.

A = 0   ' Define variable.
Check = CBool(A)   ' Check contains False.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CByte Function

[Topic intentionally blank - content coming in later builds]


CByte Function Example

This example uses the CByte function to convert an expression to a Byte.

Dim MyDouble, MyByte
MyDouble = 125.5678   ' MyDouble is a Double.
MyByte = CByte(MyDouble)   ' MyByte contains 126.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CChar Function

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CChar Function Example

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CCur Function

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CDate Function

[Topic intentionally blank - content coming in later builds]


CDate Function Example

This example uses the CDate function to convert a string to a Date. In general, hard-coding dates and times as strings (as shown in this example) is not recommended. Use date literals and time literals, such as #2/12/1969# and #4:45:23 PM#, instead.

Dim MyDate, MyShortDate, MyTime, MyShortTime
MyDate = "February 12, 1969"   ' Define date.
MyShortDate = CDate(MyDate)   ' Convert to Date data type.

MyTime = "4:35:47 PM"   ' Define time.
MyShortTime = CDate(MyTime)   ' Convert to Date data type.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CDbl Function

[Topic intentionally blank - content coming in later builds]


CDbl Function Example

This example uses the CDbl function to convert an expression to a Double.

Dim MyCurr, MyDouble
MyCurr = CCur(234.456784)   ' MyCurr is a Currency.
MyDouble = CDbl(MyCurr * 8.2 * 0.01)   ' Convert result to a Double.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CDec Function

[Topic intentionally blank - content coming in later builds]


CDec Function Example

This example uses the CDec function to convert a numeric value to a Decimal.

Dim MyDecimal, MyCurr
MyCurr = 10000000.0587   ' MyCurr is a Currency.
MyDecimal = CDec(MyCurr)    ' MyDecimal is a Decimal.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CInt Function

[Topic intentionally blank - content coming in later builds]


CInt Function Example

This example uses the CInt function to convert a value to an Integer.

Dim MyDouble, MyInt
MyDouble = 2345.5678   ' MyDouble is a Double.
MyInt = CInt(MyDouble)   ' MyInt contains 2346.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CLng Function

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CLng8 Function

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CLng8 Function Example

[Topic intentionally blank - content coming in later builds]


CLng Function Example

This example uses the CLng function to convert a value to a Long.

Dim MyVal1, MyVal2, MyLong1, MyLong2
MyVal1 = 25427.45: MyVal2 = 25427.55   ' MyVal1, MyVal2 are Doubles.
MyLong1 = CLng(MyVal1)   ' MyLong1 contains 25427.
MyLong2 = CLng(MyVal2)   ' MyLong2 contains 25428.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CSng Function

[Topic intentionally blank - content coming in later builds]


CSng Function Example

This example uses the CSng function to convert a value to a Single.

Dim MyDouble1, MyDouble2, MySingle1, MySingle2
' MyDouble1, MyDouble2 are Doubles.
MyDouble1 = 75.3421115: MyDouble2 = 75.3421555
MySingle1 = CSng(MyDouble1)   ' MySingle1 contains 75.34211.
MySingle2 = CSng(MyDouble2)   ' MySingle2 contains 75.34216.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CStr Function

[Topic intentionally blank - content coming in later builds]


CStr Function Example

This example uses the CStr function to convert a numeric value to a String.

Dim MyDouble, MyString
MyDouble = 437.324   ' MyDouble is a Double.
MyString = CStr(MyDouble)   ' MyString contains "437.324".


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CVar Function

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

CVDate Function

[Topic intentionally blank - content coming in later builds]


Date Function Example

This example uses the Date function to return the current system date.

Dim MyDate
MyDate = Date   ' MyDate contains the current system date.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Fix Function

[Topic intentionally blank - content coming in later builds]


Format Function Example

This example shows various uses of the Format function to format values using both named formats and user-defined formats. For the date separator (/), time separator (:), and AM/ PM literal, the actual formatted output displayed by your system depends on the locale settings on which the code is running. When times and dates are displayed in the development environment, the short time format and short date format of the code locale are used. When displayed by running code, the short time format and short date format of the system locale are used, which may differ from the code locale. For this example, English/U.S. is assumed.

MyTime and MyDate are displayed in the development environment using current system short time setting and short date setting.

Dim MyTime, MyDate, MyStr
MyTime = #17:04:23#
MyDate = #January 27, 1993#

' Returns current system time in the system-defined long time format.
MyStr = Format(Time, "Long Time")

' Returns current system date in the system-defined long date format.
MyStr = Format(Date, "Long Date")

MyStr = Format(MyTime, "h:m:s")   ' Returns "17:4:23".
MyStr = Format(MyTime, "hh:mm:ss AMPM")   ' Returns "05:04:23 PM".
MyStr = Format(MyDate, "dddd, mmm d yyyy")   ' Returns "Wednesday,
   ' Jan 27 1993".
' If format is not supplied, a string is returned.
MyStr = Format(23)   ' Returns "23".

' User-defined 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("HELLO", "<")   ' Returns "hello".
MyStr = Format("This is it", ">")   ' Returns "THIS IS IT".


Input Function Example

This example uses the Input function to read one character at a time from a file and print it to the Immediate window. This example assumes that TESTFILE is a text file with a few lines of sample data.

Dim MyChar
Open "TESTFILE" For Input As #1   ' Open file.
Do While Not EOF(1)   ' Loop until end of file.
   MyChar = Input(1, #1)   ' Get one character.
   Debug.Print MyChar   ' Print to the Immediate window.
Loop
Close #1   ' Close file.


InStr Function Example

This example uses the InStr function to return the position of the first occurrence of one string within another.

Dim SearchString, SearchChar, MyPos
SearchString ="XXpXXpXXPXXP"   ' String to search in.
SearchChar = "P"   ' Search for "P".

' A textual comparison starting at position 4. Returns 6.
MyPos = Instr(4, SearchString, SearchChar, 1)

' A binary comparison starting at position 1. Returns 9.
MyPos = Instr(1, SearchString, SearchChar, 0)

' Comparison is binary by default (last argument is omitted).
MyPos = Instr(SearchString, SearchChar)   ' Returns 9.

MyPos = Instr(1, SearchString, "W")   ' Returns 0.


Month Function Example

This example uses the Month function to obtain the month from a specified date. In the development environment, the date literal is displayed in short date format using the locale settings of your code.

Dim MyDate, MyMonth
MyDate = #February 12, 1969#   ' Assign a date.
MyMonth = Month(MyDate)   ' MyMonth contains 2.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

RTrim Function

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

RTrim$ Function

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Str$ Function

[Topic intentionally blank - content coming in later builds]


Str Function Example

This example uses the Str function to return a string representation of a number. When a number is converted to a string, a leading space is always reserved for its sign.

Dim MyString
MyString = Str(459)   ' Returns " 459".
MyString = Str(-459.65)   ' Returns "-459.65".
MyString = Str(459.001)   ' Returns " 459.001".


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Time$ Function

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Time Function Example

This example uses the Time function to return the current system time.

Dim MyTime
MyTime = Time   ' Return current system time.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Trim Function

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Trim$ Function

[Topic intentionally blank - content coming in later builds]


VB6.Date Function

Returns a String containing the current system date.

Date

Remarks

To set the system date, use the VB6.date statement.

Date, and if the calendar is Gregorian, Date$ behavior is unchanged by the Calendar property setting. If the calendar is Hijri, Date$ returns a 10-character string of the form mm-dd-yyyy, where mm (01-12), dd (01-30) and yyyy (1400-1523) are the Hijri month, day and year. The equivalent Gregorian range is Jan 1, 1980 through Dec 31, 2099.

See Also

Example


Weekday Function Example

This example uses the Weekday function to obtain the day of the week from a specified date.

Dim MyDate, MyWeekDay
MyDate = #February 12, 1969#   ' Assign a date.
MyWeekDay = Weekday(MyDate)   ' MyWeekDay contains 4 because
   ' MyDate represents a Wednesday.


Different Formats for Different Numeric Values (Format Function)

A user-defined format expression for numbers can have from one to four sections separated by semicolons. If the format argument contains one of the named numeric formats, only one section is allowed.

If you use | The result is
One section only | The format expression applies to all values.
Two sections | The first section applies to positive values and zeros, the second to negative values.
Three sections | The first section applies to positive values, the second to negative values, and the third to zeros.

The following example has two sections: the first defines the format for positive values and zeros; the second section defines the format for negative values.

"$#,##0;($#,##0)"

If you include semicolons with nothing between them, the missing section is printed using the format of the positive value. For example, the following format displays positive and negative values using the format in the first section and displays "Zero" if the value is zero.

"$#,##0;;\Z\e\r\o"

See Also

Different Formats for Different String Values (Format Function) | Format Function


Different Formats for Different String Values (Format Function)

A format expression for strings can have one section or two sections separated by a semicolon (;).

If you use | The result is
One section only | The format applies to all string data.
Two sections | The first section applies to string data, the second to zero-length strings ("").

See Also

Different Formats for Different Numeric Values (Format Function) | Format Function


Named Date/Time Formats (Format Function)

The following table identifies the predefined date and time format names:

Format Name | Description
General Date | Display a date and/or time. For real numbers, display a date and time, for example, 4/3/93 05:34 PM.If there is no fractional part, display only a date, for example, 4/3/93. If there is no integer part, display time only, for example, 05:34 PM. Date display is determined by your locale.
Long Date | Display a date according to your locale's long date format.
Medium Date | Display a date using the medium date format appropriate for the language version of the host application.
Short Date | Display a date using your locale's short date format.
Long Time | Display a time using your locale's long time format; includes hours, minutes, seconds.
Medium Time | Display time in 12-hour format using hours and minutes and the AM/PM designator.
Short Time | Display a time using the 24-hour format, for example, 17:45.

See Also

Format Function | Named Numeric Formats (Format Function) | User-Defined Date/Time Formats (Format Function)


Named Numeric Formats (Format Function)

The following table identifies the predefined numeric format names:

Format name | Description
General Number | Display number with no thousand separator.
Currency | Display number with thousand separator, if appropriate; display two digits to the right of the decimal separator. Output is based on system locale settings.
Fixed | Display at least one digit to the left and two digits to the right of the decimal separator.
Standard | Display number with thousand separator, at least one digit to the left and two digits to the right of the decimal separator.
Percent | Display number multiplied by 100 with a percent sign (%) appended to the right; always display two digits to the right of the decimal separator.
Scientific | Use standard scientific notation.
Yes/No | Display No if number is 0; otherwise, display Yes.
True/False | Display False if number is 0; otherwise, display True.
On/Off | Display Off if number is 0; otherwise, display On.

See Also

Format Function | Named Date/Time Formats (Format Function) | User-Defined Numeric Formats (Format Function)


User-Defined String Formats (Format Function)

You can use any of the following characters to create a format expression for strings:

Character | Description
@ | Character placeholder. Display a character or a space. If the string has a character in the position where the at symbol (@) appears in the format string, display it; otherwise, display a space in that position. Placeholders are filled from right to left unless there is an exclamation point character (!) in the format string.
& | Character placeholder. Display a character or nothing. If the string has a character in the position where the ampersand (&) appears, display it; otherwise, display nothing. Placeholders are filled from right to left unless there is an exclamation point character (!) in the format string.
< | Force lowercase. Display all characters in lowercase format.
> | Force uppercase. Display all characters in uppercase format.
! | Force left to right fill of placeholders. The default is to fill placeholders from right to left.

See Also

Different Formats for Different String Values (Format Function) | Format Function | User-Defined Date/Time Formats (Format Function) | User-Defined Numeric Formats (Format Function)


User-Defined Date/Time Formats (Format Function)

The following table identifies characters you can use to create user-defined date/time formats:

Character | Description
(:) | Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by your locale.
(/) | Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by your locale.
c | Display the date as ddddd and display the time as ttttt, in that order. Display only date information if there is no fractional part to the date serial number; display only time information if there is no integer portion.
d | Display the day as a number without a leading zero (1 – 31).
dd | Display the day as a number with a leading zero (01 – 31).
ddd | Display the day as an abbreviation (Sun – Sat).
dddd | Display the day as a full name (Sunday – Saturday).
ddddd | Display the date as a complete date (including day, month, and year), formatted according to your system's short date format setting. The default short date format is m/d/yy.
dddddd | Display a date serial number as a complete date (including day, month, and year) formatted according to the long date setting recognized by your system. The default long date format is mmmm dd, yyyy.
aaaa | The same as dddd, only it's the localized version of the string.
w | Display the day of the week as a number (1 for Sunday through 7 for Saturday).
ww | Display the week of the year as a number (1 – 54).
m | Display the month as a number without a leading zero (1 – 12). If m immediately follows h or hh, the minute rather than the month is displayed.
mm | Display the month as a number with a leading zero (01 – 12). If m immediately follows h or hh, the minute rather than the month is displayed.
mmm | Display the month as an abbreviation (Jan – Dec).
mmmm | Display the month as a full month name (January – December).
oooo | The same as mmmm, only it's the localized version of the string.
q | Display the quarter of the year as a number (1 – 4).
y | Display the day of the year as a number (1 – 366).
yy | Display the year as a 2-digit number (00 – 99).
yyyy | Display the year as a 4-digit number (100 – 9999).
h | Display the hour as a number without leading zeros (0 – 23).
Hh | Display the hour as a number with leading zeros (00 – 23).
N | Display the minute as a number without leading zeros (0 – 59).
Nn | Display the minute as a number with leading zeros (00 – 59).
S | Display the second as a number without leading zeros (0 – 59).
Ss | Display the second as a number with leading zeros (00 – 59).
t t t t t | Display a time as a complete time (including hour, minute, and second), formatted using the time separator defined by the time format recognized by your system. A leading zero is displayed if the leading zero option is selected and the time is before 10:00 A.M. or P.M. The default time format is h:mm:ss.
AM/PM | Use the 12-hour clock and display an uppercase AM with any hour before noon; display an uppercase PM with any hour between noon and 11:59 P.M.
am/pm | Use the 12-hour clock and display a lowercase AM with any hour before noon; display a lowercase PM with any hour between noon and 11:59 P.M.
A/P | Use the 12-hour clock and display an uppercase A with any hour before noon; display an uppercase P with any hour between noon and 11:59 P.M.
a/p | Use the 12-hour clock and display a lowercase A with any hour before noon; display a lowercase P with any hour between noon and 11:59 P.M.
AMPM | Use the 12-hour clock and display the AM string literal as defined by your locale with any hour before noon; display the PM string literal as defined by your system with any hour between noon and 11:59 P.M. AMPM can be either uppercase or lowercase, but the case of the string displayed matches the string as defined by your system settings. The default format is AM/PM.

See Also

Example

Format Function | Named Date/Time Formats (Format Function) | User-Defined Numeric Formats (Format Function) | User-Defined String Formats (Format Function)


User-Defined Date/Time Formats Example

The following are examples of user-defined date and time formats for December 7, 1958:

Format | Display
m/d/yy | 12/7/58
d-mmm | 7-Dec
d-mmmm-yy | 7-December-58
d mmmm | 7 December
mmmm yy | December 58
hh:mm AM/PM | 08:50 PM
h:mm:ss a/p | 8:50:35 p
h:mm | 20:50
h:mm:ss | 20:50:35
m/d/yyyy h:mm | 12/7/1958 20:50


User-Defined Numeric Formats (Format Function)

The following table identifies characters you can use to create user-defined number formats:

Character | Description
None | Display the number with no formatting.
(0) Digit placeholder. Display a digit or a zero. If the expression has a digit in the position where the 0 appears in the format string, display it; otherwise, display a zero in that position.

If the number has fewer digits than there are zeros (on either side of the decimal) in the format expression, display leading or trailing zeros. If the number has more digits to the right of the decimal separator than there are zeros to the right of the decimal separator in the format expression, round the number to as many decimal places as there are zeros. If the number has more digits to the left of the decimal separator than there are zeros to the left of the decimal separator in the format expression, display the extra digits without modification.
(#) Digit placeholder. Display a digit or nothing. If the expression has a digit in the position where the # appears in the format string, display it; otherwise, display nothing in that position.

This symbol works like the 0 digit placeholder, except that leading and trailing zeros aren't displayed if the number has the same or fewer digits than there are # characters on either side of the decimal separator in the format expression.
(.) Decimal placeholder. In some locales, a comma is used as the decimal separator. The decimal placeholder determines how many digits are displayed to the left and right of the decimal separator. If the format expression contains only number signs to the left of this symbol, numbers smaller than 1 begin with a decimal separator. To display a leading zero displayed with fractional numbers, use 0 as the first digit placeholder to the left of the decimal separator. The actual character used as a decimal placeholder in the formatted output depends on the Number Format recognized by your system.
(%) Percentage placeholder. The expression is multiplied by 100. The percent character (%) is inserted in the position where it appears in the format string.
(,) Thousand separator. In some locales, a period is used as a thousand separator. The thousand separator separates thousands from hundreds within a number that has four or more places to the left of the decimal separator. Standard use of the thousand separator is specified if the format contains a thousand separator surrounded by digit placeholders (0 or #). Two adjacent thousand separators or a thousand separator immediately to the left of the decimal separator (whether or not a decimal is specified) means "scale the number by dividing it by 1000, rounding as needed." For example, you can use the format string "##0,," to represent 100 million as 100. Numbers smaller than 1 million are displayed as 0. Two adjacent thousand separators in any position other than immediately to the left of the decimal separator are treated simply as specifying the use of a thousand separator. The actual character used as the thousand separator in the formatted output depends on the Number Format recognized by your system.
(:) Time separator. In some locales, other characters may be used to represent the time separator. The time separator separates hours, minutes, and seconds when time values are formatted. The actual character used as the time separator in formatted output is determined by your system settings.
(/) Date separator. In some locales, other characters may be used to represent the date separator. The date separator separates the day, month, and year when date values are formatted. The actual character used as the date separator in formatted output is determined by your system settings.
(E- E+ e- e+) | Scientific format. If the format expression contains at least one digit placeholder (0 or #) to the left of E-, E+, e-, or e+, the number is displayed in scientific format and E or e is inserted between the number and its exponent. The number of digit placeholders to the left determines the number of digits 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.
- + $ ( ) Display a literal character. To display a character other than one of those listed, precede it with a backslash (\) or enclose it in double quotation marks (" ").
(\) Display the next character in the format string. To display a character that has special meaning as a literal character, precede it with a backslash (\). The backslash itself isn't displayed. Using a backslash is the same as enclosing the next character in double quotation marks. To display a backslash, use two backslashes (\\).

Examples of characters that can't be displayed as literal characters are the date-formatting and time-formatting characters (a, c, d, h, m, n, p, q, s, t, w, y, / and :), the numeric-formatting characters (#, 0, %, E, e, comma, and period), and the string-formatting characters (@, &, <, >, and !).
("ABC") | Display the string inside the double quotation marks (" "). To include a string in format from within code, you must use Chr(34) to enclose the text (34 is the character code for a quotation mark (")).

See Also

Example

Different Formats for Different Numeric Values (Format Function) | Format Function | Named Numeric Formats (Format Function) | User-Defined Date/Time Formats (Format Function) | User-Defined String Formats (Format Function)


User-Defined Numeric Format Expressions Example

The following table contains some sample format expressionss for numbers. (These examples all assume that your system's locale setting is English-U.S.) The first column contains the format strings; the other columns contain the resulting output if the formatted data has the value given in the column headings.

Format (format) | Positive 5 | Negative 5 | Decimal .5
Zero-length string ("") | 5 | -5 | 0.5
0 | 5 | -5 | 1
0.00 | 5.00 | -5.00 | 0.50
#,##0 | 5 | -5 | 1
#,##0.00;;;Nil | 5.00 | -5.00 | 0.50
$#,##0;($#,##0) | $5 | ($5) | $1
$#,##0.00;($#,##0.00) | $5.00 | ($5.00) | $0.50
0% | 500% | -500% | 50%
0.00% | 500.00% | -500.00% | 50.00%
0.00E+00 | 5.00E+00 | -5.00E+00 | 5.00E-01
0.00E-00 | 5.00E00 | -5.00E00 | 5.00E-01


This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Assignment Operators

= Operator

^= Operator

*= Operator

/= Operator

\= Operator

+= Operator

-= Operator

&= Operator

See Also


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Bitwise Operators

BitAnd Operator

BitNot Operator

BitOr Operator

BitXor Operator

See Also


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Alias

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Any

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Append

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Base

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Case

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Compare

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Each

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

EndIf

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Explicit

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Global

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

In

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Lib

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Local

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Loop

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Module

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Output

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Preserve

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Random

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Read

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Shared

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Text

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

TypeOf

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Until

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Wend

[Topic intentionally blank - content coming in later builds]


Object doesn't support this action (Error 445)

Not all objects support all actions. This error has the following cause and solution:
  • You referenced a method or property that isn't supported by this object.

    See the object's documentation for more information on the object and check the spellings of properties and methods.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


This array is fixed or temporarily locked (Error 10

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

This array is fixed or temporarily locked (Error 10)

Not all arrays can be redimensioned. Even arrays specifically declared to be dynamic and arrays within Variant variables are sometimes locked temporarily. This error has the following causes and solutions:
  • You tried to use ReDim to change the number of elements of a fixed-size array . For example, in the following code, the fixed array FixedArr is received by SomeArr in the NextOne procedure, and then an attempt is made to resize SomeArr:
    Sub FirstOne
   Dim FixedArr(25) As Integer   ' Create a fixed-size array and
   NextOne FixedArr()   ' pass it to another procedure.
End Sub

Sub NextOne(SomeArr() As Integer)
   ReDim SomeArr(35)      ' Error 10 occurs here.
   . . .
End Sub

    Make the original array dynamic rather than fixed by declaring it with ReDim (if the array is declared within a procedure), or by declaring it without specifying the number of elements (if the array is declared at module level).

  • You tried to redimension a module-level dynamic array, in which one element has been passed as an argument to a procedure. For example, in the following code, ModArray is a dynamic, module-level array whose forty-fifth element is being passed by reference to the Test procedure:
    Dim ModArray () As Integer   ' Create a module-level dynamic array.
   . . .

Sub AliasError()
   ReDim ModArray (1 To 73) As Integer
   Test ModArray (45)   ' Pass an element of the module-level
                        ' array to the Test procedure.
End Sub

Sub Test(SomeInt As Integer)
   ReDim ModArray (1 To 40) As Integer  ' Error occurs here.
End Sub

    There is no need to pass an element of the module-level array in this case, since it's visible within all procedures in the module. However, if an element is passed, the array is locked to prevent a deallocation of memory for the reference parameter within the procedure, causing unpredictable behavior when the procedure returns.

  • You attempted to assign a value to a Variant variable containing an array, but the Variant is currently locked. For example, if your code uses a For Each...Next loop to iterate over a variant containing an array, the array is locked on entry into the loop, and then released at the termination of the loop:
    SomeArray = Array(9,8,7,6,5,4,3,2,1)

For Each X In SomeArray
   SomeArray = 301   ' Causes error since array is locked.
Next X

    Use a For...Next rather than a For Each...Next loop to iterate. When an array is the object of a For Each...Next loop, you can read the array, but not write to it.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

For Each...Next Statement | For...Next Statement | ReDim Statement | Sub Statement | Variant Data Type


Can't call Friend procedure on an object that isn't an instance of the defining class (Error 97)

A Friend procedure is callable from a module that is outside the class, but part of the project within which the class is defined. This error has the following causes and solutions:
  • You tried to call the Friend procedure of a class. Although your reference variable is of the proper type, the variable points to an instance that isn't an instance of the class.

    For example, this can occur if there are two classes, classics and classy (that implements classy), but you mistakenly assign the instance of classy to the instance of classics.

  • You tried to access a Friend property or method either cross-process or cross-thread. Friend procedures are not part of a class's public interface, so they cannot be marshaled cross-process or cross-thread.

For additional information, select the item in question and press F1.


Bad file mode (Error 54)

Statements used in manipulating file contents must be appropriate to the mode in which the file was opened. This error has the following causes and solutions:
  • A Put or Get statement is specifying a sequential file.

    Put and Get can only refer to files opened for Random or Binary access.

  • A Print # statement specifies a file opened for an access mode other than Output or Append.

    Use a different statement to place data in the file or reopen the file in an appropriate mode.

  • An Input # statement specifies a file opened for an access mode other than Input.

    Use a different statement to place data in the file or reopen the file in Input mode.

  • You attempted to write to a read-only file.

    Change the read/write status of the file or don't try to write to it.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Get Statement | Input # Statement | Open Statement | Print # Statement | Put Statement


Bad file name or number (Error 52)

An error occurred trying to access the specified file. This error has the following causes and solutions:
  • A statement refers to a file with a file number or file name that is:
    • Not specified in the Open statement or was specified in an Open statement, but has since been closed.

      Specify the file name in an Open statement. Note that if you invoked the Close statement without arguments, you may have inadvertently closed all currently open files, invalidating all file numbers.

    • Out of the range of file numbers (1 – 511).

      If your code is generating file numbers algorithmically, make sure the numbers are valid.

  • There is an invalid name or number.

    File names must conform to operating system conventions as well as Basic file-naming conventions. In Microsoft Windows, use the following conventions for naming files and directories:

    • The name of a file or directory can have two parts: a name and an optional extension. The two parts are separated by a period, for example, myfile.new.
    • The name can contain up to 255 characters.
    • The name must start with either a letter or number. It can contain any uppercase or lowercase characters (file names aren't case-sensitive) except the following characters: quotation mark ("), apostrophe ('), slash (/), backslash (\), colon (:), and vertical bar (|).
    • The name can contain spaces.
    • The following names are reserved and can't be used for files or directories: CON, AUX, COM1, COM2, COM3, COM4, LPT1, LPT2, LPT3, PRN, and NUL. For example, if you try to name a file PRN in an Open statement, the default printer will simply become the destination for Print # and Write # statements directed to the file number specified in the Open statement.
    • The following are examples of valid Microsoft Windows file names:
       LETTER.DOC
   My Memo.Txt
   BUDGET.92
   12345678.901
   Second Try.Rpt
    • On the Macintosh, a file name can include any character except the colon (:), and can contain spaces. Null characters (Chr(0)) aren't allowed in any file names.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Chr Function | Open Statement | Print # Statement | Write # Statement


Invalid pattern string (Error 93)

The pattern string specified in the Like operation of a search is invalid. This error has the following cause and solution:
  • A common example of an invalid character list expression is [a-b , where the right bracket is missing.

    Review the valid characters for list expressions.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Like Operator


Bad record length (Error 59)

The length of a record variable in a Get or Put statement must be the length specified in its corresponding Open statement. This error has the following causes and solutions:
  • The record variable's length differs from the length specified in the corresponding Open statement.

    Make sure the sum of the sizes of fixed-length variables in the user-defined type defining the record variable's type is the same as the value stated in the Open statement's Len clause. In the following example, assume RecVar is a variable of the appropriate type. You can use the Len function to specify the length, as follows:

    Open MyFile As #1 Len = Len(RecVar)
  • The variable in a Put statement is (or includes) a variable-length string.

    Because a 2-byte descriptor is always added to a variable-length string placed in a random access file with Put, the variable-length string must be at least 2 characters shorter than the record length specified in the Len clause of the Open statement.

  • The variable in a Put statement is (or includes) a Variant.

    Like variable-length strings, Variant data types also require a 2-byte descriptor. Variants containing variable-length strings require a 4-byte descriptor. Therefore, for variable-length strings in a Variant, the string must be at least 4 bytes shorter than the record length specified in the Len clause.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Bad record number (Error 63)

An error occurred during the attempted file access. This error has the following cause and solution:
  • The record number in a Put or Get statement is less than or equal to zero.

    Check the calculations used in generating the record number. Make sure that the variables containing the record number or used in calculating record numbers are spelled correctly. A misspelled variable name is implicitly declared and initialized to zero, unless you have properly placed Option Explicit in the module.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't perform requested operation (Error 17)

An operation can't be carried out if it would invalidate the current state of the project. This error has the following cause and solution:
  • The requested operation would invalidate the current state of the project. For example, the error occurs if you use the References dialog box to add a reference to a new project or object library while a program is in break mode.

    Stop execution of the current code, and then retry the operation.

  • An attempt was made to programmatically modify currently running code. For example, your code may have tried to read code from a disk file into a currently running module.

    Although you can modify modules in the project while they aren't actually running, you can't make modifications to a running module. To make such changes, you must stop the module from running, make the additions or changes, and then restart execution.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


ActiveX component can't create object or return reference to this object (Error 429)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

COM component can't create object or return reference to this object (Error 429)

Creating objects requires that the object's class be registered in the system registry and that any associated dynamic-link libraries (DLL) be available. This error has the following causes and solutions:
  • The class isn't registered. For example, the system registry has no mention of the class, or the class is mentioned, but specifies either a file of the wrong type or a file that can't be found.

    If possible, try to start the object's application. If the registry information is out of date or wrong, the application should check the registry and correct the information. If starting the application doesn't fix the problem, rerun the application's setup program.

  • A DLL required by the object can't be used, either because it can't be found, or it was found but was corrupted.

    Make sure all associated DLLs are available. For example, the Data Access Object (DAO) requires supporting DLLs that vary among platforms. You may have to rerun the setup program for such an object if that is what is causing this error.

  • The object is available on the machine, but it is a licensed Automation object, and can't verify the availability of the license necessary to instantiate it.

    Some objects can be instantiated only after the component finds a license key, which verifies that the object is registered for instantiation on the current machine. When a reference is made to an object through a properly installed type library or object library, the correct key is supplied automatically.

    If the attempt to instantiate is the result of a CreateObject or GetObject call, the object must find the key. In this case, it may search the system registry or look for a special file that it creates when it is installed, for example, one with the extension .lic. If the key can't be found, the object can't be instantiated. If an end user has improperly set up the object's application, inadvertently deleted a necessary file, or changed the system registry, the object may not be able to find its key. If the key can't be found, the object can't be instantiated. In this case, the instantiation may work on the developer's system, but not on the user's system. It may be necessary for the user to reinstall the licensed object.

  • You are trying to use the GetObject function to retrieve a reference to class created with Visual Basic.

    GetObject can't be used to obtain a reference to a class created with Visual Basic.

  • Access to the object has explicitly been denied.

    For example, you may be trying to access a data object that's currently being used and is locked to prevent deadlock situations. If that's the case, you may be able to access the object at another time.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

CreateObject Function | GetObject Function


Can't create necessary temporary file (Error 322)

Creating an executable file requires creation of temporary files. This error has the following cause and solution:
  • The drive that contains the directory specified by the TEMP environment variable is full.

    Delete files from the full drive or specify a different drive in the TEMP environment variable.

  • The TEMP environment variable specifies an invalid or read-only drive or directory.

    Specify a valid drive for the TEMP environment variable or remove the read-only restriction from the currently specified drive or directory.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


A property or method call cannot include a reference to a private object, either as an argument or as a return value (Error 98)

Private objects should never be passed outside a project. The following, all of which are prohibited, are possible causes for the error:
  • A client invoked a property or method of an out-of-process component and attempted to pass a reference to a private object as one of the arguments. A client invoked a property or method of an out-of-process component and the component attempted to return a reference to a private object, or to assign such a reference to a ByRef argument.
  • An out-of-process component has invoked a call-back method on its client and attempted to pass a reference to a private object.
  • An out-of-process component attempted to pass a reference to a private object as an argument of an event it was raising.
  • A client attempted to assign a private object reference to a ByRef argument of an event it was handling.

Note that although Visual Basic prevents you from passing references to nonvisual private objects across processes, there are some cases in which Visual Basic can't detect this error and thus can't prevent it. Private objects are not designed to be used outside your project. If you pass them to a client, you may jeopardize program stability and cause incompatibility with future versions of Visual Basic. If you need to pass a private class of your own to a client, set the Instancing property to a value other than Private.

For additional information, select the item in question and press F1.


Can't save file to TEMP directory (Error 735)

Components often need to save temporary information to disk. This error has the following cause and solution:
  • Component can't find a directory named TEMP.

    Create a directory named TEMP and set the TEMP environment variable equal to its path.

  • The drive or partition containing the TEMP directory lacks sufficient space to save information.

    Make some space on the drive by erasing unnecessary files, or create a TEMP directory on another partition and set the TEMP environment variable equal to its path.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid use of Null (Error 94)

Null is a Variant subtype used to indicate that a data item contains no valid data. This error has the following cause and solution:
  • You are trying to obtain the value of a Variant variable or an expression that is Null. For example:
    MyVar = Null
For Count = 1 To MyVar
   . . .
Next Count

    Make sure the variable contains a valid value.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Variant Data Type


Class not registered on local machine (Error 463)

The CreateObject function requires a valid server. This error has the following cause and solution:
  • A server parameter was specified, but the specified class progid (the first parameter of the CreateObject function) is not registered on the local system.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Code resource lock error (Error 455)

This error can only occur on the Macintosh. When you access a code resource, you must lock it. This error has the following cause and solution:
  • A call was made to a procedure in a code resource. The code resource was found, but an error occurred when an attempt was made to lock the resource.

    Check for an error returned by Hlock, for example, "Illegal on empty handle" or "Illegal on free block".

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Code resource not found (Error 454)

This error can only occur on the Macintosh. This error has the following cause and solution:
  • A call was made to a procedure in a code resource, but the code resource could not be found.

    Check to be sure the resource is available and properly referenced.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Device unavailable (Error 68)

This error has the following causes and solutions:
  • The device you are trying to access either is not online or doesn't exist.

    Check power to the device and any cables connecting your computer to the device. If you are trying to access a printer over a network, make sure there is a logical connection between your computer and the printer, for example, a connection associating LPT1 with the network printer ID.

  • Your network connection may have been broken.

    Reconnect to the network and try the operation again.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Can't rename with different drive (Error 74)

The Name statement must rename the file to the current drive. This error has the following cause and solution:
  • You tried to move a file to a different drive using the Name statement.

    Use FileCopy to write the file to another drive, and then delete the old file with a Kill statement.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

FileCopy Statement | Kill Statement | Name Statement


Disk full (Error 61)

This error has the following causes and solutions:
  • There isn't enough room on the disk for the completion of a Print #, Write #, or Close operation.

    Move some files to another disk or delete some files.

  • There isn't enough room on the disk to create required files.

    Move some files to another disk or delete some files.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Close Statement | Print # Statement | Write # Statement


Disk not ready (Error 71)

This error has the following causes and solutions:
  • There is no disk in the specified drive.

    Put a disk in the drive and retry the operation.

  • The drive door of the specified drive is open.

    Close the drive door and retry the operation.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Division by zero (Error 11)

Division by zero isn't possible. This error has the following cause and solution:
  • The value of an expression being used as a divisor is zero.

    Check the spelling of variables in the expression. A misspelled variable name can implicitly create a numeric variable that is initialized to zero. Check previous operations on variables in the expression, especially those passed into the procedure as arguments from other procedures.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Bad DLL calling convention (Error 49)

Arguments passed to a dynamic-link library (DLL) or Macintosh code resource routine must exactly match those expected by the routine. Calling conventions deal with number, type, and order of arguments. This error has the following causes and solutions:
  • Your program is calling a routine in a DLL (in Windows) or a code resource (on the Macintosh) that's being passed the wrong type of arguments.

    Make sure all argument types agree with those specified in the declaration of the routine you are calling.

  • Your program is calling a routine in a DLL (in Windows) or a code resource (on the Macintosh) that's being passed the wrong number of arguments.

    Make sure you are passing the same number of arguments indicated in the declaration of the routine you are calling.

  • Your program is calling a routine in a DLL, but isn't using the StdCall calling convention.

    If the DLL routine expects arguments by value, then make sure ByVal is specified for those arguments in the declaration for the routine.

  • Your Declare statement for a Windows DLL includes CDecl.

    The CDecl keyword applies only to the Macintosh.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

ByVal


Error in loading DLL (Error 48)

A dynamic link library (DLL) is a library specified in the Lib clause of a Declare statement. This error has the following causes and solutions:
  • The file isn't DLL-executable.

    If the file is a source-text file, it must be compiled and linked to DLL executable form.

  • The file isn't a Microsoft Windows DLL.

    Obtain the Microsoft Windows DLL equivalent of the file.

  • The file is an early Microsoft Windows DLL that is incompatible with Microsoft Windows protect mode.

    Obtain an updated version of the DLL.

  • The DLL references another DLL that isn't present.

    Obtain the referenced DLL and make it available to the other DLL.

  • The DLL or one of the referenced DLLs isn't in a directory specified by your path.

    Move the DLL to a referenced directory or place its current directory on the path.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Declare Statement


This key is already associated with an element of this collection (Error 457)

A key is a string specified in the Add method that uniquely identifies a specific member of a collection. This error has the following cause and solution:
  • You specified a key for a collection member that already identifies another member of the collection.

    Choose a different key for this member.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Add Method


Input past end of file (Error 62)

You can't read past the end-of-file position. This error has the following cause and solution:
  • An Input # or Line Input # statement is reading from a file in which all data has been read or from an empty file.

    Use the EOF function immediately before the Input # statement to detect the end of file.

  • You used the EOF function with a file opened for Binary access.

    EOF only works with files opened for sequential Input access. Use Seek and Loc with files opened for Binary access.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

EOF Function | Input # Statement | Line Input # Statement


Expression too complex (Error 16)

The number of subexpressions allowed in a floating-point expression varies among platforms. For example, on 32-bit Microsoft Windows operating systems, the limit is 8 levels of nested floating-point expressions. This error has the following cause and solution:
  • A floating-point expression contains too many nested subexpressions.

    Break the expression into as many separate expressions as necessary to prevent the error from occurring.

Note In earlier versions of Visual Basic, Error 16 was "String expression too complex." That error condition can no longer occur. However, if you have early code that traps and handles that error, you should remove it to prevent confusion with this new error.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


File already exists (Error 58)

This error has the following causes and solutions:
  • This error occurs at run time when the new file name, for example, one specified in a Name statement, is identical to a file name that already exists.

    Specify a new file name in the Name statement or delete the old file before specifying it in a Name statement.

  • You used the Save As command to save a currently loaded project, but the project name already exists.

    Use a different project name if you don't want to replace the other project.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Kill Statement | Name Statement


File already open (Error 55)

Sometimes a file must be closed before another Open or other operation can occur. This error has the following causes and solutions:
  • A sequential-output mode Open statement was executed for a file that is already open.

    You must close a file opened for one type of sequential access before opening it for another. For example, you must close a file opened for Input before opening it for Output.

  • A statement, for example, Kill, SetAttr, or Name, refers to an open file.

    Close the file before executing the statement.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Kill Statement | Name Statement | Open Statement | SetAttr Statement


File not found (Error 53)

The file was not found where specified. This error has the following causes and solutions:
  • A statement, for example, Kill, Name, or Open, refers to a file that doesn't exist.

    Check the spelling of the file name and the path specification.

  • An attempt has been made to call a procedure in a dynamic-link library (DLL) or Macintosh code resource, but the library or resource file name specified in the Lib clause of the Declare statement can't be found.

    Check the spelling of the file name and the path specification.

  • In the development environment, this error occurs if you attempt to open a project or load a text file that doesn't exist.

    Check the spelling of the project name or file name and the path specification.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Wrong number of arguments (Error 450)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Wrong number of arguments or invalid property assignment (Error 450)

The number of arguments to a procedure must match the number of parameters in the procedure's definition. This error has the following causes and solutions:
  • The number of arguments in the call to the procedure wasn't the same as the number of required arguments expected by the procedure.

    Check the argument list in the call against the procedure declaration or definition.

  • You specified an index for a control that isn't part of a control array.

    The index specification is interpreted as an argument but neither an index nor an argument is expected, so the error occurs. Remove the index specification, or follow the procedure for creating a control array. Set the Index property to a nonzero value in the control's Properties window at design time.

  • You tried to assign a value to a read-only property, or you tried to assign a value to a property for which no Property Let procedure exists.

    Assigning a value to a property is the same as passing the value as an argument to the object's Property Let procedure. Properly define the Property Let procedure; it must have one more argument than the corresponding Property Get procedure. If the property is meant to be read-only, you can't assign a value to it.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Function Statement | Sub Statement


Property Get can't be executed on write-only property (Error 394)

Not all properties return information. This error has the following cause and solution:
  • The property you are trying to access doesn't return information.

    You can't determine the state of the property.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Property Get can't be executed at run time (Error 393)

Not all properties return run-time information. This error has the following cause and solution:
  • The property you are trying to access is read-only at run time.

    Terminate execution and view the property in design time.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Method or data member not found (Error 461)

The collection, object, or user-defined type doesn't contain the referenced member. This error has the following causes and solutions:
  • You misspelled the object or member name.

    Check the spelling of the names and check the Type statement or the object documentation to determine what the members are and the proper spelling of the object or member names.

  • You specified a collection index that's out of range.

    Check the Count property to determine whether a collection member exists. Note that collection indexes begin at 1 rather than zero, so the Count property returns the highest possible index number.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Collection Object | Count Property | Type Statement


For loop not initialized (Error 92)

For loop counters must be initialized. This error has the following cause and solution:
  • You jumped into the middle of a For...Next loop.

    Remove the jump into the loop. Placing labels inside a For...Next loop isn't recommended.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

For Each...Next Statement | For...Next Statement


Invalid procedure call or argument (Error 5)

Some part of the call can't be completed. This error has the following causes and solutions:
  • An argument probably exceeds the range of permitted values. For example, the Sin function can only accept values within a certain range. Positive arguments less than 2,147,483,648 are accepted, while 2,147,483,648 generates this error.

    Check the ranges permitted for arguments.

  • This error can also occur if an attempt is made to call a procedure that isn't valid on the current platform. For example, some procedures may only be valid for Microsoft Windows, or for the Macintosh, and so on.

    Check platform-specific information about the procedure.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Function Statement | Property Get Statement | Property Let Statement | Property Set Statement | Sub Statement


Internal error (Error 51)

Make sure this error wasn't generated by the Error statement or Raise method. This error has the following cause and solution:
  • An internal malfunction has occurred in Visual Basic.

    Unless this call was generated by the Error statement or Raise method, contact Microsoft Product Support Services to report the conditions under which the message appeared.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Error Statement | Raise Method


Invalid Clipboard format (Error 460)

The Clipboard only accepts data in certain specified formats. This error has the following cause and solution:
  • You tried to place data from a component on the Clipboard, but the data is in a format incompatible with the Clipboard.

    Consult the documentation for the component to determine whether you can use the Clipboard for transferring data from the component.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Specified DLL function not found (Error 453)

The dynamic-link library (DLL) in a user library reference was found, but the DLL function specified wasn't found within the DLL. This error has the following causes and solutions:
  • You specified an invalid ordinal in the function declaration.

    Check for the proper ordinal or call the function by name.

  • You gave the right DLL name, but it isn't the version that contains the specified function.

    You may have the correct version on your machine, but if the directory containing the wrong version precedes the directory containing the correct one in your path, the wrong DLL is accessed. Check your machine for different versions. If you have an early version, contact the supplier for a later version.

  • If you are working on a 32-bit Microsoft Windows platform, both the DLL name and alias (if used) must be correct.

    Make sure the DLL name and alias are correct.

  • Some 32-bit DLLs contain functions with slightly different versions to accommodate both Unicode and ANSI strings. An "A" at the end of the function name specifies the ANSI version. A "W" at the end of the function name specifies the Unicode version.

    If the function takes string-type arguments, try appending an "A" to the function name.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid file format (Error 321)

Disk files often have data stored in proprietary formats. This error has the following cause and solution:
  • You tried to load a file into a component, but the format of the data in the file was incompatible with the component.

    Consult the documentation for the component to determine the proper format for disk file data and whether the component provides support for converting from one format to another.

  • You tried to save component data to a file, but the format of the data was incompatible with the format of the file.

    Consult the documentation for the component to determine whether it provides support for converting from one format to another.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid ordinal (Error 452)

Your call to a dynamic-link library (DLL) indicated to use a number instead of a procedure name, using the #num syntax. This error has the following causes and solutions:
  • An attempt to convert the num expression to an ordinal failed.

    Make sure the expression represents a valid number or call the procedure by name.

  • The num specified doesn't specify any function in the DLL.

    Make sure num identifies a valid function in the DLL.

  • A type library has an invalid declaration resulting in internal use of an invalid ordinal number.

    Comment out code to isolate the procedure call causing the problem. Write a Declare statement for the procedure and report the problem to the type library vendor.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid picture (Error 481)

Only a picture can be assigned to the Picture property or Picture object. This error has the following cause and solution:
  • You attempted to assign something to a Picture property or a Picture object that isn't recognized as an icon, bitmap, or Microsoft Windows metafile.

    See the Help topics for the Picture object or Picture property of the object you're using to determine the acceptable picture types.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid property-array index (Error 381)

A property value may consist of an array of values. This error has the following cause and solution:
  • A component's property array could have a lower bound of zero and an upper bound equal to the number of elements in the array minus 1. Alternatively, the lower bound could be 1 and the upper bound could equal the number of elements in the array.

    Check the component's documentation to make sure your index is within the valid range for the specified property.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid property value (Error 380)

Most properties only accept values of a certain type, within a certain range. This error has the following cause and solution:
  • An inappropriate value has been assigned to a property.

    See the property's Help topic to determine what types and range of values are appropriate for the property.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Invalid format in resource file (Error 325)

When accessing a resource file, the resource you are trying to retrieve must have a valid format. This error has the following cause and solution:
  • The resource file you're trying to retrieve has an invalid format, or a specific resource in the file has an invalid format.

    If the file contents have been damaged, reinstall the file from its original disk. If the error continues, contact the provider of the resource for a new file or a version of the resource with the expected format.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Variable uses a type not supported in Visual Basic (Error 458)

Not every variable that appears in a type library or object library can be used by every programming language. This error has the following cause and solution:
  • You tried to use a variable defined in a type library or object library that has a data type that isn't supported by Visual Basic.

    You can't use a variable of a type not recognized by Visual Basic in a Visual Basic program.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Device I/O error (Error 57)

External devices are sometimes subject to unanticipated errors. This error has the following cause and solution:
  • An input or output error occurred while your program was using a device such as a printer or disk drive.

    Make sure the device is operating properly, and then retry the operation.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Object doesn't support current locale setting (Error 447)

Not all objects support all locale settings. This error has the following causes and solutions:
  • You attempted to access an object that doesn't support the locale setting for the current project. For example, if your current project has the locale setting Canadian French, the object you are trying to access must support that locale setting.

    Check which locale settings the object supports.

  • The object relies on national language support in a dynamic-link library (DLL) or Macintosh code resource, for example, OLE2NLS.DLL, that may be out of date.

    Obtain a more recent version of the DLL, one that supports the current project locale.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Connection to type library or object library for remote process has been lost (Error 442)

During remote access (that is, when accessing an object that is part of another process or is running on another machine), the connection to the library containing object information was broken. This error has the following cause and solution:
  • You lost your connection to the remote process's object library or type library.

    To reconnect, follow these steps:

    1. Restart the Application object.
    2. In the error dialog box through which you entered this Help topic, click OK to display the References dialog box.
    3. The lost reference appears with the word MISSING to its left.
    4. Remove the lost reference.
    5. In the References dialog box, click the check box for the object you started in step 1.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Understanding Automation


Object doesn't support named arguments (Error 446)

Not all objects support named arguments. This error has the following cause and solution:
  • You tried to access an object whose methods don't support named arguments.

    Specify arguments positionally when performing methods on this object. See the object's documentation for more information on argument positions and types.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Named argument not found (Error 448)

A named argument may not be used in a procedure invocation unless it appears in the procedure definition. This error has the following cause and solution:
  • You specified a named argument, but the procedure was not defined to accept an argument by that name.

    Check the spelling of the argument name.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Need property-array index (Error 385)

This property value consists of an array rather than a single value. This error has the following cause and solution:
  • You didn't specify the index for the property array you tried to access.

    Check the component's documentation to find the range for the indexes appropriate to the array. Specify an appropriate index in your property access statement.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Property or method not found (Error 423)

The spelling of an object name must exactly match the definition in its object library. This error has the following cause and solution:
  • You referred to an object.method or object.property, but method or property isn't defined.

    You may have misspelled the name of the object. To see what properties and methods are defined for an object, display the Object Browser. Select the appropriate object library to view a list of available properties and methods.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Property let procedure not defined and property get procedure did not return an object (Error 451)

Certain properties, methods, and operations can only apply to Collection objects. This error has the following cause and solution:
  • You specified an operation or property that is exclusive to collections, but the object isn't a collection.

    Check the spelling of the object or property name, or verify that the object is a Collection object. Also look at the Add method used to add the object to the collection to be sure the syntax is correct and that any identifiers were spelled correctly.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Add Method | Collection Object


Object required (Error 424)

References to properties and methods often require an explicit object qualifier. This error has the following causes and solutions:
  • You referred to an object property or method, but didn't provide a valid object qualifier.

    Specify an object qualifier if you didn't provide one. For example, although you can omit an object qualifier when referencing a form property from within the form's own module, you must explicitly specify the qualifier when referencing the property from a standard module.

  • You supplied an object qualifier, but it isn't recognized as an object.

    Check the spelling of the object qualifier and make sure the object is visible in the part of the program in which you are referencing it. In the case of Collection objects, check any occurrences of the Add method to be sure the syntax and spelling of all the elements are correct.

  • You supplied a valid object qualifier, but some other portion of the call contained an error.

    An incorrect path as an argument to a host application's File Open command could cause the error. Check arguments.

  • You didn't use the Set statement in assigning an object reference.

    If you assign the return value of a CreateObject call to a Variant variable, an error doesn't necessarily occur if the Set statement is omitted. In the following code example, an implicit instance of Microsoft Excel is created, and its default property (the string "Microsoft Excel") is returned and assigned to the Variant RetVal. A subsequent attempt to use RetVal as an object reference causes this error:

    Dim RetVal                        ' Implicitly a Variant.
' Default property is assigned to Type 8 Variant RetVal.
RetVal = CreateObject("Excel.Application")
RetVal.Visible = True            ' Error occurs here.

    Use the Set statement when assigning an object reference.

  • In rare cases, this error occurs when you have a valid object but are attempting to perform an invalid action on the object. For example, you may receive this error if you try to assign a value to a read-only property.

    Check the object's documentation and make sure the action you are trying to perform is valid.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Add Method | Collection Object | Function Statement | Sub Statement


This component doesn't support this set of events (Error 459)

Not every component supports client sinking of events. This error has the following cause and solution:
  • You tried to use a WithEvents variable with a component that can't work as an event source for the specified set of events. For example, you may be sinking events of an object, then create another object that Implements the first object. Although you might think you could sink the events from the implemented object, that isn't automatically the case. Implements only implements an interface for methods and properties.

    You can't sink events for a component that doesn't source events.

  • WithEvents isn't supported for Private UserControls, because the type-info needed to raise the ObjectEvent isn't available at runtime.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Object variable not set (Error 91)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Object variable or With block variable not set (Error 91)

There are two steps to creating an object variable. First you must declare the object variable. Then you must assign a valid reference to the object variable using the Set statement. Similarly, a With...End With block must be initialized by executing the With statement entry point. This error has the following causes and solutions:
  • You attempted to use an object variable that isn't yet referencing a valid object.

    Specify or respecify a reference for the object variable. For example, if the Set statement is omitted in the following code, an error would be generated on the reference to MyObject:

    Dim MyObject As Object   ' Create object variable.
Set MyObject = Sheets(1)   ' Create valid object reference.
MyCount = MyObject.Count   ' Assign Count value to MyCount.
  • You attempted to use an object variable that has been set to Nothing.
    Set MyObject = Nothing   ' Release the object.
MyCount = MyObject.Count   ' Make a reference to a released object.

    Respecify a reference for the object variable. For example, use a new Set statement to set a new reference to the object.

  • The object is a valid object, but it wasn't set because the object library in which it is described hasn't been selected in the References dialog box.

    Select the object library in the Add References dialog box.

  • The target of a GoTo statement is inside a With block.

    Don't jump into a With block. Make sure the block is initialized by executing the With statement entry point.

  • You specified a line inside a With block when you chose the Set Next Statement command.

    The With block must be initialized by executing the With statement.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Creating Object Variables | Nothing | Set Statement


Automation error (Error 440)

When you access Automation objects, specific types of errors can occur. This error has the following cause and solution:
  • An error occurred while executing a method or getting or setting a property of an object variable. The error was reported by the application that created the object.

    Check the properties of the Err object to determine the source and nature of the error. Also try using the On Error Resume Next statement immediately before the accessing statement, and then check for errors immediately following the accessing statement.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Err Object | On Error Statement | Understanding Automation


Filename or class name not found during Automation operation (Error 432)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

File name or class name not found during Automation operation (Error 432)

The GetObject function requires either a valid file name with a path specification, or the name of a class that is registered with the system. This error has the following cause and solution:
  • The name specified for file name or class in a call to the GetObject function could not be found.

    Check the names and try again. Make sure the name used for the class parameter matches that registered with the system.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

GetObject Function


Automation object doesn't have a default value (Error 443)

When you specify an object name without a property or method, Visual Basic assumes you are referencing the object's default member (property or method). However, not all objects expose a default member. This error has the following cause and solution:
  • Visual Basic can't determine the default member for the specified object.

    Check the object's documentation and give an explicit specification for the property or method.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Object doesn't support this property or method (Error 438)

Not all objects support all properties and methods. This error has the following cause and solution:
  • You specified a method or property that doesn't exist for this Automation object.

    See the object's documentation for more information on the object and check the spellings of properties and methods.

  • You specified a Friend procedure to be called late bound.

    The name of a Friend procedure must be known at compile time. It can't appear in a late-bound call.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Class doesn't support Automation (Error 430)

Not all objects expose an Automation interface. This error has the following cause and solution:
  • The class you specified in the GetObject or CreateObject function call was found, but has not exposed a programmability interface.

    You can't write code to control an object's behavior unless it has been exposed for Automation. Check the documentation of the application that created the object for limitations on the use of Automation with this class of object.

  • You changed a project from .dll to .exe, or vice versa. If, for example, you have a .dll server already compiled and registered, and then you change the project type to .exe and recompile it, the fact that the .dll and .exe are already registered on your system prevents you from creating either object. You must manually unregister the old .dll or .exe to avoid the problem.

    This is caused by the combination of project compatibility and changing a project from an .exe to a .dll. In project compatibility, the CLSID is preserved, but not the IID. Since the CLSID is preserved, the class ends up being registered with two servers—one an in-process server, the other a local server. When an instance is created, the in-process one is chosen. When the querying of the interface occurs, the .dll does not support the IID because it's new.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

CreateObject Function | GetObject Function | Understanding Automation


Subscript out of range (Error 9)

Elements of arrays and members of collections can only be accessed within their defined ranges. This error has the following causes and solutions:
  • You referenced a nonexistent array element.

    The subscript may be larger or smaller than the range of possible subscripts, or the array may not have dimensions assigned at this point in the application. Check the declaration of the array to verify its upper and lower bounds. Use the UBound and LBound functions to condition array accesses if you're working with arrays that are redimensioned. If the index is specified as a variable, check the spelling of the variable name.

  • You declared an array but didn't specify the number of elements. For example, the following code causes this error:
    Dim MyArray() As Integer
MyArray(8) = 234   ' Causes Error 9.

    Visual Basic doesn't implicitly dimension unspecified array ranges as 0 – 10. Instead, you must use Dim or ReDim to specify explicitly the number of elements in an array.

  • You referenced a nonexistent collection member.

    Try using the For Each...Next construct instead of specifying index elements.

  • You used a shorthand form of subscript that implicitly specified an invalid element.

    For example, when you use the ! operator with a collection, the ! implicitly specifies a key. For example, object!keyname.value is equivalent to object.item(keyname).value. In this case, an error is generated if keyname represents an invalid key in the collection. To fix the error, use a valid key name or index for the collection.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Dim Statement | For Each...Next Statement | LBound Function | ReDim Statement | UBound Function


Out of memory (Error 7)

More memory was required than is available, or a 64K segment boundary was encountered. This error has the following causes and solutions:
  • You have too many applications, documents, or source files open.

    Close any unnecessary applications, documents, or source files that are open.

  • You have a module or procedure that's too large.

    Break large modules or procedures into smaller ones. This doesn't save memory, but it can prevent hitting 64K segment boundaries.

  • You have terminate-and-stay-resident programs running.

    Eliminate terminate-and-stay-resident programs.

  • You have many device drivers loaded.

    Eliminate unnecessary device drivers.

  • You have run out of space for Public variables.

    Reduce the number of Public variables.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Out of stack space (Error 28)

The stack is a working area of memory that grows and shrinks dynamically with the demands of your executing program. This error has the following causes and solutions:
  • You have too many active Function, Sub, or Property procedure calls.

    Check that procedures aren't nested too deeply. This is especially true with recursive procedures, that is, procedures that call themselves. Make sure recursive procedures terminate properly. Use the Calls dialog box to view which procedures are active (on the stack).

  • Your local variables require more local variable space than is available.

    Try declaring some variables at the module level instead. You can also declare all variables in the procedure static by preceding the Property, Sub, or Function keyword with Static. Or you can use the Static statement to declare individual Static variables within procedures.

  • You have too many fixed-length strings.

    Fixed-length strings in a procedure are more quickly accessed, but use more stack space than variable-length strings, because the string data itself is placed on the stack. Try redefining some of your fixed-length strings as variable-length strings. When you declare variable-length strings in a procedure, only the string descriptor (not the data itself) is placed on the stack. You can also define the string at module level where it requires no stack space. Variables declared at module level are Public by default, so the string is visible to all procedures in the module.

  • You have too many nested DoEvents function calls.

    Use the Calls dialog box to view which procedures are active on the stack.

  • Your code triggered an event cascade.

    An event cascade is caused by triggering an event that calls an event procedure that's already on the stack. An event cascade is similar to an unterminated recursive procedure call, but it's less obvious, since the call is made by Visual Basic rather than by an explicit call in your code. Use the Calls dialog box to view which procedures are active (on the stack).

To display the Calls dialog box, select the Calls button to the right of the Procedure box in the Debug window or choose the Calls command. For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Creating Recursive Procedures | DoEvents Function | Function Statement | Property Get Statement | Property Let Statement | Property Set Statement | Static Statement | Sub Statement


Out of string space (Error 14)

Visual Basic permits you to use very large strings. However, the requirements of other programs and the way you manipulate your strings may cause this error. This error has the following causes and solutions:
  • Expressions requiring that temporary strings be created for evaluation may cause this error. For example, the following code causes an Out of string space error on some operating systems:
    MyString = "Hello"
For Count = 1 To 100
   MyString = MyString & MyString
Next Count

    Assign the string to a variable of another name.

  • Your system may have run out of memory, which prevented a string from being allocated.

    Remove any unnecessary applications from memory to create more space.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Overflow (Error 6)

An overflow results when you try to make an assignment that exceeds the limitations of the target of the assignment. This error has the following causes and solutions:
  • The result of an assignment, calculation, or data type conversion is too large to be represented within the range of values allowed for that type of variable.

    Assign the value to a variable of a type that can hold a larger range of values.

  • An assignment to a property exceeds the maximum value the property can accept.

    Make sure your assignment fits the range for the property to which it is made.

  • You attempt to use a number in a calculation, and that number is coerced into an integer, but the result is larger than an integer. For example:
        Dim x As Long
    x = 2000 * 365   ' Error: Overflow

    To work around this situation, type the number, like this:

        Dim x As Long
    x = CLng(2000) * 365

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Argument not optional (Error 449)

The number and types of arguments must match those expected. This error has the following causes and solutions:
  • Incorrect number of arguments.

    Supply all necessary arguments. For example, the Left function requires two arguments; the first representing the character string being operated on, and the second representing the number of characters to return from the left side of the string. Because neither argument is optional, both must be supplied.

  • Omitted argument isn't optional.

    An argument can only be omitted from a call to a user-defined procedure if it was declared Optional in the procedure declaration. Either supply the argument in the call or declare the parameter Optional in the definition.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Left Function | Optional


Path/File access error (Error 75)

During a file-access or disk-access operation, for example, Open, MkDir, ChDir, or RmDir, the operating system couldn't make a connection between the path and the file name. This error has the following causes and solutions:
  • The file specification isn't correctly formatted.

    A file name can contain a fully qualified (absolute) or relative path. A fully qualified path starts with the drive name (if the path is on another drive) and lists the explicit path from the root to the file. Any path that isn't fully qualified is relative to the current drive and directory.

  • You attempted to save a file that would replace an existing read-only file.

    Change the read-only attribute of the target file or save the file with a different file name.

  • You attempted to open a read-only file in sequential Output or Append mode.

    Open the file in Input mode or change the read-only attribute of the file.

  • You attempted to change a Visual Basic project within a database or document.

    You can't make design changes to the project.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

ChDir Statement | MkDir Statement | Open Statement | RmDir Statement


Path not found (Error 76)

The path to a file includes the drive specification plus the directories and subdirectories that must be traversed to locate the file. A path can be relative or absolute. This error has the following cause and solution:
  • During a file-access or disk-access operation, for example, Open, MkDir, ChDir, or RmDir, the operating system was unable to find the specified path.

    Respecify the path.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

ChDir Statement | MkDir Statement | Open Statement | RmDir Statement


Permission denied (Error 70)

An attempt was made to write to a write-protected disk or to access a locked file. This error has the following causes and solutions:
  • You tried to open a write-protected file for sequential Output or Append.

    Open the file for Input or change the write-protection attribute of the file.

  • You tried to open a file on a disk that is write-protected for sequential Output or Append.

    Remove the write-protection device from the disk or open the file for Input.

  • You tried to write to a file that another process locked.

    Wait to open the file until the other process releases it.

  • You attempted to access the registry, but your user permissions don't include this type of registry access.

    On 32-bit Microsoft Windows systems, a user must have the correct permissions for access to the system registry. Change your permissions or have them changed by the system administrator.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Open Statement


Printer error (Error 482)

This error has the following cause and solution:
  • An error occurred at the printer, but no other information was returned to the computer that sent the file.

    You must physically examine the printer. Make sure all connections between computer and printer are solid. Most printers provide a display for error information such as "Out of paper," "Offline," and so on.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Property not found (Error 422)

Not all objects support the same set of properties. This error has the following cause and solution:
  • This object doesn't support the specified property.

    Check the spelling of the property name. Also, you may be trying to access something like a "text" property when the object actually supports a "caption" or some similarly named property. Check the object's documentation.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Replacements too long (Error 746)

A replacement may not exceed a specified maximum length. This error has the following cause and solution:
  • You specified a replacement that exceeded the length permitted.

    Consult the component documentation for maximum length restriction.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Resume without error (Error 20)

A Resume statement can only appear within an error handler and can only be executed in an active error handler. This error has the following causes and solutions:
  • You placed a Resume statement outside error-handling code.

    Move the statement into an error handler, or delete it.

  • Your code jumped into an error handler even though there was no error.

    Perhaps you misspelled a line label. Jumps to labels can't occur across procedures, so search the procedure for the label that identifies the error handler. If you find a duplicate label specified as the target of a GoTo statement that isn't an On Error GoTo statement, change the line label to agree with its intended target.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

GoTo Statement | On Error Statement | Resume Statement


Return without GoSub (Error 3)

A Return statement must have a corresponding GoSub statement. This error has the following cause and solution:
  • You have a Return statement that can't be matched with a GoSub statement.

    Make sure your GoSub statement wasn't inadvertently deleted.

Unlike For...Next, While...Wend, and Sub...End Sub, which are matched at compile time, GoSub and Return are matched at run time.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

For...Next Statement | GoSub...Return Statement | Sub Statement | While...Wend Statement


Search text not found (Error 744)

This error has the following cause and solution:
  • The text you specified wasn't found.

    The text doesn't exist.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Property Set not permitted (Error 387)

Not all properties support returning a reference. This error has the following cause and solution:
  • You tried to get a reference to a property that doesn't return a reference.

    Restrict your access to this property to Property Let and Property Get.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Property Set can't be used with a read-only property (Error 383)

It may not be possible to obtain a reference to a property at run time.This error has the following cause and solution:
  • You tried to get a reference to a property that's read-only at run time.

    Since you can use a reference for both reading and writing, the property must provide run-time support for both operations for a reference to be obtained at run time. You can only use a Property Get with this property.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Property Set can't be executed at run time (Error 382)

It may not be possible to obtain a reference to a property at run time.This error has the following cause and solution:
  • You tried to get a reference to a property that's either read-only or write-only at run time.

    Since you can use a reference for both reading and writing, the property must provide run-time support for both operations for a reference to be obtained at run time.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


The remote server machine does not exist or is unavailable (Error 462)

The CreateObject function requires a valid server. This error has the following cause and solution:
  • A server parameter was specified, but the server could not be either reached or found.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Too many DLL application clients

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Too many DLL application clients (Error 47)

The dynamic-link library (DLL) for Visual Basic can only accommodate access by 50 host applications at a time. This error has the following cause and solution:
  • Your application and other applications that are Visual Basic hosts (some of which may be accessed by your application) are all attempting to access the Visual Basic DLL at the same time.

    Reduce the number of open applications accessing Visual Basic.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Too many files (Error 67)

There is a limit to the number of disk files that can be open at one time. This error has the following causes and solutions:
  • MS-DOS operating system: More files have been created in the root directory than the operating system permits.

    The MS-DOS operating system limits the number of files that can be in the root directory, usually 512. If your program is opening, closing, or saving files in the root directory, change your program so that it uses a subdirectory.

  • MS-DOS operating system: More files have been opened than the number specified in the files= setting in your CONFIG.SYS file.

    Increase the number specified in the files= setting in your CONFIG.SYS file and restart your computer.

  • Macintosh: Your program tried to open more than 40 files.

    On the Macintosh, the standard limit is 40 files. This limit can be changed using a utility to modify the MaxFiles parameter of the boot block.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Trappable Errors

Trappable errors can occur while an application is running. Some trappable errors can also occur during development or compile time. You can test and respond to trappable errors using the On Error statement and the Err object. Unused error numbers in the range 1 – 1000 are reserved for future use by Visual Basic.

Code | Message
3 | Return without GoSub
5 | Invalid procedure call
6 | Overflow
7 | Out of memory
9 | Subscript out of range
10 | This array is fixed or temporarily locked
11 | Division by zero
13 | Type mismatch
14 | Out of string space
16 | Expression too complex
17 | Can't perform requested operation
18 | User interrupt occurred
20 | Resume without error
28 | Out of stack space
35 | Sub, Function, or Property not defined
47 | Too many code resource or DLL application clients
48 | Error in loading code resource or DLL
49 | Bad code resource or DLL calling convention
51 | Internal error
52 | Bad file name or number
53 | File not found
54 | Bad file mode
55 | File already open
57 | Device I/O error
58 | File already exists
59 | Bad record length
61 | Disk full
62 | Input past end of file
63 | Bad record number
67 | Too many files
68 | Device unavailable
70 | Permission denied
71 | Disk not ready
74 | Can't rename with different drive
75 | Path/File access error
76 | Path not found
91 | Object variable or With block variable not set
92 | For loop not initialized
93 | Invalid pattern string
94 | Invalid use of Null
97 | Can't call Friend procedure on an object that is not an instance of the defining class
98 | A property or method call cannot include a reference to a private object, either as an argument or as a return value
298 | System resource or DLL could not be loaded
320 | Can't use character device names in specified file names
321 | Invalid file format
322 | Can’t create necessary temporary file
325 | Invalid format in resource file
327 | Data value named not found
328 | Illegal parameter; can't write arrays
335 | Could not access system registry
336 | ActiveX Component not correctly registered
337 | ActiveX Component not found
338 | ActiveX Component did not run correctly
360 | Object already loaded
361 | Can't load or unload this object
363 | ActiveX Control specified not found
364 | Object was unloaded
365 | Unable to unload within this context
368 | The specified file is out of date. This program requires a later version
371 | The specified object can't be used as an owner form for Show
380 | Invalid property value
381 | Invalid property-array index
382 | Property Set can't be executed at run time
383 | Property Set can't be used with a read-only property
385 | Need property-array index
387 | Property Set not permitted
393 | Property Get can't be executed at run time
394 | Property Get can't be executed on write-only property
400 | Form already displayed; can't show modally
402 | Code must close topmost modal form first
419 | Permission to use object denied
422 | Property not found
423 | Property or method not found
424 | Object required
425 | Invalid object use
429 | ActiveX Component can't create object or return reference to this object
430 | Class doesn't support Automation
432 | File name or class name not found during Automation operation
438 | Object doesn't support this property or method
440 | Automation error
442 | Connection to type library or object library for remote process has been lost
443 | Automation object doesn't have a default value
445 | Object doesn't support this action
446 | Object doesn't support named arguments
447 | Object doesn't support current locale setting
448 | Named argument not found
449 | Argument not optional or invalid property assignment
450 | Wrong number of arguments or invalid property assignment
451 | Object not a collection
452 | Invalid ordinal
453 | Specified DLL function code resource not found
454 | Code resource not found
455 | Code resource lock error
457 | This key is already associated with an element of this collection
458 | Variable uses a type not supported in Visual Basic
459 | This component doesn't support the set of events
460 | Invalid Clipboard format
461 | Method or data member not found
462 | The remote server machine does not exist or is unavailable
463 | Class not registered on local machine
480 | Can't create AutoRedraw image
481 | Invalid picture
482 | Printer error
483 | Printer driver does not support specified property
484 | Problem getting printer information from the system. Make sure the printer is set up correctly
485 | Invalid picture type
486 | Can't print form image to this type of printer
520 | Can't empty Clipboard
521 | Can't open Clipboard
735 | Can't save file to TEMP directory
744 | Search text not found
746 | Replacements too long
31001 | Out of memory
31004 | No object
31018 | Class is not set
31027 | Unable to activate object
31032 | Unable to create embedded object
31036 | Error saving to file
31037 | Error loading from file

See Also

CVErr Function | Err Object | Error Function | Error Statement


Type mismatch (Error 13)

Visual Basic is able to convert and coerce many values to accomplish data type assignments that weren't possible in earlier versions. However, this error can still occur and has the following causes and solutions:
  • The variable or property isn't of the correct type. For example, a variable that requires an integer value can't accept a string value unless the whole string can be recognized as an integer.

    Try to make assignments only between compatible data types. For example, an Integer can always be assigned to a Long, a Single can always be assigned to a Double, and any type (except a user-defined type) can be assigned to a Variant.

  • An object was passed to a procedure that is expecting a single property or value.

    Pass the appropriate single property or call a method appropriate to the object.

  • A module or project name was used where an expression was expected, for example:
    Debug.Print MyModule

    Specify an expression that can be displayed.

  • You attempted to mix traditional Basic error handling with Variant values having the Error subtype (10, vbError), for example:
    Error CVErr(n)

    To regenerate an error, you must map it to an intrinsic Visual Basic or a user-defined error, and then generate that error.

  • A CVErr value can't be converted to Date. For example:
    MyVar = CDate(CVErr(9))

    Use a Select Case statement or some similar construct to map the return of CVErr to such a value.

  • At run time, this error typically indicates that a Variant used in an expression has an incorrect subtype, or a Variant containing an array appears in a Print # statement.

    To print arrays, create a loop that displays each element individually.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

CVErr Function | Data Type Summary | Print # Statement | Select Case Statement


Sub, Function, or Property not defined (Error 35)

A Sub, Function, or Property procedure must be defined to be called. This error has the following causes and solutions:
  • You misspelled the name of your procedure.

    Check the spelling and correct it.

  • You tried to call a procedure from another project without explicitly adding a reference to that project in the References dialog box.

    To add a reference

    1. Display the References dialog box.
    2. Find the name of the project containing the procedure you want to call. If the project name doesn't appear in the References dialog box, click the Browse button to search for it.
    3. Click the check box to the left of the project name.
    4. Click OK.
  • The specified procedure isn't visible to the calling procedure.

    Procedures declared Private in one module can't be called from procedures outside the module. If Option Private Module is in effect, procedures in the module aren't available to other projects. Search to locate the procedure.

  • You declared a Windows dynamic-link library (DLL) routine or Macintosh code-resource routine, but the routine isn't in the specified library or code resource.
  • Check the ordinal (if you used one) or the name of the routine. Make sure your version of the DLL or Macintosh code-resource is the correct one. The routine may only exist in later versions of the DLL or Macintosh code-resource. If the directory containing the wrong version precedes the directory containing the correct one in your path, the wrong DLL or Macintosh code-resource is accessed. You gave the right DLL name or Macintosh code-resource, but it isn't the version that contains the specified function.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

See Also

Function Statement | Option Private Statement | Private Statement | Property Get Statement | Property Let Statement | Property Set Statement | Sub Statement


User interrupt occurred (Error 18)

The process of breaking execution is useful, but if left unhandled, it results in termination of the application. This error has the following cause and solution:
  • A user pressed CTRL+BREAK or another interrupt key.

    In the development environment, continue execution. To provide for the occurrence of this condition at run time, handle the error in an appropriate way.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).


Add Method Example

This example uses the Add method to add Inst objects (instances of a class called Class1 containing a Public variable InstanceName) to a collection called MyClasses. To see how this works, insert a class module and declare a public variable called InstanceName at module level of Class1 (type Public InstanceName) to hold the names of each instance. Leave the default name as Class1. Copy and paste the following code into the Form_Load event procedure of a form module.

Dim MyClasses As New Collection   ' Create a Collection object.
Dim Num As Integer   ' Counter for individualizing keys.
Dim Msg
Dim TheName   ' Holder for names user enters.
Do
   Dim Inst As New Class1   ' Create a new instance of Class1.
   Num = Num + 1   ' Increment Num, then get a name.
   Msg = "Please enter a name for this object." & Chr(13) _
    & "Press Cancel to see names in collection."
   TheName = InputBox(Msg, "Name the Collection Items")
   Inst.InstanceName = TheName   ' Put name in object instance.
   ' If user entered name, add it to the collection.
   If Inst.InstanceName <> "" Then
      ' Add the named object to the collection.
      MyClasses.Add item := Inst, key := CStr(Num)
   End If
   ' Clear the current reference in preparation for next one.
   Set Inst = Nothing
Loop Until TheName = ""
For Each x In MyClasses
   MsgBox x.instancename, , "Instance Name"
Next


Item Method Example

This example uses the Item method to retrieve a reference to an object in a collection. Assuming Birthdays is a Collection object, the following code retrieves from the collection references to the objects representing Bill Smith's birthday and Adam Smith's birthday, using the keys "SmithBill" and "SmithAdam" as the index arguments. Note that the first call explicitly specifies the Item method, but the second does not. Both calls work because the Item method is the default for a Collection object. The references, assigned to SmithBillBD and SmithAdamBD using Set, can be used to access the properties and methods of the specified objects. To run this code, create the collection and populate it with at least the two referenced members.

Dim SmithBillBD As Object
Dim SmithAdamBD As Object
Dim Birthdays
Set SmithBillBD = Birthdays.Item("SmithBill")
Set SmithAdamBD = Birthdays("SmithAdam")


Remove Method Example

This example illustrates the use of the Remove method to remove objects from a Collection object, MyClasses. This code removes the object whose index is 1 on each iteration of the loop.

Dim Num, MyClasses
For Num = 1 To MyClasses.Count
   MyClasses.Remove 1   ' Remove the first object each time
         ' through the loop until there are
         ' no objects left in the collection.
Next Num


+ Operator Example

This example uses the + operator to sum numbers. The + operator can also be used to concatenate strings. However, to eliminate ambiguity, you should use the & operator instead. If the components of an expression created with the + operator include both strings and numerics, the arithmetic result is assigned. If the components are exclusively strings, the strings are concatenated.

Dim MyNumber, Var1, Var2
MyNumber = 2 + 2   ' Returns 4.
MyNumber = 4257.04 + 98112   ' Returns 102369.04.

Var1 = "34": Var2 = 6   ' Initialize mixed variables.
MyNumber = Var1 + Var2   ' Returns 40.

Var1 = "34": Var2 = "6"   ' Initialize variables with strings.
MyNumber = Var1 + Var2   ' Returns "346" (string concatenation).


/ Operator Example

This example uses the / operator to perform floating-point division.

Dim MyValue
MyValue = 10 / 4   ' Returns 2.5.
MyValue = 10 / 3   ' Returns 3.333333.


\ Operator Example

This example uses the \ operator to perform integer division.

Dim MyValue
MyValue = 11 \ 4   ' Returns 2.
MyValue = 9 \ 3   ' Returns 3.
MyValue = 100 \ 3   ' Returns 33.


* Operator Example

This example uses the * operator to multiply two numbers.

Dim MyValue
MyValue = 2 * 2   ' Returns 4.
MyValue = 459.35 * 334.90    ' Returns 153836.315.


- Operator Example

This example uses the - operator to calculate the difference between two numbers.

Dim MyResult
MyResult = 4 - 2   ' Returns 2.
MyResult = 459.35 - 334.90   ' Returns 124.45.


Constants (Visual Basic for Applications)

NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Constants (Visual Basic Language Reference)

Calendar Constants

CallType Constants

Color Constants

Comparison Constants

Compiler Constants

Date Constants

Date Format Constants

Dir, GetAttr, and SetAttr Constants

DriveType Constants

File Attribute Constants

File Input/Output Constants

Form Constants

IMEStatus Constants

Keycode Constants

Miscellaneous Constants

MsgBox Constants

QueryClose Constants

Shell Constants

SpecialFolder Constants

StrConv Constants

System Color Constants

Tristate Constants

Variables and Constants Keyword Summary

VarType Constants

Visual Basic Constants


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

HxLink DID NOT INITIALIZE

Events (Visual Basic Language Reference)

Activate, Deactivate Events
Initialize Event
QueryClose Event
Resize Event
Terminate Event


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Visual Basic Compiler Options

[Topic intentionally blank - content coming in later builds]


The binary compatibility DLL or EXE contains an Implements type whose definition cannot be found

If you have a Binary Compatible server which implements an interface that is contained in another DLL, you must be careful when recompiling it. This warning has the following cause and solution:
  • The other DLL was recompiled as Project Compatible which changes the interface GUID. Since this is not a visible change, this can be an unexpected error. This can also occur if someone gives you a Project Compatible DLL to reference.

    Basically, this error occurs when a project’s binary compatible DLL or EXE has a typelib with a broken reference. Broken references can occur when a referenced typelib is overwritten by another file (such as a re-compiled DLL/EXE), when you delete the typelib file, or when you move a referencing typelib over to a machine, but either don’t move the referenced typelib or don’t register the referenced typelib.

    One possible fix is to obtain a copy of the referenced typelib onto your machine and register it. You won't be able to use the old one because it was overwritten on recompile. Failing this, all that can be done is to stop using the DLL/EXE as your binary compatible version.


The binary compatibility DLL or EXE contains a parameter type or return type whose definition cannot be found

If you have a Binary Compatible server which contains a parameter or return type that is contained in another DLL, you must be careful when recompiling it. This warning has the following cause and solution:
  • When you set Binary Compatibility on a project and then recompile the project, Project Compatibility is set automatically, changing the interface's internal GUID. Since this is not a visible change, this can be an unexpected error.

    Basically, this error occurs when a project’s binary compatible DLL or EXE has a typelib with a broken reference. Broken references can occur when a referenced typelib is overwritten by another file (such as a re-compiled DLL/EXE), when you delete the typelib file, or when you move a referencing typelib over to a machine, but either don’t move the referenced typelib or don’t register the referenced typelib.

    One possible fix is to obtain a copy of the referenced typelib onto your machine and register it. You won't be able to use the old one because it was overwritten on recompile. Failing this, all that can be done is to stop using the DLL/EXE as your binary compatible version.


Close Statement Example

This example uses the Close statement to close all three files opened for Output.

Dim I, FileName
For I = 1 To 3   ' Loop 3 times.
   FileName = "TEST" & I   ' Create file name.
   Open FileName For Output As #I   ' Open file.
   Print #I, "This is a test."   ' Write string to file.
Next I
Close   ' Close all 3 open files.


Const Statement

Declares constants for use in place of literal values.

[Public|Private|Protected|Friend|Protected Friend] Const constname [As type] = expression

The Const statement syntax has these parts:

Part | Description
Public | Optional. Entities declared with the Public modifier have public access. There are no restrictions on the use of public entities.
Private | Optional. Entities declared with the Private modifier have private access. A private entity is accessible only within its declaration context, including any nested entities.
Protected | Optional. Entities declared with the Protected modifier have protected access. Protected access can only be specified on members of types (both regular type members and nested types), although there are different access rules for the two. A protected type member contained in a type is accessible to entities contained in a derived type, provided the access takes place through the derived type. A protected type nested in a type is accessible to entities contained in a derived type, provided the access takes place through the base type (since nested types are not inherited). Protected access is not a superset of friend access.
Friend | Optional. Entities declared with the Friend modifier have friend access. An entity with friend access is accessible only within the program that contains the entity declaration.
Protected Friend | Optional. Entities declared with the Protected Friend modifiers have the union of protected and friend accessibility.
constname | Required. Name of the constant; follows standard variable naming conventions.
type | Optional. Data type of the constant; may be Byte, Boolean, Char, Short, Integer, Long, Single, Double, Decimal, Date, String. Use a separate As type clause for each constant being declared.
expression | Required. Literal, other constant, or any combination that includes all arithmetic or logical operators except Is.

Remarks

Constants are private by default. Within procedures, constants are always private; their visibility can't be changed.

You can't use variables, user-defined functions, or intrinsic Visual Basic functions (such as Chr) in expressions assigned to constants.

If you don't explicitly declare the constant type using As type, the type of the constant is the result type of the expression.

Constants declared in a Sub, Function, or Property procedure are local to that procedure. A constant declared outside a procedure is defined throughout the class, module or structure in which it is declared. You can use constants anywhere you can use an expression.

See Also

Example


Const Statement Example

This example uses the Const statement to declare constants for use in place of literal values. Public constants are declared in the General section of a standard module, rather than a class module. Private constants are declared in the General section of any type of module.

' Constants are Private by default.
Const MyVar = 459

' Declare Public constant.
Public Const MyString = "HELP"

' Declare Private Integer constant.
Private Const MyInt As Integer = 5

' Declare multiple constants on same line.
Const MyStr = "Hello", MyDouble As Double = 3.4567


Date Statement Example

This example uses the Date statement to set the computer system date. In the development environment, the date literal is displayed in short date format using the locale settings of your code.

Dim MyDate
MyDate = #February 12, 1985#   ' Assign a date.
Date = MyDate   ' Change system date.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

DefBool Statement

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

DefByte Statement

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

DefChar Statement

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

DefCur Statement

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

DefDate Statement

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

DefDbl Statement

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

DefDec Statement

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

DefInt Statement

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

DefLng Statement

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

DefLng8 Statement

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

DefObj Statement

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

DefSng Statement

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

DefStr Statement

[Topic intentionally blank - content coming in later builds]


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

DefVar Statement

[Topic intentionally blank - content coming in later builds]


Erase Statement

Releases an array instance. The Erase statement is equivalent to assigning Nothing to an array variable.

Erase arraylist

The required arraylist argument is one or more comma-delimited array variables to be erased.

See Also

Example


Erase Statement Example

This example uses the Erase statement to reinitialize the elements of fixed-size arrays and deallocate dynamic-array storage space.

' Declare array variables.
Dim NumArray(10) As Integer   ' Integer array.
Dim StrVarArray(10) As String   ' Variable-string array.
Dim StrFixArray(10) As String * 10   ' Fixed-string array.
Dim VarArray(10) As Variant   ' Variant array.
Dim DynamicArray() As Integer   ' Dynamic array.
ReDim DynamicArray(10)   ' Allocate storage space.
Erase NumArray   ' Each element set to 0.
Erase StrVarArray   ' Each element set to zero-length
   ' string ("").
Erase StrFixArray   ' Each element set to 0.
Erase VarArray   ' Each element set to Empty.
Erase DynamicArray   ' Free memory used by array.


FileCopy Statement Example

This example uses the FileCopy statement to copy one file to another. For purposes of this example, assume that SRCFILE is a file containing some data.

Dim SourceFile, DestinationFile
SourceFile = "SRCFILE"   ' Define source file name.
DestinationFile = "DESTFILE"   ' Define target file name.
FileCopy SourceFile, DestinationFile   ' Copy source to target.


For...Next Statement Example

This example uses the For...Next statement to create a string that contains 10 instances of the numbers 0 through 9, each string separated from the other by a single space. The outer loop uses a loop counter variable that is decremented each time through the loop.

Dim Words, Chars, MyString
For Words = 10 To 1 Step -1    ' Set up 10 repetitions.
   For Chars = 0 To 9   ' Set up 10 repetitions.
      MyString = MyString & Chars   ' Append number to string.
   Next Chars   ' Increment counter
   MyString = MyString & " "   ' Append a space.
Next Words


Get Statement Example

This example uses the Get statement to read data from a file into a variable. This example assumes that TESTFILE is a file containing five records of the user-defined type Record.

Type Record   ' Define user-defined type.
   ID As Integer
   Name As String * 20
End Type

Dim MyRecord As Record, Position   ' Declare variables.
' Open sample file for random access.
Open "TESTFILE" For Random As #1 Len = Len(MyRecord)
' Read the sample file using the Get statement.
Position = 3   ' Define record number.
Get #1, Position, MyRecord   ' Read third record.
Close #1   ' Close file.


GoTo Statement

Branches unconditionally to a specified line within a procedure.

Syntax

GoTo line

The required line argument can be any line label or line number.

Remarks

GoTo can branch only to lines within the procedure where it appears.

A GoTo to any label within a Catch or Finally block of a Try…Catch…Finally construct from outside the block is not allowed. Also not allowed is any GoTo within a Catch or Finally block to a label outside the block.

Note Too many GoTo statements can make code difficult to read and debug. Use structured control statements (Do...Loop, For...Next, If...Then...Else, Select Case) whenever possible.

See Also

Example


GoTo Statement Example

This example uses the GoTo statement to branch to line labels within a procedure.

Sub GotoStatementDemo()
Dim Number, MyString
   Number = 1    ' Initialize variable.
   ' Evaluate Number and branch to appropriate label.
   If Number = 1 Then GoTo Line1 Else GoTo Line2

Line1:
   MyString = "Number equals 1"
   GoTo LastLine   ' Go to LastLine.
Line2:
   ' The following statement never gets executed.
   MyString = "Number equals 2"
LastLine:
   Debug.Print MyString   ' Print "Number equals 1" in
      ' the Immediate window.
End Sub


Input # Statement Example

This example uses the Input # statement to read data from a file into two variables. This example assumes that TESTFILE is a file with a few lines of data written to it using the Write # statement; that is, each line contains a string in quotations and a number separated by a comma, for example, ("Hello", 234).

Dim MyString, MyNumber
Open "TESTFILE" For Input As #1   ' Open file for input.
Do While Not EOF(1)   ' Loop until end of file.
   Input #1, MyString, MyNumber   ' Read data into two variables.
   Debug.Print MyString, MyNumber   ' Print data to the Immediate window.
Loop
Close #1   ' Close file.


Line Input # Statement Example

This example uses the Line Input # statement to read a line from a sequential file and assign it to a variable. This example assumes that TESTFILE is a text file with a few lines of sample data.

Dim TextLine
Open "TESTFILE" For Input As #1   ' Open file.
Do While Not EOF(1)   ' Loop until end of file.
   Line Input #1, TextLine   ' Read line into variable.
   Debug.Print TextLine   ' Print to the Immediate window.
Loop
Close #1   ' Close file.


MkDir Statement Example

This example uses the MkDir statement to create a directory or folder. If the drive is not specified, the new directory or folder is created on the current drive.

MkDir "MYDIR"   ' Make new directory or folder.


RaiseEvent Statement Example

The following example uses events to count off seconds during a demonstration of the fastest 100 meter race. The code illustrates all of the event-related methods, properties, and statements, including the RaiseEvent statement.

The class that raises an event is the event source, and the classes that implement the event are the sinks. An event source can have multiple sinks for the events it generates. When the class raises the event, that event is fired on every class that has elected to sink events for that instance of the object.

The example also uses a form (Form1) with a button (Command1), a label (Label1), and two text boxes (Text1 and Text2). When you click the button, the first text box displays "From Now" and the second starts to count seconds. When the full time (9.84 seconds) has elapsed, the first text box displays "Until Now" and the second displays "9.84"

The code for Form1 specifies the initial and terminal states of the form. It also contains the code executed when events are raised.

Option Explicit

Private WithEvents mText As TimerState

Private Sub Command1_Click()
    Text1.Text = "From Now"
    Text1.Refresh
    Text2.Text = "0"
    Text2.Refresh
    Call mText.TimerTask(9.84)
End Sub

Private Sub Form_Load()
    Command1.Caption = "Click to Start Timer"
    Text1.Text = ""
    Text2.Text = ""
    Label1.Caption = "The fastest 100 meters ever run took this long:"
    Set mText = New TimerState
    End Sub

Private Sub mText_ChangeText()
    Text1.Text = "Until Now"
    Text2.Text = "9.84"
End Sub

Private Sub mText_UpdateTime(ByVal dblJump As Double)
    Text2.Text = Str(Format(dblJump, "0"))
    DoEvents
End Sub

The remaining code is in a class module named TimerState. Included among the commands in this module are the Raise Event statements.

Option Explicit
Public Event UpdateTime(ByVal dblJump As Double)
Public Event ChangeText()

Public Sub TimerTask(ByVal Duration As Double)
    Dim dblStart As Double
    Dim dblSecond As Double
    Dim dblSoFar As Double
    dblStart = Timer
    dblSoFar = dblStart

    Do While Timer < dblStart + Duration
        If Timer - dblSoFar >= 1 Then
            dblSoFar = dblSoFar + 1
            RaiseEvent UpdateTime(Timer - dblStart)
        End If
    Loop

    RaiseEvent ChangeText

End Sub


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Return Statement

[Topic intentionally blank - content coming in later builds]


RmDir Statement Example

This example uses the RmDir statement to remove an existing directory or folder.

' Assume that MYDIR is an empty directory or folder.
RmDir "MYDIR"   ' Remove MYDIR.


Time Statement Example

This example uses the Time statement to set the computer system time to a user-defined time.

Dim MyTime
MyTime = #4:35:17 PM#   ' Assign a time.
Time = MyTime   ' Set system time to MyTime.


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Unlock Statement

[Topic intentionally blank - content coming in later builds]


While...End While Statement

Executes a series of statements as long as a given condition is True.

While condition
[statements]
End While

Parameters

condition
Required. Boolean that evaluates to True or False. If condition is Null, condition is treated as False.
statements
Optional. One or more statements executed while condition is True.

Remarks

If condition is True, all statements are executed until the End While statement is encountered. Control then returns to the While statement and condition is again checked. If condition is still True, the process is repeated. If it is not True, execution resumes with the statement following the End While statement.

While...End While loops can be nested to any level. Each End While matches the most recent While.

Tip The Do...Loop statement provides a more structured and flexible way to perform looping.

See Also

Do...Loop Statement | Using Do...Loop Statements | With Statement


NGWS SDK Documentation

This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!

Access

[Topic intentionally blank - content coming in later builds]