 Visual Basic Help

Technical Support	Glossary	Other Information Sources

How to use Visual Basic

Learning Visual Basic

Building a Visual Basic Application

Creating the Interface

Setting Properties

Writing and Debugging Code

Reference

Properties	Programming Language
Events	Programming Environment
Objects	Trappable Errors
Copyright Notice


Creating the Interface

These steps are the first part of the process of creating a Visual Basic application.

Create a new project to organize the parts of your application.

Create a form for each window in your application.

Use the Toolbox to draw the controls for each form.

Create a menu bar for the main form.

More information

Adding and Deleting Controls at Run Time

Adding and Deleting Menu Commands at Run Time

Aligning an Item to the Grid

Assigning an Icon to a Form

Changing Grid Spacing

Creating a Control Array

Creating a Menu Bar

Creating a Menu Control Array

Displaying Graphics on a Form

Displaying or Hiding the Grid

Drawing a Control

Drawing Lines and Shapes on a Form

Selecting Controls


Setting Properties

This is the second part of the process of creating a Visual Basic application.

Set form and control properties.

More information

Accessing Screen Properties

Binding a Control to a Data Control

Properties List

Setting Colors

Setting Form and Control Properties

Setting Tab Order

Specifying Access Keys

Using MDI Features


Writing Code

These steps are the third part of the process of creating a Visual Basic application.

Write event procedures and general procedures.

Debug your code.

Create an executable file to turn the project into an application.

More information

Communicating with Other Applications

Controlling Program Flow

Debugging Code

Processing Files

Project Management

Using Language Elements

Using the Code Window


Using the Code Window

Adding, Editing and Deleting Watch Expressions

Executing a Specific Statement

Guidelines for Entering and Editing Code

Importing a Text File into Code

Replacing Text in Code

Saving and Loading forms in ASCII Format

Searching for Text in Code

Setting and Clearing Breakpoints

Splitting a Code Window Into Panes

Turning Syntax Checking On or Off

Using Example Code from Online Help

Using the Debug Window


Using Language Elements

Attaching an Event Procedure to a Form or Control

Calling Windows API Functions

Creating a Database

Creating a General Procedure

Creating Custom Colors

Entering Declarations in Code

Filling a Grid with Data from a Database

Finding a Procedure

Loading Constants from CONSTANT.TXT or DATACONS.TXT

Querying a Database

Specifying Access Keys

Accessing External Databases

Using SQL (Structured Query Language)


Debugging code

Adding, Editing and Deleting Watch Expressions

Continuing Execution

Debugging Checklist

Executing a Specific Statement

Guidelines for Entering and Editing Code

KnowledgeBase Articles from Microsoft Product Support

Restarting Execution

Setting and Clearing Breakpoints

Starting Execution

Tracing Execution

Turning Syntax Checking On or Off

Using Example Code from Online Help

Using Instant Watch

Using the Debug Window

Using Watch Expressions


Processing Files

Importing a Text File into Code

Saving and Loading Forms in ASCII Format

KnowledgeBase Articles from Microsoft Product Support

Replacing Text in Code

Saving Your Work

Searching for Text in Code


Communicating with other applications

Calling Windows API Functions

Creating a DDE Source or Destination Link

KnowledgeBase Articles from Microsoft Product Support

Using Dynamic Data Exchange (DDE)

Using Custom Controls


Controlling program flow

Ending Execution

Executing a Specific Statement

Halting Execution

KnowledgeBase Articles from Microsoft Product Support

Restarting Execution

Specifying a Startup Form

Starting Execution


Project management

Importing a Text File into Code

KnowledgeBase Articles from Microsoft Product Support

Saving and Loading Forms in ASCII Format

Saving Your Work

Setup Toolkit

Using Example Code from Online Help


Introducing and Learning Visual Basic

Learning Visual Basic

Fast paced lessons to teach you the basics of Visual Basic.  To run a lesson, choose the Learning Visual Basic command on Visual Basic's Help menu.

How Visual Basic Works

Creating an Application

Writing Event-driven Programs

Working with Forms and Controls

Adding Menus

Debugging Your Application

Using Color and Graphics


Objects

Global Objects

Clipboard Object

Debug Object

Printer Object

Screen Object

App Object

Interface Objects

Controls

Form

MDI Form

Data Access Objects

Data Access Overview

Data Control

Database Object

Dynaset Object

Field Object

Fields Collection

Index Object

Indexes Collection

QueryDef Object

Snapshot Object

Table Object

TableDef Object

TableDefs Collection


Programming Environment

Visual Basic Windows

Code Window

Color Palette

Debug Window

Menu Bar

Menu Design Window

Project Window

Properties Window

Toolbar

Toolbox

Interface Information

Keyboard Guide

Menus & Commands

Accessibility for People with Disabilities


Glossary


Glossary

A

access key

action query

active window

ANSI Character Set

application

argument

array

ASCII Character Set

assignment statement

automatic formatting

B

binary format

bit field

bit mask

bit

bitmap

bitwise

block If

Boolean data type

break mode

breakpoint

C

Cancel button

Caption

cascading event

check box

Checked check box

client area

client

Clipboard

collection

combo box

command line

comment

comparison operator

compile time

consistent

constant

container

control array

Control Panel

Control-menu box

Control-menu commands

control

copy buffer

cross hair

current index

current record

custom control

D

data page

data type

database

Database object

database objects

date separators

DDE

declaration

default color box

design time

destination

device context

dialog box

DLL

domain

domain function

drag-and-drop operation

Dynaset

E

editing key

Empty

Enabled check box

Enter button

enumerated data type

event procedure

event

exclusive

executable file

expression

F

focus

form code

form

frame

function key

Function procedure

G

general procedure

graphics method

grid

H

handle

hierarchical menu

horizontal scroll bar

I

icon

image control

inconsistent

index

index (Data Access)

insertion point

instance

K

keyboard modifier

keyword

L

label

line label

line number

list box

logic error

Long data type

M

Maximize button

MDI child

MDI form

metafile

method

Microsoft Access Data Types

millisecond

Minimize button

modal

modeless

module level

module variable

module

N

navigation key

Null

numeric expression

O

Object box

object data type

object

OLE

optimistic

option button

P

Paste Link command

path

pen

persistent bitmap

pessimistic

picture box

pixel

point

poke

position indicator

Printer object

Procedure box

procedure call

procedure level

procedure template

procedure

Project window

project

Properties window

Property list

property

Q

QueryDef

R

recordset

relational operators

reserved word

Restore button

run time

run-time error

S

scoping

seed

separator bar

server

Settings box

Shortcut box

shortcut key

size indicator

Snapshot

sort order

source

split bar

statement

string comparison

String data type

string expression

Sub procedure

submenu

syntax checking

syntax error

syntax

system modal

T

tab order

Table

text box

text file

three-dot button

title bar

twip

twos complement

type-declaration character

V

valid date separators

variable naming

variable

Variant data type

VarType

Visible check box

W

watch expression

Windows API


Events


Events

A

Activate

C

Change

Click

D

DblClick

Deactivate

DragDrop

DragOver

DropDown

E

Error

G

GotFocus

K

KeyDown

KeyPress

KeyUp

L

LinkClose

LinkError

LinkExecute

LinkNotify

LinkOpen

Load

LostFocus

M

MouseDown

MouseMove

MouseUp

P

Paint

PathChange

PatternChange

Q

QueryUnload

R

Reposition

Resize

RowColChange

S

Scroll

SelChange

T

Timer

U

Unload

Updated

V

Validate


Programming Topics
Programming Language


Programming Language

Operators

& Operator

* Operator

+ Operator

- Operator

/ Operator

\ Operator

^ Operator

A

Abs Function

AddItem Method

AddNew Method

Aggregate Functions, Domain (SQL Only)

Aggregate Functions for SQL Only

And Operator

ANSI Character Set

Any Data Type

AppActivate Statement

Append Method (Professional Edition Only)

AppendChunk Method

Arithmetic Operators

Arithmetic Operators

Arrange Method

Asc Function

As

Atn Function

B

Beep Statement

BeginTrans Statement

ByVal

C

Call Statement

ChDir Statement

ChDrive Statement

Choose Function

Chr, Chr$ Function

Circle Method

Clear Method

Clone Method (Professional Edition Only)

Close Method

Close Statement

Cls Method

Command, Command$ Function

Command Line Switches

Command Line Switches

CommitTrans Statement

CompactDatabase Statement

Comparison Operators

Concatenation Operators

Const Statement

Cos Function

CreateDatabase Function (Professional Edition Only)

CreateDynaset Method (Professional Edition Only)

CreateQueryDef Method (Professional Edition Only)

CreateSnapshot Method (Professional Edition Only)

CurDir, CurDir$ Function

Currency Data Type

CVDate Function

D

Data Access

Data Type Conversion Functions

Data Types

Date, Date$ Function

Date, Date$ Statement

DateAdd Function

DateDiff Function

DatePart Function

DateSerial Function

DateValue Function

Day Function

DDB Function

DDE Methods

Declare Statement

Deftype Statements

Delete Method

DeleteQueryDef Method (Professional Edition Only)

Derived Math Functions

Dim Statement

Dir, Dir$ Function

Do...Loop Statement

DoEvents Function

DoEvents Statement

Domain Aggregate Functions (SQL Only)

Double Data Type

Drag Method

E

Edit Method

Else

End Statement

EndDoc Method

Environ, Environ$ Function

EOF Function

Equivalent SQL Data Types

Eqv Operator

Erase Statement

Err, Erl Functions

Err Statement

Error, Error$ Function

Error Statement

Errors, Trappable Data Access

Errors, Trappable

Execute Method

ExecuteSQL Method

Exit Statement

Exp Function

F

False

FieldSize Method

FileAttr Function

FileCopy Statement

FileDateTime Function

FileLen Function

Financial Functions

FindFirst Method

FindLast Method

FindNext Method

FindPrevious Method

Fix Function

For...Next Statement

Format, Format$ Function

FreeFile Function

FreeLocks Statement

Function Statement

FV Function

G

Get Statement

GetAttr Function

GetChunk Method

GetData Method

GetFormat Method

GetText Method

Global Statement

GoSub...Return Statement

GoTo Statement

H

Hex, Hex$ Function

Hide Method

Hour Function

I

If...Then...Else Statement

IIf Function

Imp Operator

Input, Input$ Function

Input # Statement

InputBox, InputBox$ Function

InStr Function

Int Function

Integer Data Type

IPmt Function

IRR Function

Is Operator

IsDate Function

IsEmpty Function

Is

IsNull Function

IsNumeric Function

K

Kill Statement

L

LBound Function

LCase, LCase$ Function

Left, Left$ Function

Len Function

Let Statement

Like Operator

Line Input # Statement

Line Method

LinkExecute Method

LinkPoke Method

LinkRequest Method

LinkSend Method

ListFields Method (Professional Edition Only)

ListIndexes Method (Professional Edition Only)

ListParameters Method (Professional Edition Only)

ListTables Method (Professional Edition Only)

Load Statement

LoadPicture Function

Loc Function

Lock, Unlock Statements

LOF Function

Log Function

Logical Operators

Long Data Type

LSet Statement

LTrim, LTrim$ Function

M

Math Functions

Me

Mid, Mid$ Function

Mid, Mid$ Statement

Minute Function

MIRR Function

MkDir Statement

Mod Operator

Mod Operator

Month Function

Move Method

MoveFirst Method

MoveLast Method

MoveNext Method

MovePrevious Method

MsgBox Function

MsgBox Statement

N

Name Statement

New

NewPage Method

Next

Not Operator

Not Operator

Now Function

NPer Function

NPV Function

O

Oct, Oct$ Function

On Error Statement

On...GoSub Statement

On...GoTo Statement

On

Open Statement

OpenDatabase Function (Professional Edition Only)

OpenQueryDef Method (Professional Edition Only)

OpenTable Method (Professional Edition Only)

Operator Precedence

Option Base Statement

Option Compare Statement

Option Explicit Statement

Option

Or Operator

Or Operator

Other Operators

Other Operators

P

Partition Function

Pmt Function

Point Method

PopupMenu Method

PPmt Function

Print # Statement

Print Method

PrintForm Method

Private

PSet Method

Put Statement

PV Function

Q

QBColor Function

R

Randomize Statement

Rate Function

ReDim Statement

Refresh Method

RegisterDatabase Statement

Rem Statement

RemoveItem Method

RepairDatabase Statement

Reserved Words for SQL Only

Reset Statement

Resume Statement

RGB Function

Right, Right$ Function

RmDir Statement

Rnd Function

RollBack Method

Rollback Statement

RSet Statement

RTrim, RTrim$ Function

S

SavePicture Statement

Scale Method

Second Function

Seek Function

Seek Statement

Select Case Statement

SendKeys Statement

Set Statement

SetAttr Statement

SetData Method

SetDataAccessOption Statement

SetDefaultWorkspace Statement

SetFocus Method

SetText Method

Setup Kit Contents

Sgn Function

Shell Function

Show Method

Sin Function

Single Data Type

SLN Function

Space, Space$ Function

Spc Function

SQL Aggregate Function

SQL Reserved Words

Sqr Function

Static Statement

Step

Stop Statement

Str, Str$ Function

StrComp Function

String, String$ Function

String Data Type

Sub Statement

Switch Function

SYD Function

T

Tab Function

Tan Function

TextHeight Method

TextWidth Method

Time, Time$ Function

Time, Time$ Statement

Timer Function

TimeSerial Function

TimeValue Function

To

Trappable Data Access Errors

Trappable Errors

Trim, Trim$ Function

True

Type Statement

U

UBound Function

UCase, UCase$ Function

Unload Statement

Update Method

UpdateControls Method

UpdateRecord Method

User-Defined Data Type

V

Val Function

Variant Data Type

VarType Function

Visual Basic Data Types

W

Weekday Function

While...Wend Statement

Width # Statement

Write# Statement

X

XOR Operator

Y

Year Function

Z

ZOrder Method


Trappable Errors


Trappable Errors

See Also

Trappable errors can occur while an application is running, either within the Visual Basic environment or as a stand-alone executable.  Some of these can also occur during design time or compile time.  You can test and respond to trappable errors using the On Error statement and the Err function.

Remember, while developing in Visual Basic you can get help on any message by pressing F1.

Code	Message

3	Return without GoSub

5	Illegal function call

6	Overflow

7	Out of memory

9	Subscript out of range

10	Duplicate definition

11	Division by zero

13	Type mismatch

14	Out of string space

16	String formula too complex

17	Can't continue

19	No Resume

20	Resume without error

28	Out of stack space

35	Sub or Function not defined

48	Error in loading DLL

49	Bad 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

64	Bad file name

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 not set

92	FOR loop not initialized

93	Invalid pattern string

94	Invalid use of Null

95	Cannot destroy active form instance

281	No More DDE channels

282	No foreign application responded to a DDE initiate

283	Multiple applications responded to a DDE initiate

284	DDE channel locked

285	Foreign application won't perform DDE method or operation

286	Timeout occured while waiting for DDE response

287	User pressed ESC key during DDE operation

288	Destination is busy

289	Data not provided in DDE operation

290	Data in wrong format

291	Foreign application quit

292	DDE conversation closed or changed

293	DDE method invoked with no channel open

294	Invalid DDE Link format

295	Message queue filled; DDE message lost

298	DDE requires DDEML.DLL

320	Can't use character device names in filenames: 'item'

321	Invalid file format

341	Invalid object array index

342	Not enough room to allocate control array 'item'

343	Object not an array

344	Must specify index for object array

360	Object already loaded

361	Can't load or unload this object

362	Can't unload controls created at design time

363	Custom control 'item' not found

364	Object was unloaded

365	Unable to unload within this context

380	Invalid property value

382	'item' property cannot be set at run time

383	'item' property is read-only

384	'item' property can't be modified when form is minimized or maximized

385	Must specify index when using property array

386	'item' property not available at run time

387	'item' property can't be set on this control

388	Can't set Visible property from a parent menu

391	Name not available.

392	MDI Child forms cannot be hidden

393	'item' property cannot be read at runtime

394	'item' property is write-only

400	Form already displayed; can't show modally

401	Can't show non-modal form when a modal form is displayed

402	Must close or hide topmost modal form first

403	MDI forms cannot be shown modally

404	MDI child forms cannot be shown modally.

420	Invalid object reference

421	Method not applicable for this object

422	Property 'item' not found

424	Object required

425	Invalid object use

426	Only one MDI form allowed

460	Invalid clipboard format

461	Specified format does not match format of data

480	Can't create AutoRedraw image

481	Invalid picture

482	Printer error

708	File not found: |

710	File already open: |

712	Device IO error: |

713	File already exists: |

716	Disk full: |

719	Bad file name: |

722	Too many files: |

725	Permission denied: |

730	Path access error: |

731	Path not found: |

732	Must have startup form or Sub Main()

735	Can't save file to TEMP

740	Invalid procedure name

742	Not enough room to paste contents into current line

743	Unable to set next statement

744	Search text not found

745	Text would be too long. Edit prevented

746	One or more replacements too long and not made

747	Syntax errors produced while replacing

748	An undo error has occurred. Further undo is unavailable

749	Watch expression too long. Expression truncated.

750	An expression must be selected

752	Error reading Tutorial file 'item'

753	Tutorial directory 'item' not found

754	Can't find Tutorial file 'item'

755	Not enough memory to load Tutorial

756	Duplicate procedure name

757	Can't find Windows Help .EXE file

758	Control must be same type as rest of array

759	Array already has a control at index 'item'

760	Not a legal object name: 'item'

761	Must specify which item(s) to print

762	Can't clear INDEX property without changing NAME

764	| is a control name

765	Controls without the align property cannot be placed directly on the MDI form

766	Event handler must be a Sub procedure

768	Event procedure argument has incorrect data type

769	Menu subitem skipped a level

770	Can't put check mark here

771	Can't assign shortcut key to menu name

772	Can't use separator bar as menu name

773	Menu control must have a name

774	Menu control array element must have an index

775	Menu control array indices must be in ascending order

776	Menu control array elements must be contiguous and within the same

777	Shortcut key already assigned

778	Separator may not be checked or disabled, or have an shortcut key

779	At least one submenu item must be visible

780	Valid Range: [1..32]

781	Valid Range:[24..1188]

783	Separator may not be the Window List menu

784	Can't have more than one Window List menu

785	New not allowed on this type

20000	Can't load Custom Control DLL: 'item'

20001	Can't unload Custom Control DLL; in use

20002	Can't quit at this time

20003	You'll have to restart your program after this edit--proceed anyway?

20004	'item' has been changed; must reset

20005	Reset halted programs so Code window can be closed?

20006	Not enough stack space to enter break mode--continue?

20007	Not enough stack space to enter break mode for error--must reset

20008	Line too long to edit--edit truncated line?

20009	Search complete

20011	Invalid command-line argument 'item'

20012	Save changes to 'item'?

20013	You already have a control named 'item'.  Do you want to create a control array?

20014	Error loading 'item'.  The code associated with this form could not be loaded.  Continue loading form?

20015	Error loading 'item'.  An error was encountered loading a property.  Continue?

20016	Error loading 'item'.  A control could not be loaded due to load error.  Continue?

20017	Form had old file format

20018	Replace existing 'item'?

20019	'item' does not exist

20020	'item' already exists in project

20021	'|' is a Read-Only file

20022	Errors during load. Refer to '|' for details

20023	'|' could not be loaded

20024	Version number missing or invalid; Visual Basic 2.0 assumed.

20025	String value to long to process; form load aborted

20048	Line |1: The file |2 could not be loaded.

Grid Messages

30000	Can not do a RemoveItem on a fixed row

30001	Can not do an AddItem in a fixed row

30002	Grid does not contain that row

30004	Invalid Column number for alignment

30005	Invalid Alignment value

30006	Unable to Allocate Memory For Grid

30008	Not a valid Picture type

30009	Invalid Row Value

30010	Invalid Column Value

30011	Unable to register the memory manager

30013	Invalid Row Height Value

30014	Invalid Column Width Value

30015	Can not remove last non-fixed row

30016	FixedRows must be one less than Rows value

30017	FixedColumns must be one less than columns value

OLE Messages

31001	Out of memory

31003	Can't open Clipboard

31004	No object

31006	Unable to close object

31007	Can't paste

31008	Invalid property value

31009	Can't copy

31017	Invalid format

31018	Class is not set

31019	Source Document is not set

31021	Invalid Action

31022	Unable to initialize OLE

31023	Invalid or unknown Class

31024	Unable to create link

31026	Source name is too long

31027	Unable to activate object

31028	Object not running

31029	Dialog already in use

31031	Invalid source for link

31032	Unable to create embedded object

31033	Unable to fetch Link source name

31034	Invalid Verb index

31035	Incorrect Clipboard format

31036	Error saving to file

31037	Error loading from file

31038	This control requires VB version 3.0 or greater

31039	Unable to access source document


See Also

Help:

Error Messages (Common Dialog)

Err Statement

Error Statement

Error$ Function

Resume Statement

Trappable Data Access Errors

Programmer's Guide:

Chapter 9, "Debugging"

Chapter 10, "Handling Run-Time Errors"


Trappable Data Access Errors


Trappable Data
Access Errors

See Also

Trappable errors can occur while an application is running, either within the Visual Basic environment or as a stand-alone executable.  These errors may be generated in operations that involve the data access functionality of Visual Basic.  You can test and respond to trappable errors using the On Error statement and the Err function.

Remember, while developing in Visual Basic you can get help on any message by pressing F1.

Code	Message

600	Set value not allowed on collections

601	Get value not allowed on collections

602	General ODBC error: 'Item'

603	ODBC - SQLAllocEnv failure

604	ODBC - SQLAllocConnect failure

605	OpenDatabase - invalid connect string

606	ODBC - SQLConnect failure 'Item'

607	Access attempted on unopened DataBase

608	ODBC - SQLFreeConnect error

609	ODBC - GetDriverFunctions failure

610	ODBC - SQLAllocStmt failure

611	ODBC - SQLTables (TableDefs.Refresh) failure: 'Item'

612	ODBC - SQLBindCol failure

613	ODBC - SQLFetch failure: 'Item'

614	ODBC - SQLColumns (Fields.Refresh) failure: 'Item'

615	ODBC - SQLStatistics (Indexes.Refresh) failure: 'Item'

616	Table exists - append not allowed

617	No fields defined - cannot append table

618	ODBC - SQLNumResultCols (CreateDynaset) failure: 'Item'

619	ODBC - SQLDescibeCol (CreateDynaset) failure: 'Item'

621	Row-returning SQL is illegal in ExecuteSQL method

622	CommitTrans/Rollback illegal - Transactions not support

623	Name not found in this collection

624	Unable to Build Data Type Table

625	Data type of field 'Item' not supported by target database

626	Attempt to Move past EOF

627	Dynaset is not updatable or Edit method has not been invoked

628	'Item' Dynaset method illegal - no scrollable cursor support

629	Warning: Item (ODBC - SQLSetConnectOption failure)

630	Property is read-only

631	Zero rows affected by Update method

632	Update illegal without previous Edit or AddNew method

633	Append illegal - Field is part of a TableDefs collection

634	Property value only valid when Field is part of a Dynaset

635	Cannot set the property of an object which is part of a Database object

636	Set field value illegal without previous Edit or AddNew method

637	Append illegal - Index is part of a TableDefs collection

637	Append illegal - Index is part of a TableDefs collection

638	Access attempted on unopened Dynaset

639	Field type is illegal

640	Field size illegal for specified Field Type

642	Reserved parameter must be FALSE

643	Property Not Found

644	ODBC - SQLConfigDataSource error 'Item'

645	ODBC Driver does not support exclusive access to Dynasets

646	GetChunk: Offset/Size argument combination illegal

647	Delete method requires a name argument

648	Data access objects require VBDB300.DLL

625	Data type of field 'Item' not supported by target database

631	Zero rows affected by Update method

639	Field type is illegal

640	Field size illegal for specified Field Type

641	Item illegal - no current record

642	Reserved parameter must be FALSE

646	GetChunk: Offset/Size argument combination illegal

2420	Syntax error in number

2421	Syntax error in date

2422	Syntax error in string

2423	Invalid use of '.', '!', or '()'.

2424	Unknown name

2425	Unknown function name

2426	Function isn't available in expressions

2427	Object has no value

2428	Invalid arguments used with domain function

2429	In operator without ()

2430	Between operator without And

2431	Syntax error

2432	Syntax error

2433	Syntax error

2434	Syntax error

2435	Extra )

2436	Missing ), ], or Item

2437	Invalid use of vertical bars

2438	Syntax error

2439	Wrong number of arguments used with function

2440	IIF function without ()

2442	Invalid use of parentheses

2443	Invalid use of Is operator

2445	Expression too complex

2447	Invalid use of '.', '!', or '()'.

2448	Can't set value.

2449	Invalid method in expression.

2450	Invalid reference to form 'Item'.

2451	Invalid reference to report 'Item'.

2452	Invalid reference to Parent property.

2453	Invalid reference to control 'Item'.

2454	Invalid reference to '!Item'.

2455	Invalid reference to property 'Item'.

2456	Invalid form number reference.

2457	Invalid report number reference.

2458	Invalid control number reference.

2459	Can't refer to Parent property in Design view.

2460	Can't refer to Dynaset property in Design view.

2461	Invalid section reference.

2462	Invalid section number reference.

2463	Invalid group level reference.

2464	Invalid group level number reference.

2465	Invalid reference to field 'Item'.

2466	Invalid reference to Dynaset property.

2467	Object referred to in expression no longer exists.

2468	Invalid argument used with DatePart, DateAdd or DateDiff function.

2469	Item1 in validation rule: 'Item2'.

2470	Item in validation rule.

2471	Item in query.

2472	Item in linked master field.

2473	Item1 in 'Item2' expression.

2474	No control is active.

2475	No form is active.

2476	No report is active.

2477	Invalid subclass 'Item' referred to in TypeOf function.

3001	Invalid argument.

3002	Couldn't start session.

3003	Couldn't start transaction; too many transactions already nested.

3004	Couldn't find database 'Item'.

3005	'Item' isn't a valid database name.

3006	Database 'Item' is exclusively locked.

3007	Couldn't open database 'Item'.

3008	Table 'Item' is exclusively locked.

3009	Couldn't lock table 'Item'; currently in use.

3010	Table 'Item' already exists.

3011	Couldn't find object 'Item'.

3012	Object 'Item' already exists.

3013	Couldn't rename installable ISAM file.

3014	Can't open any more tables.

3015	'Item' isn't an index in this table.

3016	Field won't fit in record.

3017	Field length is too long.

3018	Couldn't find field 'Item'.

3019	Operation invalid without a current index.

3020	Update without Addor Edit.

3021	No current record.

3021	No current record.

3022	Can't have duplicate key; index changes were unsuccessful.

3023	Addor Edit already used.

3024	Couldn't find file 'Item'.

3025	Can't open any more files.

3026	Not enough space on disk.

3027	Couldn't update; database is read-only.

3028	Couldn't initialize data access because file 'SYSTEM.MDA' couldn't be opened.

3029	Not a valid account name or password.

3030	'Item' isn't a valid account name.

3031	Not a valid password.

3032	Can't delete account.

3033	No permission for 'Item'.

3034	Commit or Rollback without BeginTrans.

3036	Database has reached maximum size.

3037	Can't open any more tables or queries.

3039	Couldn't create index; too many indexes already defined.

3040	Disk I/O error during read.

3041	Incompatible database version.

3042	Out of MS-DOS file handles.

3043	Disk or network error.

3044	'Item' isn't a valid path.

3045	Couldn't use 'Item'; file already in use.

3046	Couldn't save; currently locked by another user.

3047	Record is too large.

3048	Can't open any more databases.

3049	'Item' is corrupted or isn't a Microsoft Access database.

3050	Couldn't lock file; SHARE.EXE hasn't been loaded.

3051	Couldn't open file 'Item'.

3052	MS-DOS file sharing lock count exceeded.  You need to increase the number of locks installed with SHARE.EXE.

3053	Too many client tasks.

3054	Too many Memo or Long Binary fields.

3055	Not a valid file name.

3056	Couldn't repair this database.

3057	Operation not supported on attached tables.

3058	Can't have Null value in index.

3059	Operation canceled by user.

3060	Wrong data type for parameter 'Item'.

3061	Item1 parameters were expected, but only Item2 were supplied.

3062	Duplicate output alias 'Item'.

3063	Duplicate output destination 'Item'.

3064	Can't open action query 'Item'.

3065	Can't execute a non-action query.

3066	Query must have at least one output field.

3067	Query input must contain at least one table or query.

3068	Not a valid alias name.

3069	Can't have action query '<Item>' as an input.

3070	Can't bind name 'Item'.

3071	Can't evaluate expression.

3073	Operation must use an updatable query.

3074	Can't repeat table name 'Item' in FROM clause.

3075	Item1 in query expression 'Item2'.

3076	Item in criteria expression.

3077	Item in expression.

3078	Couldn't find input table or query 'Item'.

3079	Ambiguous field reference 'Item'.

3080	Joined table 'Item' not listed in FROM clause.

3081	Can't join more than one table with the same name (Item).

3082	JOIN operation 'Item' refers to a non-joined table.

3083	Can't use internal report query.

3084	Can't insert into action query.

3085	Undefined function 'Item' in expression.

3086	Couldn't delete from specified tables.

3087	Too many expressions in GROUP BY clause.

3088	Too many expressions in ORDER BY clause.

3089	Too many expressions in DISTINCT output.

3090	Resultant table may not have more than one Counter field.

3091	HAVING clause (Item) without grouping or aggregation.

3092	Can't use HAVING clause in TRANSFORM statement.

3093	ORDER BY clause (Item) conflicts with DISTINCT.

3094	ORDER BY clause (Item) conflicts with GROUP BY clause.

3095	Can't have aggregate function in expression (Item).

3096	Can't have aggregate function in WHERE clause (Item).

3097	Can't have aggregate function in ORDER BY clause (Item).

3098	Can't have aggregate function in GROUP BY clause (Item).

3099	Can't have aggregate function in JOIN operation (Item).

3100	Can't set field 'Item' in join key to Null.

3101	Join is broken by value(s) in fields 'Item'.

3102	Circular reference caused by 'Item'.

3103	Circular reference caused by alias 'Item' in query definition's SELECT list.

3104	Can't specify Fixed Column Heading 'Item' in a crosstab query more than once.

3105	Missing destination field name in SELECT INTO statement (Item).

3106	Missing destination field name in UPDATE statement (Item).

3107	Couldn't insert; no insert permission for table or query 'Item'.

3108	Couldn't replace; no replace permission for table or query 'Item'.

3109	Couldn't delete; no delete permission for table or query 'Item'.

3110	Couldn't read definitions; no read definitions permission for table or query 'Item'.

3111	Couldn't create; no create permission for table or query 'Item'.

3112	Couldn't read; no read permission for table or query 'Item'.

3113	Can't update 'Item'; field not updatable.

3114	Can't include Memo or Long Binary when you select unique values (Item).

3115	Can't have Memo or Long Binary in aggregate argument (Item).

3116	Can't have Memo or Long Binary in criteria (Item) for aggregate function.

3117	Can't sort on Memo or Long Binary (Item).

3118	Can't join on Memo or Long Binary (Item).

3119	Can't group on Memo or Long Binary (Item).

3120	Can't group on fields selected with '*' (Item).

3121	Can't group on fields selected with '*'.

3122	'Item' not part of aggregate function or grouping.

3123	Can't use '*' in crosstab query.

3124	Can't input from internal report query (Item).

3125	'Item' isn't a valid name.

3126	Invalid bracketing of name 'Item'.

3127	INSERT INTO statement contains unknown field name 'Item'.

3128	Must specify tables to delete from.

3129	Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.

3130	Syntax error in DELETE statement.

3131	Syntax error in FROM clause.

3132	Syntax error in GROUP BY clause.

3133	Syntax error in HAVING clause.

3134	Syntax error in INSERT statement.

3135	Syntax error in JOIN operation.

3136	Syntax error in LEVEL clause.

3137	Missing semicolon (;) at end of SQL statement.

3138	Syntax error in ORDER BY clause.

3139	Syntax error in PARAMETER clause.

3140	Syntax error in PROCEDURE clause.

3141	Syntax error in SELECT statement.

3142	Characters found after end of SQL statement.

3143	Syntax error in TRANSFORM statement.

3144	Syntax error in UPDATE statement.

3145	Syntax error in WHERE clause.

3146	ODBC--call failed.

3147	ODBC--data buffer overflow.

3148	ODBC--connection failed.

3149	ODBC--incorrect DLL.

3151	ODBC--connection to 'Item' failed.

3152	ODBC--incorrect driver version 'Item1'; expected version 'Item2'.

3153	ODBC--incorrect server version 'Item1'; expected version 'Item2'.

3154	ODBC--couldn't find DLL 'Item'.

3155	ODBC--insert failed.

3156	ODBC--delete failed.

3157	ODBC--update failed.

3158	Couldn't save record; currently locked by another user.

3159	Not a valid bookmark.

3160	Table isn't open.

3161	Couldn't decrypt file.

3162	Null is invalid.

3163	Couldn't insert or paste; data too long for field.

3164	Couldn't update field.

3165	Couldn't open .INF file.

3166	Missing memo file.

3167	Record is deleted.

3168	Invalid .INF file.

3169	Illegal type in expression.

3170	Couldn't find installable ISAM.

3171	Couldn't find net path or user name.

3172	Couldn't open PARADOX.NET.

3173	Couldn't open table 'MSysAccounts' in SYSTEM.MDA.

3174	Couldn't open table 'MSysGroups' in SYSTEM.MDA.

3175	Date is out of range or is in an invalid format.

3183	Not enough space on temporary disk.

3184	Couldn't execute query; couldn't find linked table.

3185	SELECT INTO remote database tried to produce too many fields.

3186	Couldn't save; currently locked by user 'Item2' on machine 'Item1'.

3187	Couldn't read; currently locked by user 'Item2' on machine 'Item1'.

3188	Couldn't update; currently locked by another session on this machine.

3189	Table 'Item1' is exclusively locked by user 'Item3' on machine 'Item2'.

3190	Too many fields defined.

3191	Can't define field more than once.

3192	Couldn't find output table 'Item'.

3196	Couldn't use 'Item'; database already in use.

3197	Data has changed; operation stopped.

3198	Couldn't start session.  Too many sessions already active.

3199	Couldn't find reference.

3200	Can't delete or change record. Since related records exist in table 'Item', referential integrity rules would be violated.

3201	Can't add or change record.  Referential integrity rules require a related record in table 'Item'.

3202	Couldn't save; currently locked by user 'Item2' on machine 'Item1'.

3203	Can't specify subquery in expression (Item).

3204	Database already exists.

3205	Too many crosstab column headers (Item).

3206	Can't create a relationship between a field and itself.

3207	Operation not supported on Paradox table with no primary key.

3208	Invalid Deleted entry in [dBASE ISAM] section in INI file.

3209	Invalid Stats entry in [dBASE ISAM] section in INI file.

3210	Connect string too long.

3211	Couldn't lock table 'Item'; currently in use.

3212	Couldn't lock table 'Item1'; currently in use by user 'Item3' on machine 'Item2'.

3213	Invalid Date entry in [dBASE ISAM] section in INI file.

3214	Invalid Mark entry in [dBASE ISAM] section in INI file.

3215	Too many Btrieve tasks.

3216	Parameter 'Item' specified where a table name is required.

3217	Parameter 'Item' specified where a database name is required.

3218	Couldn't update; currently locked.

3219	Can't perform operation; it is illegal.

3220	Wrong Paradox sort sequence.

3221	Invalid entries in [Btrieve ISAM] section in WIN.INI.

3222	Query can't contain a Database parameter.

3223	'Item' isn't a valid parameter name.

3224	Btrieve--data dictionary is corrupted.

3225	Encountered record locking deadlock while performing Btrieve operation.

3226	Errors encountered while using the Btrieve DLL.

3227	Invalid Century entry in [dBASE ISAM] section in INI file.

3228	Invalid CollatingSequence entry in [Paradox ISAM] section in INI file.

3229	Btrieve--can't change field.

3230	Out-of-date Paradox lock file.

3231	ODBC--field would be too long; data truncated.

3232	ODBC--couldn't create table.

3233	ODBC--incorrect driver version.

3234	ODBC--remote query timeout expired.

3235	ODBC--data type not supported on server.

3236	ODBC--encountered unexpected Null value.

3237	ODBC--unexpected type.

3238	ODBC--data out of range.

3239	Too many active users.

3240	Btrieve--missing WBTRCALL.DLL.

3241	Btrieve--out of resources.

3242	Invalid reference in SELECT statement.

3246	Operation not supported in transactions.

3247	ODBC--linked table definition has changed.

3248	Invalid NetworkAccess entry in INI file.

3249	Invalid PageTimeout entry in INI file.

3252	Illegal reentrancy during query execution.

3254	ODBC--Can't lock all records.

3255	ODBC--Can't change connect string parameter.

3256	Index file not found.

3257	Syntax error in WITH OWNERACCESS OPTION declaration.

3258	Query contains ambiguous (outer) joins.

3260	Couldn't update; currently locked by user 'Item2' on machine 'Item1'.

3261	Item

3262	Item

3264	No fields defined - cannot append table.

3265	Name not found in this collection.

3267	Property value only valid when Field is part of a recordset.

3268	Cannot set the property of an object which is part of a Database object.

3270	Property not found.

3271	Invalid property value.

3273	Method not applicable for this object.

3274	External table isn't in the expected format.

3277	Can't have more than 10 fields in an index.

3279	Database engine has already been initialized.

3280	Can't delete a field that is part of an index.

3281	Can't delete an index that is used in a relationship.

3284	Index already exists.

3287	Can't create index on Memo field or Long Binary field.

3289	Paradox: No primary index.

3290	Syntax error.

3291	Syntax error in CREATE TABLE statement.

3292	Syntax error in CREATE INDEX statement.

3293	Syntax error in column definition.

3294	Syntax error in ALTER TABLE statement.

3295	Syntax error in DROP INDEX statement.

3299	Several tables exist with that name; please specify owner, as in 'owner.table'.


idxRealDataAccessErrorsSee
See Also

Help:

Error Messages (Common Dialog)

Err Statement

Error Statement

Error$ Function

Resume Statement

Trappable Errors

Programmer's Guide:

Chapter 9, "Debugging"

Chapter 10, "Handling Run-Time Errors"


Properties List
Properties


Properties

A

Action (Common Dialog)

Action (OLE Control)

ActiveControl

ActiveForm

Alignment

Align

AppIsRunning

Archive

Attributes

AutoActivate

AutoRedraw

AutoSize

AutoVerbMenu

B

BackColor

BackStyle

BOF

Bookmark

Bookmarkable

BorderColor

BorderStyle

BorderWidth

C

CancelError

Cancel

Caption

CellSelected

Checked

Class

ClipControls

Clip

Col, Row

ColAlignment

CollatingOrder

Color

Cols

Columns

ColWidth

Connect

ControlBox

Copies

Count

CurrentX

CurrentY

D

DatabaseName

Database

DataChanged

DataField

Data

DataSource

DataText

DateCreated

DefaultExt

Default

DialogTitle

DisplayType

DragIcon

DragMode

DrawMode

DrawStyle

DrawWidth

Drive

E

EditMode

Enabled

EOF

Exclusive

EXEName

F

Fields

FileName

FileNumber

FileTitle

FillColor

FillStyle

Filter (Common Dialog)

Filter (Professional Edition Only)

FilterIndex

FixedAlignment

FixedCols

FixedRows

Flags (Color Dialog)

Flags (File Dialogs)

Flags (Font Dialog)

Flags (Print Dialog)

FontBold

FontCount

FontItalic

FontName

Fonts

FontSize

FontStrikethru

FontTransparent

FontUnderline

ForeColor

Format

FromPage

G

GridLines

GridLineWidth

H

hDC

Height

HelpCommand

HelpContext (Common Dialog)

HelpContextID

HelpFile

HelpKey

Hidden

HideSelection

HighLight

HostName

hWnd

I

Icon

Image

Index (Control Arrays)

Index (Data Access)

InitDir

Interval

ItemData

K

KeyPreview

L

LargeChange

LastModified

LastUpdated

LastUpdated

LeftCol

Left

LinkItem

LinkMode

LinkTimeout

LinkTopic

ListCount

List

ListIndex

LockEdits

lpOLEObject

M

Max, Min

Max (Common Dialog)

MaxButton

MaxFileSize

MaxLength

MDIChild

Min (Common Dialog)

MinButton

MousePointer

MultiLine

MultiSelect

N

Name

NewIndex

NoMatch

Normal

O

ObjectAcceptFormatsCount

ObjectAcceptFormats

ObjectGetFormatsCount

ObjectGetFormats

Object

ObjectVerbFlags

ObjectVerbsCount

ObjectVerbs

OleTypeAllowed

OleType

Options

OrdinalPosition

P

Page

Parent

PasswordChar

PasteOK

Path

Pattern

Picture

PrevInstance

Primary

PrinterDefault

Q

QueryTimeout (Professional Edition Only)

R

ReadOnly

RecordCount

Recordset

RecordSource

RowHeight

Rows

S

ScaleHeight

ScaleLeft

ScaleMode

ScaleTop

ScaleWidth

ScrollBars

SelCount

Selected

SelEndCol

SelEndRow

SelLength

SelStartCol

SelStart

SelStartRow

SelText

Shape

Shortcut

SizeMode

Size

SmallChange

Sort (Professional Edition Only)

Sorted

SourceDoc

SourceField

SourceItem

SourceTable

SourceTableName

SQL (Professional Edition Only)

Stretch

Style

System

T

TabIndex

TabStop

Tag

Text

Title

ToPage

Top

TopIndex

TopRow

Transactions

TwipsPerPixelX

TwipsPerPixelY

Type

U

Unique

Updatable

UpdateOptions

V

Value

Verb

Visible

W

Width

WindowList

WindowState

WordWrap

X

X1

X2

Y

Y1

Y2


Copyright Notice
Copyright © 1991-1993 Microsoft Corp.  All rights reserved.

Microsoft, MS, and MS-DOS are registered trademarks, and Windows and the Windows logo are trademarks of Microsoft Corporation.

Information in this document is subject to change without notice.  Companies, names, and data used in examples herein are fictitious unless otherwise noted. No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without express written permission of Microsoft Corporation.

The software and/or databases described in this document are furnished under a license agreement or nondisclosure agreement. The software and/or databases may be used or copied only in accordance with the terms of the agreement.  It is against the law to copy the software except as specifically allowed in the license or nondisclosure agreement.  No part of this document may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or information storage and retrieval systems, for any purpose other than the purchaser's personal use, without the express written permission of Microsoft Corporation.


AddNew Method

See Also

Description

Clears the copy buffer in preparation for creating a new record in a Table or Dynaset.

Syntax

recordset.AddNew

Remarks

The AddNew method uses these parts:

Part	Description

recordset	The Recordset property of a data control; in the Professional Edition, can be an object variable that identifies a Table or Dynaset.  If recordset does not exist or is not open, an error occurs.

The AddNew method sets all fields in the copy buffer to Null and makes it the current record.  After putting data in the record, use the Update method to add the record to the recordset.  If you add a record to a Table, the record does not immediately appear in any currently existing Dynaset based on that Table.  If you add a record to a Dynaset, however, the record immediately appears in the underlying Table.

While already editing a new record, using AddNew again clears any changes made to fields in the copy buffer since the last AddNew.  With a data control, if an Edit or AddNew operation is pending when you use one of the Find or Move methods or close the recordset, Update is automatically invoked if not stopped during the Validate event.

The new record's apparent position in the recordset depends on whether you add new records to a Table or a Dynaset.  If you add a new record to a Table, the new record appears in its position in the table according to the current index.  If you add a new record to a Dynaset, the new record appears at the end of the Dynaset.

When you use the Update method after AddNew, the record that was current before you executed AddNew becomes the current record again, and the new record is added to the recordset.  To make the new record current after you use Update:

Set the Bookmark equal to the LastModified property.

Use MoveLast with a Dynaset or a Table that does not have an index.

In the Professional Edition, use Seek with a Table that has an index.

Caution   In the Professional Edition, if you are not using a data control and use one of the Find or Move methods or close the recordset while an Edit or AddNew operation is pending, any existing changes will be lost and no error will occur.

In a multiuser environment with the recordset's LockEdits property set to True, using Edit or AddNew locks the page until after Update has completed the updating process.  If the LockEdits property is False, the page is not locked until the actual Update operation.


lanAddNewSee
See Also

Help:

Delete Method

Edit Method

EditMode Property

FindFirst, FindLast, FindNext, FindPrevious Methods

LastModified Property

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

Seek Method (Professional Edition Only)

Update Method

Validate Event

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


AppendChunk Method

See Also	Example

Description

Appends data from a String to a Memo or Long Binary field in the copy buffer of a specified Table or Dynaset.

Syntax

fieldobject.AppendChunk( source )

Remarks

The AppendChunk method uses these parts:

Part	Description

fieldobject	A field of Memo or Long Binary field data type (not valid on fields of other field data types).  If a data control is used, the field is a member of the Fields collection in a recordset.  In the Professional Edition, can also be an object variable identifying a Field in a recordset.

source	String expression containing the data you want to append to fieldobject.

AppendChunk allows you to manipulate pieces of data, which conserves memory when working with fields larger than 64K.

If there is no current record when you use AppendChunk, an error occurs.

In Microsoft Access, the Long Binary field data type is called an OLE Object field data type.


lanAppendChunkSee
See Also

Help:

FieldSize Method

GetChunk Method

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


lanAppendChunkX
AppendChunk Method Example

This example uses AppendChunk with a data control to save the contents of a separate file into a field.  You would call this procedure with the path and name of the file you want to put into your database.  This procedure works for either Memo or Long Binary fields.

Sub PasteBigFile (FName As String)
Dim TotalSize As Long, CurChunk As String
Dim I As Integer, FNum As Integer, ChunkSize As Integer
ChunkSize = 12000	' Set size of chunk.
Data1.RecordSet.Edit	' Enter Edit mode.
Data1.RecordSet.Fields("Comments") = ""	' Clear Comments field.
FNum = FreeFile	' Get free file number.
Open FName For Binary As #FNum	' Open the file.
TotalSize = LOF(FNum)
Do While Not EOF(FNum)
If TotalSize - Seek(FNum) < ChunkSize Then
ChunkSize = TotalSize - Seek(FNum) + 10
End If
CurChunk = String$(ChunkSize + 1, 32)
Get #FNum, , CurChunk	' Read chunk from file.
If InStr(CurChunk, Chr$(0)) > 0 Then
CurChunk = Left$(CurChunk, InStr(CurChunk, Chr$(0)) - 1)
End If
' Append chunk to Comments field.
Data1.RecordSet.Fields("Comments").AppendChunk (CurChunk)
Loop
Data1.RecordSet.Update	' Save the record.
Close FNum	' Close the file.
End Sub


Close Method

See Also

Description

Closes a specified Database, QueryDef, or recordset.

Syntax

database.Close

recordset.Close

querydef.Close (Professional Edition Only)

Remarks

The Close method uses these parts:

Part	Description

database	The Database property of a data control.  In the Professional Edition, can also be an object variable identifying an open Database.

recordset	The Recordset property of a data control.  In the Professional Edition, can also be an object variable identifying an open Table, Dynaset, or Snapshot.

querydef	In the Professional Edition, an object variable that identifies an open QueryDef.

If you close the recordset or database of a data control, the data control sets all bound controls to Null and nothing will happen when a user clicks the buttons on the data control.

Using Close on the Recordset property of a data control automatically invokes the Update method if an Edit or AddNew operation is pending.  Using Close on the Database property of a data control automatically closes all open recordsets.  Unloading a form automatically closes a data control's Database property.

If the object is already closed when you use Close, an error occurs.

Caution   In the Professional Edition, if you are not using a data control you should use Close on all open recordsets before you close a database.  Otherwise you might lose changes from pending Edit or AddNew operations.

In the Professional Edition, any local object variables identifying Databases, Dynasets, QueryDefs, or Tables are automatically closed when the procedure exits.  If you are not using a data control, attempting to close a Database that has open recordsets will generate an error.


lanCloseMethodSee
See Also

Help:

CommitTrans Method

Data Access

Edit Method

Unload Statement

Update Method

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


Delete Method

See Also	Example 1	Example 2 (Professional Edition Only)

Description

Deletes the current record in a specified Table or Dynaset.  In the Professional Edition, deletes a specified member from a collection.

Syntax

recordset.Delete

collection.Delete membername (Professional Edition Only)

Remarks

The Delete method uses these parts:

Part	Description

recordset	The Recordset property of a data control.  In the Professional Edition, can also be an object variable identifying a Table or Dynaset.

collection	In the Professional Edition, a TableDefs or Indexes collection.

membername	In the Professional Edition, a string expression that is the name of an existing TableDef or Index in the specified collection.

Before you use Delete, a record must be recognized as current in recordset or an error will occur.  To make a record current, use one of the Move or Find methods, or the Bookmark property.  In the Professional Edition, you can use the Seek method with a Table object.

In a Table, Delete removes the current record.  In a Dynaset and the data control's Recordset property, Delete sets the current record to Null and removes the current record from its underlying tables.

The deleted record remains current, but any references to it produce an error.  Until you move to another record, what was the next record remains the next record, and the previous record remains the previous record.  Once you move to another record, you can't make the deleted record current again.

To delete more than one record, it is faster to execute an action query.  For example, in a list of publishers, you can delete those from New York with this statement:

Data1.Database.Execute "DELETE FROM Publishers WHERE State = 'NY'"

In the Professional Edition, deleting a member of the TableDefs collection deletes the table and all data in the table.  You can't delete a Field from a Fields collection of a TableDef; but you can accomplish the same thing by creating a duplicate table without the Field, and then copying the data from the first Table into the new one.

To restore a deleted record, you must have used BeginTrans before using the Delete method, then you can use the Rollback method.


lanDeleteSee
See Also

Help:

AddNew Method

BeginTrans, CommitTrans, Rollback Methods

Edit Method

FindFirst, FindLast, FindNext, FindPrevious Methods

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


lanDeleteX1
Delete Method Example 1

This example finds a record in the Recordset property of a data control named Data1 and deletes it.

' Find the record you want to delete.
Data1.Recordset.FindFirst "PubNum = 9"
If Not Data1.Recordset.NoMatch Then	' Check if record found.
Data1.Recordset.Delete	' Delete the record.
End If


lanDeleteX2
Delete Method Example 2 (Professional Edition Only)

This example finds and then deletes a record.

Dim Db As Database, MyTable As Table
Set Db = OpenDatabase("BIBLIO.MDB")
Set MyTable = Db.OpenTable("Publishers")
MyTable.FindFirst "PubNum = 9"	' Find a specific record.
If Not MyTable.NoMatch Then	' Check if record found.
MyTable.Delete	' Delete record.
End If

This example adds and then deletes an Index from a TableDef.

Dim MyDB As Database, MyTableDef As TableDef, MyIndex As New Index
Set MyDB = OpenDatabase("BIBLIO.MDB")	' Open the database.
Set MyTableDef = MyDB.TableDefs("Publishers")	' Set the TableDef.
MyIndex.Name = "Author Name"	' Set Index properties.
MyIndex.Fields = "Author"
MyTableDef.Indexes.Append MyIndex	' Add Index to TableDef.
...
MyTableDef.Indexes.Delete "Author Name"	' Delete the Index.


Edit Method

See Also	Example

Description

Opens the current record in a specified recordset for editing by copying it to the copy buffer.

Syntax

recordset.Edit

Remarks

The Edit method uses these parts:

Part	Description

recordset	The Recordset property of a data control.  In the Professional Edition, can also be an object variable identifying a Table or Dynaset.

Use the Edit method to allow changes to the current record and to lock the current page with pessimistic locking to prevent changes by other users.  After the user has changed the record, use the Update method to save changes.  Using Edit a second time without using Update will undo any changes made to the record in the copy buffer.

In a multiuser environment with the recordset's LockEdits property set to True, using Edit or AddNew locks the page until after Update has completed the updating process.  If the LockEdits property is False, the page is not locked until the actual Update operation.

With a data control, if an Edit or AddNew operation is pending when you use one of the Find or Move methods or close the recordset, Update is automatically invoked if not stopped during the Validate event.

The current record remains current after an Edit operation.

Caution   In the Professional Edition, if you are not using a data control and use one of the Find or Move methods, or close the recordset while an Edit or AddNew operation is pending, any existing changes will be lost and no error will occur.

Using Edit will produce an error in the following conditions:

There is no current record.

The database or recordset is read-only.

No fields in the record are updatable.

The database or recordset was opened for exclusive use by another user.


lanEditSee
See Also

Help:

AddNew Method

CreateDynaset Method (Professional Edition Only)

Delete Method

EditMode Property

LockEdits Property

OpenTable Method (Professional Edition Only)

Update Method

Validate Event

Data Access Guide:

Chapter 3, "Creating Applications to Manipulate Data"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


lanEditEx
Edit Method Example

This example finds the first record in a recordset matching the search criteria and opens it for editing.  Then it changes the value in the Title field and saves the change using the Update method.

Dim Criteria As String, NewTitle As String
Criteria = "Title = 'My Right Hand'"	' Create the criteria.
NewTitle = "My Right Foot"	' Create a new title.
Data1.Recordset.FindFirst Criteria	' Make record current.
Do While Not Data1.Recordset.NoMatch
If Not Data1.Recordset.NoMatch Then
Data1.Recordset.Edit	' Open record.
Data1.Recordset.Fields("Title") = NewTitle	' Enter new title.
Data1.Recordset.Update	' Save changes.
End If
Data1.Recordset.FindNext Criteria
Loop

The following example achieves the same effect:

Dim SQLQuery As String, NewTitle As String
' Create the Criteria string
SQLQuery = "UPDATE Titles SET Title = 'My Right Foot'"
SQLQuery = SQLQuery & " WHERE Title = 'My Right Hand'"
Data1.Database.Execute SQLQuery	' Execute the query.


FindFirst, FindLast, FindNext, FindPrevious Methods

See Also	Example 1	Example 2 (Professional Edition Only)

Description

Locate the first, last, next, or previous record that satisfies the specified criteria and make that record the current record.

Syntax

recordset.FindFirst criteria

recordset.FindLast criteria

recordset.FindNext criteria

recordset.FindPrevious criteria

Remarks

Each Find method uses these parts:

Part	Description

recordset	The Recordset property of a data control.  In the Professional Edition, can also be an object variable identifying a Dynaset, or Snapshot.

criteria	String expression (the WHERE clause in an SQL string without the word "WHERE") specifying the records you want.

If recordset contains more than one record that matches criteria, FindFirst locates the first occurrence, FindNext locates the next occurrence, and so on.  You can follow a Find operation with a Move operation, such as MoveNext, which moves to the next record regardless of whether it matches any criteria.

If no matching records are found, the NoMatch property is True and the current record remains the same as before the Find method was used.

With a data control, if an Edit or AddNew operation is pending when you use one of the Find or Move methods, Update is automatically invoked if not stopped during the Validate event.

Caution   In the Professional Edition, if you are not using a data control and use one of the Find or Move methods while an Edit or AddNew operation is pending, any existing changes will be lost and no error will occur.


lanFindMethodsSee
See Also

Help:

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

NoMatch Property

Seek Method (Professional Edition Only)

Validate Event

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


lanFindMethodsX1
FindFirst, FindLast, FindNext, FindPrevious Methods Example 1

This example finds the first record matching the specified criteria, and then finds the next matching record.

Dim MyCriteria As String
MyCriteria = "State = 'NY'"	' Set the criteria.
Data1.Recordset.FindFirst MyCriteria	' Find first matching record.
If Not Data1.Recordset.NoMatch Then...	' Check if record is found.
...
Data1.Recordset.FindNext MyCriteria	' Find next matching record.


lanFindMethodsX2
FindFirst, FindLast, FindNext, FindPrevious Methods Example 2 (Professional Edition Only)

This example creates a Dynaset and then uses FindFirst to locate the first record satisfying the title condition.

Dim MyCriteria As String, MyDB As Database, MySet As Dynaset
MyCriteria = "State = 'NY'" 	' Define search criteria.
Set MyDB = OpenDatabase("BIBLIO.MDB")
' Create a Dynaset based on Publishers table.
Set MySet = MyDB.CreateDynaset("Publishers")
MySet.FindFirst MyCriteria	' Find first matching record.
If Not Data1.Recordset.NoMatch Then...	' Check if record is found.
...
MySet.FindNext MyCriteria	' Find next matching record.


MoveFirst, MoveLast, MoveNext, MovePrevious Methods

See Also

Description

Move to the first, last, next, or previous record in a specified recordset and makes that record the current record.

Syntax

recordset.MoveFirst

recordset.MoveLast

recordset.MoveNext

recordset.MovePrevious

Remarks

Each Move method uses these parts:

Part	Description

recordset	The Recordset property of a data control.  in the Professional Edition, can also be an object variable identifying a Table, Dynaset, or Snapshot.  If recordset does not exist or is an unopened Table, an error occurs.

The buttons on a data control correspond to the MoveFirst, MovePrevious, MoveNext, and MoveLast methods, respectively.  The BOF and EOF properties never become True when using the data control buttons.

If you use MoveFirst or MoveLast when the first or last record is already current, the current record doesn't change.

If you use MoveLast on a Dynaset which is the result of a query, you force the query to completion.

If you use MovePrevious when the first record is current, the BOF property will be True and there will be no current record. If you use MovePrevious again, an error occurs and BOF remains True.

If you use MoveNext when the last record is current, the EOF property will be True and there will be no current record. If you use MoveNext again, an error occurs and EOF remains True.

When you open recordset, the first record is current and the BOF property is False.  If recordset contains no records, both BOF and EOF properties are True, and there is no current record.

With a data control, if an Edit or AddNew operation is pending when you use one of the Find or Move methods, Update is automatically invoked if not stopped during the Validate event.

Caution   In the Professional Edition, if you are not using a data control and use one of the Find or Move methods while an Edit or AddNew operation is pending, any existing changes will be lost and no error will occur.

In the Professional Edition, if recordset refers to a Table, movement follows the Table's current index.  If there is no current index, movement between records follows the order in which records were added.


lanMoveMethodsSee
See Also

BOF Property

EditMode Property

EOF Property

FindFirst, FindLast, FindNext, FindPrevious Methods

Index Property (Data Access)

RecordCount Property

Seek Method (Professional Edition Only)

Update Method

Validate Event

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"

Chapter 4, "Using Visual Basic with Data Access Objects"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


GetChunk Method

See Also	Example

Description

Returns all or a portion of a Memo or Long Binary field in a specified recordset.

Syntax

stringvar = fieldobject.GetChunk( offset, numbytes )

Remarks

The GetChunk method uses these parts:

Part	Description

stringvar	A variable of type String or Variant that will receive the data from the field named by fieldobject.

fieldobject	A field of Memo or Long Binary type (not valid on fields of other field data types).  It can be a member of the Fields collection in a recordset.  In the Professional Edition, can also be an object variable identifying a Field in a recordset.

offset	Numeric expression for the number of bytes to skip before copying begins.

numbytes	Numeric expression for the number of bytes you want to return.

GetChunk allows you to manipulate pieces of data, which conserves memory when working with fields larger than 64K.

If offset is 0, GetChunk begins copying from the first byte of the field.

If numbytes is larger than about 64K, an error occurs.  After assigning the results of GetChunk to a string variable, you can use the Len function to determine the number of bytes returned.  If numbytes is larger than the number of bytes in the field, only the actual number of bytes of data in the field are returned.  If numbytes is negative, an error occurs.

In Microsoft Access, the Long Binary field data type is called an OLE Object field data type.


lanGetChunkSee
See Also

Help:

AppendChunk Method

Data Control

Fields Collection

FieldSize Method

Len Function

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


lanGetChunkEx
GetChunk and FieldSize Methods Example

This example uses GetChunk with a data control to save the contents of a field to a separate file.  You would call this procedure with the path and name of the file where you want to save the contents of the field.  This procedure works for either text or binary fields.

Sub GetBigFile (FName As String)
Dim NumChunks As Long, TotalSize As Long
Dim RemChunk As Integer, CurSize As Integer
Dim I As Integer, FNum As Integer, CurChunk As String
ChunkSize = 2000	' Set size of chunk.
' Get field size.
TotalSize = Data1.RecordSet.Fields("Comments").FieldSize()
NumChunks = TotalSize \ ChunkSize	' Set number of chunks.
' Set number of remaining bytes.
RemChunk = TotalSize Mod ChunkSize
' Set starting size of chunk.
CurSize = ChunkSize
FNum = FreeFile	' Get free file number.
Open FName For Binary As #FNum	' Open the file.
For I = 0 To NumChunks
If I = NumChunks Then CurSize = RemChunk
CurChunk = Data1.RecordSet.Fields("Comments").GetChunk(I * ChunkSize, CurSize)
Put #FNum, , CurChunk	' Write chunk to file.
Next I
Close FNum
End Sub


FieldSize Method

See Also	Example

Description

Returns the number of bytes in a text or binary field.

Syntax

sizevar = fieldobject.FieldSize( )

Remarks

The FieldSize method uses these parts:

Part	Description

sizevar	A variable of Long or Variant data type.

fieldobject	A field of Memo or Long Binary field data type (not valid on fields of other field data types).  Can be a member of the Fields collection in a recordset.  In the Professional Edition, can also be an object variable identifying a Field in a recordset.

Since a binary field can be very large, always assign the value returned by FieldSize to a variable of Long or Variant data type.

You can use FieldSize with the AppendChunk and GetChunk methods to manipulate large fields.

An error occurs if you use FieldSize with fields other than Memo or Long Binary field data types.


lanFieldSizeSee
See Also

Help:

AppendChunk Method

Fields Collection

GetChunk Method

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


Update Method

See Also	Example

Description

Saves the contents of the copy buffer to a specified Table or Dynaset.

Syntax

recordset.Update

Remarks

The Update method uses these parts:

Part	Description

recordset	The Recordset property of a data control.  In the Professional Edition, can also be an object variable that identifies a Table or Dynaset.

Use Update to save any changes to a record after using Edit or AddNew.  With a data control, if an Edit or AddNew operation is pending when you move to another record or close the recordset, Update is automatically invoked if not stopped during the Validate event.

Caution   In the Professional Edition, if you are not using a data control and move to another record or close the recordset while an Edit or AddNew operation is pending, any existing changes will be lost and no error will occur.

To edit a record, use the Edit method to copy the current record to the copy buffer for editing. You must use Edit before you use Update or an error occurs.

In a multiuser environment with the recordset's LockEdits property set to True, using Edit or AddNew locks the page until after Update has completed the updating process.  If the LockEdits property is False, the page is not locked until the actual Update operation.


lanUpdateSee
See Also

Help:

AddNew Method

CreateDynaset Method (Professional Edition Only)

CreateSnapshot Method (Professional Edition Only)

Edit Method

EditMode Property

OpenTable Method (Professional Edition Only)

Validate Event

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


lanUpdateEx
Update Method Example

This example changes the Title field in the current record of a data control, and uses the Update method to save the changes.

Data1.Recordset.Edit	' Enable editing.
Data1.Recordset.Fields("Title") = "My Right Foot"	' Change title.
Data1.Recordset.Update	' Save changes.


CreateQueryDef Method (Professional Edition Only)

See Also	Example

Description

Creates a new QueryDef in a specified database.

Syntax

Set querydef = database.CreateQueryDef(name [, sqltext ])

Remarks

The CreateQueryDef method uses these parts:

Part	Description

querydef	Object variable for the QueryDef object you want to create.

database	Object variable identifying an open database that will store the new QueryDef.

name	String expression that is the name of the new QueryDef which is saved in the database itself.  You use this name with the OpenQueryDef and DeleteQueryDef methods.

sqltext	String expression (a valid SQL statement) defining the QueryDef.  If you omit this argument, you must define the QueryDef by setting its SQL property before using it.

You can use QueryDef objects to find and return records in the CreateDynaset and CreateSnapshot methods.

QueryDefs are listed in the TableDefs collection of a Database.  To test if a member of the TableDefs collection is really a QueryDef, examine the Attributes property of a member of the TableDefs collection.

To open a QueryDef for changes, use the OpenQueryDef method.  The QueryDef is automatically saved when you create or change it, even if it wasn't defined by sqltext.

To execute a QueryDef that performs an action, such as update, delete, or insert, use the Execute method.  If you attempt to use a QueryDef that has not yet been defined by sqltext or the SQL property setting, an error occurs.

To delete an existing QueryDef, use the DeleteQueryDef method.


lanCreateQueryDefSee
See Also

Help:

Close Method

CreateDynaset Method (Professional Edition Only)

CreateSnapshot Method (Professional Edition Only)

DeleteQueryDef Method (Professional Edition Only)

Execute Method

OpenQueryDef Method (Professional Edition Only)

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


lanCreateQueryDefX
CreateQueryDef Method Example

This example creates a QueryDef named "All Pubs" with an SQL statement, and then creates a Dynaset based on the query.

Dim MyDB As Database, MyQuery As QueryDef, MySet As Dynaset
Set MyDB = OpenDatabase("BIBLIO.MDB")	' Open a database.
' Create a QueryDef.
Set MyQuery = MyDB.CreateQueryDef("All Pubs", "SELECT * FROM Publishers;")
Set MySet = MyDB.CreateDynaset("All Pubs")	' Create dynaset from query.
...
MyQuery.Close	' Close QueryDef object.
MyDB.DeleteQueryDef("All Pubs")	' Delete QueryDef.


DeleteQueryDef Method (Professional Edition Only)

See Also	Example

Description

Deletes a specified QueryDef from a database.

Syntax

database.DeleteQueryDef( name )

Remarks

The DeleteQueryDef method uses these parts:

Part	Description

database	Object variable identifying an open database.  If database isn't open, an error occurs.

name	String expression that is the name of an existing QueryDef.  Note that the name of a QueryDef is not the same as the name of an object variable identifying a QueryDef.  If the QueryDef named by name doesn't exist or is open, an error occurs.

QueryDefs are listed in the TableDefs collection of a Database.  To test if a member of theTableDefs collection is really a QueryDef, examine the Attributes property of a member of the TableDefs collection.

Once you use DeleteQueryDef, subsequent references to name are invalid and will produce an error.


lanDeleteQueryDefSee
See Also

Help:

Attributes Property

CreateQueryDef Method

OpenQueryDef Method

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


lanDeleteQueryDefX
DeleteQueryDef Method Example

This example creates and then deletes a QueryDef.  It also uses the QueryDef to create a Snapshot.

Dim MyDB As Database, MyQuery As QueryDef, ListSet As Snapshot
Set MyDB = OpenDatabase("BIBLIO.MDB")	' Open a database.
' Create the QueryDef.
Set MyQuery = MyDB.CreateQueryDef("All Pubs", "SELECT * FROM Publishers;")
Set ListSet = MyQuery.CreateSnapshot()	' Create Snapshot.
MyQuery.Close	' Close QueryDef.
MyDB.DeleteQueryDef("All Pubs")	' Delete QueryDef.


ListFields Method (Professional Edition Only)

See Also	Example

Description

Creates a Snapshot with one record for each field in a specified recordset.

Note   It is easier and more efficient to use the Fields collection of a recordset instead of this method.

Syntax

Set snapshot = recordset.ListFields( )

Remarks

The ListFields method uses these parts:

Part	Description

snapshot	Object variable for the Snapshot you want to create.

recordset	An object variable identifying an existing recordset containing the fields you want to list.

ListFields can return up to 255 records.  The records in the Snapshot are in the same order as the fields in recordset.  The following table shows the Snapshot field contents.

Field	Data type	Description

Name	String	Name of the field.

Type	Long	Number for the field data type.  See table below.

Size	Long	Maximum size of the field.  For Long Text and Long Binary fields (Type 11 and 12), Size is 0; for fields of Type 1 or 2, Size is 1.

Attributes	Long	Numeric value for one or more attributes of the field.  See table below.

SourceTable	String	Name of the underlying table that supplied the field.

SourceField	String	Name of the field in the underlying table.

CollatingOrder	Integer	Comparison code for the current language.  Use this value for the compare part of the StrComp and InStr functions.

The values and symbolic constants (from DATACONS.TXT) for the Type field in the Snapshot are:

Value	Constant	Description

1	DB_BOOLEAN	True/False

2	DB_BYTE	Byte

3	DB_INTEGER	Integer

4	DB_LONG	Long

5	DB_CURRENCY	Currency

6	DB_SINGLE	Single

7	DB_DOUBLE	Double

8	DB_DATE	Date/Time

10	DB_TEXT	Text

11	DB_LONGBINARY	Long Binary

12	DB_MEMO	Memo

The values and symbolic constants (from DATACONS.TXT) for the Attributes field in the Snapshot are:

Value	Constant	Description

1	DB_FIELDFIXED	Field is a fixed-length field.

4	DB_FIELDNOTNULL	Values in field cannot be null.

16	DB_FIELDCOUNTER	Field is a counter field.

32	DB_FIELDUPDATABLE	Field is updatable.

You can't use the Fields collection of a Snapshot created with this method.  To get the value of a specific record, you must explicitly use the name of the field.

In a Snapshot created using ListFields, you can determine field types by referring to the values in the Type field, and the Type constants defined in DATACONS.TXT.  To determine field Attributes, use the values in Field Attributes and the Attributes constants defined in DATACONS.TXT.

If the QueryDef has no parameters, the Snapshot will have no records.

Note   The Fields collection is not available in Snapshots created by the ListTables, ListFields, ListIndexes, and ListParameters methods; therefore, you can't access the field values using an index into the Fields collection.  To access the field values you must explicitly use the name of each field.

You also can't use the Find methods, such as FindFirst, on a Snapshot created with this method.


lanListFieldsSee
See Also

Help:

Fields Collection

StrComp Function

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"

Chapter 3, "Creating Programs to Manipulate Data"


lanListFieldsX
ListFields Method Example

This example creates a Snapshot listing all of the fields in the Publishers table of the BIBLIO.MDB database, then prints the data in the active form.

Dim ListSet As Snapshot, MyDB As Database, MyTable As Table
Set MyDB = OpenDatabase("BIBLIO.MDB")
Set MyTable = MyDB.OpenTable("Publishers")	' Open Table.
Set ListSet = MyTable.ListFields()	' Put field info in ListSet.
MyTable.Close	' Close Table.
Do While Not ListSet.EOF
Print ListSet("Name")
Print ListSet("Type")
Print ListSet("Size")
Print ListSet("Attributes")
Print ListSet("SourceTable")
Print ListSet("SourceField")
ListSet.MoveNext
Loop

ListSet might look like the following table.

Name	Type	Size	Attributes	SourceTable	SourceField

PubID	4	4	33	Publishers	PubID
Name	10	50	32	Publishers	Name
Company Name	10	255	32	Publishers	Company Name
Address	10	50	32	Publishers	Address
City	10	20	32	Publishers	City
State	10	15	32	Publishers	State
Zip Code	10	10	32	Publishers	Zip Code
Telephone	10	24	32	Publishers	Telephone
Fax	10	24	32	Publishers	Fax


ListIndexes Method (Professional Edition Only)

See Also	Example

Description

Creates a Snapshot with one record for each field in each index in a specified table.

Note   It is easier and more efficient to use the Indexes collection of a Table instead of this method.

Syntax

Set snapshot = table.ListIndexes( )

Remarks

The ListIndexes method uses these parts:

Part	Description

snapshot	Object variable for the Snapshot you want to create.

table	Object variable identifying an existing table containing the indexes you want to list.

There is one record in the Snapshot for each field in each index in the table.  The Snapshot records are sorted by IndexName and (for indexes with multiple fields) field order of fields in the index.  The following table shows the Snapshot field contents.

Field	Data type	Description

IndexName	String	Name of the index.

FieldCount	Long	Number of fields in the index.

IndexAttributes	Long	Numeric value for one or more attributes of the index.  See table below.

FieldName	String	Name of the field in the table.

FieldOrder	Long	Order of the field in the index.

FieldType	Long	Numeric value for the field data type.  See table below.

FieldAttributes	Long	Numeric value for one or more attributes of the field.  See table below.

FieldCollatingOrder	Integer	Comparison code for the current language.  Use this value for the compare argument in the StrComp and InStr functions.  See table below.

The values and symbolic constants (from DATACONS.TXT) for the IndexAttributes field in the Snapshot are:

Value	Constant	Description

1	DB_UNIQUE	Unique values are required.

2	DB_PRIMARY	Primary key.

4	DB_NONULLS	Indexed values cannot be Null.

8	DB_IGNORENULL	Null values are ignored by the index.

The values and symbolic constants (from DATACONS.TXT) for the FieldType field in the Snapshot are:

Value	Constant	Description

1	DB_BOOLEAN	True/False

2	DB_BYTE	Byte

3	DB_INTEGER	Integer

4	DB_LONG	Long

5	DB_CURRENCY	Currency

6	DB_SINGLE	Single

7	DB_DOUBLE	Double

8	DB_DATE	Date/Time

10	DB_TEXT	Text

11	DB_LONGBINARY	Long Binary

12	DB_MEMO	Memo

The values and symbolic constants (from DATACONS.TXT) for the FieldAttributes field in the Snapshot are:

Value	Constant	Description

0	DB_INDEXASCEND	Index in this field is in ascending order.

1	DB_INDEXDESCEND	Index in this field is in descending order.

The values and symbolic constants (from CONSTANT.TXT) for the FieldCollatingOrder field in the Snapshot are:

Value	Constant	Description

0	DB_SORTBINARY	Sort by binary values.

256	DB_GENERAL	Sort by EFGPI rules (English, French, German, Portuguese, Italian).

258	DB_SORTSPANISH	Sort by Spanish rules.

259	DB_SORTDUTCH	Sort by Dutch rules.

260	DB_SORTSWEDFIN	Sort by Swedish, Finnish rules.

261	DB_SORTNORWDAN	Sort by Norwegian, Danish rules.

262	DB_SORTICELANDIC	Sort by Icelandic rules.

4096	DB_SORTPDXINTL	Sort by Paradox international rules.

4097	DB_SORTPDXSWE	Sort by Paradox Swedish, Finnish rules.

4098	DB_SORTPDXNOR	Sort by Paradox Norwegian, Danish rules.

-1	DB_SORTUNDEFINED	Field sort rules are undefined or unknown.

Values above 262 for FieldCollatingOrder are not supported by the Instr and StrComp functions.

In a Snapshot created using ListIndexes, you can determine index attributes by referring to the values in the IndexAttributes field and the IndexAttribute constants defined in DATACONS.TXT.  To determine field attributes and sort order, refer to the FieldAttributes and FieldCollatingOrder fields and the symbolic constants defined in DATACONS.TXT.

If the specified table has no indexes, and if the QueryDef has no parameters, the Snapshot will have no records.

Note   The Fields collection is not available in Snapshots created by the ListTables, ListFields, ListIndexes, and ListParameters methods; therefore, you can't access the field values using an index into the Fields collection.  To access the field values you must explicitly use the name of each field.

You can't use the Find methods, such as FindFirst, on a Snapshot created with this method.


lanListIndexesSee
See Also

Help:

Indexes Collection

Instr Function

StrComp Function


lanListIndexesX
ListIndexes Method Example

This example creates a Snapshot listing all of the indexes in the Customers table of the BIBLIO.MDB database, then prints the Snapshot on the active form.

Dim ListSet As Snapshot, MyDB As Database, MyTable As Table
Set MyDB = OpenDatabase("BIBLIO.MDB")
Set MyTable = MyDB.OpenTable("Publishers")	' Open Table.
Set ListSet = MyTable.ListIndexes()	' Copy index info to ListSet.
MyTable.Close	' Close Table.
Do While Not ListSet.EOF
Print ListSet("IndexName")
Print ListSet("FieldCount")
Print ListSet("IndexAttributes")
Print ListSet("FieldName")
Print ListSet("FieldOrder")
Print ListSet("FieldType")
Print ListSet("FieldAttributes")
Print ListSet("FieldCollatingOrder")
ListSet.MoveNext
Loop

ListSet might look like the following table.

Index	Field	Index	Field	Field	Field	Collating
Name	Count	Attributes	FieldName	Order	Type	Attributes	Order

PubID Name	2	0	PubID	0	4	0
PubID Name	2	0	Name	1	10	0	256
PrimaryKey	1	7	PubID	0	4	0


OpenQueryDef Method (Professional Edition Only)

See Also	Example

Description

Opens a specified QueryDef for editing.

Syntax

Set querydef = database.OpenQueryDef( name )

Remarks

The OpenQueryDef method uses these parts:

Part	Description

querydef	Object variable of type QueryDef.

database	Object variable identifying an open Database.

name	String expression for the name of a QueryDef that exists in database.

If the QueryDef contains parameters, you must set the parameters before using the QueryDef.  You set the parameters using the following syntax:

querydef ! parameter = parametervalue

You can use a QueryDef as you would a Table in the CreateDynaset and CreateSnapshot methods.


lanOpenQueryDefSee
See Also

Help:

Close Method

CreateDynaset Method

CreateQueryDef Method

CreateSnapshot Method

DeleteQueryDef Method

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


lanOpenQueryDefX
OpenQueryDef Method Example

This example provides a value for the State Wanted parameter of an existing query named Get State and creates a Snapshot of the records for all publishers in New York.

Dim MyDB As Database, MyQuery As QueryDef, MySet As Snapshot
Set MyDB = OpenDatabase("BIBLIO.MDB")
Set MyQuery = MyDB.OpenQueryDef("Get State")	' Open QueryDef.
MyQuery![State Wanted] = "NY"	' Set parameter.
Set MySet = MyQuery.CreateSnapshot()	' Create Snapshot.
...


Seek Method (Professional Edition Only)

See Also	Example

Description

Locates a record in an indexed table that meets the specified criteria for the current index and makes it the current record.

Syntax

table.Seek comparison, key1, key2...

Remarks

The Seek method uses these parts:

Part	Description

table	Object variable identifying an open Table.

comparison	One of the following string expressions:  <,  <=,  =,  >=,  >,  or  <>.

key1, key2...	One value for each field in the table's current index.

Seek searches through the specified Table using the current index and locates the first record satisfying the criteria specified by comparison and the key values (key1, key2...), and makes it the current record.

You must set the current index with the Index property before you use Seek.  If the index identifies a nonunique key field, Seek locates the first record satisfying the criteria.

When comparison is  =,  >=,  >,  or  <>, Seek starts at the beginning of the index and searches forward.  When comparison is  <=  or  <, Seek starts at the end of the index and searches backward.

The value of each key value must be of the same field data type as the corresponding field in the current index. For example, if the current index refers to a numeric key field (such as Employee ID), key1 must be a numeric expression. Similarly, if the current index refers to a Text field (such as Last Name), key1 must be a string expression.

There doesn't have to be a current record when you use Seek.

You can use the Indexes collection to get names of existing indexes.

If table doesn't refer to an open table, or if there is no current index, an error occurs.

Use the Move methods, such as MoveFirst, to move between all records in a recordset. In a Dynaset or Snapshot, use the Find methods, such as FindFirst, to move between records that meet specific conditions.

Note   Always inspect the value of the NoMatch property of the recordset to determine whether the Seek method has succeeded.  If it fails, NoMatch is True and the current record is unchanged.


lanSeekMethodSee
See Also

Help:

BOF Property

EOF Property

FindFirst, FindLast, FindNext, FindPrevious Methods

Index Property (Data Access)

Indexes Collection

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

NoMatch Property

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


lanSeekMethodX
Seek Method Example

This example uses Seek to locate the first record in the Publishers table where the PubID field is 3, using the existing primary key index.

Dim MyDB As Database, MyTable As Table
Set MyDB = OpenDatabase("BIBLIO.MDB")	' Open a database.
Set MyTable = MyDB.OpenTable("Publishers")	' Open a table.
MyTable.Index = "PrimaryKey"	' Define current index.
MyTable.Seek "=", 3	' Seek record.
If MyTable.NoMatch Then...


BOF Property

See Also	Example

Applies To

Table object, Dynaset object, Snapshot object.

Description

After using the MovePrevious method, indicates whether the current record position is before the first record in a recordset.  Not available at design time; read-only at run time.

Syntax

recordset.BOF

Setting

The BOF property settings are:

Setting	Description

True	The current record position is before the first record in a recordset.

False	The current record position is on or after the first record in a recordset.

Remarks

Check the BOF property before using the MovePrevious method to avoid moving beyond the limits of a recordset as you move from record to record.

When you create or open a recordset containing at least one record, the first record is the current record and BOF is False.  If the current record is the first record, and you use MovePrevious, BOF will then be True and there will be no current record.  Using MovePrevious while BOF is True produces an error and BOF remains True.  There is no current record when BOF is True.  If the recordset contains no records, both BOF and EOF are True.

Data Type

Integer (Boolean)


proBOFSee
See Also

Help:

EOF Function

EOF Property

MoveFirst, MovePrevious, MoveNext, MoveLast Methods

NoMatch Property

Recordset Property

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


proBOFEx
BOF, EOF Properties Example

This example uses the BOF and EOF properties to detect the limits of the Publishers table.  It moves through the records first from the beginning of the file to the end, and then from the end to the beginning.  The MoveLast method is required because there is no current record immediately following the first loop.

Data1.DatabaseName = "BIBLIO.MDB"
Data1.RecordSource = "Publishers"	' Open table.
...
Do Until Data1.Recordset.EOF	' Until end of file.
...
Data1.Recordset.MoveNext	' Move to next record.
Loop
Data1.Recordset.MoveLast	' Move to last record.
Do Until Data1.Recordset.BOF	' Until beginning of file.
...
Data1.Recordset.MovePrevious	' Move to previous record.
Loop


Bookmark Property

See Also	Example

Applies To

Table object, Dynaset object, Snapshot object.

Description

Determines which record in a recordset is the current record.  Not available at design time; read/write at run time.

Syntax

recordset.Bookmark [ = variable ]

Remarks

When a recordset is created or opened, each record already has a unique bookmark.  You can save the bookmark for the current record by assigning the value of the Bookmark property to a variable.  To quickly return to that record at any time after moving to a different record, set the recordset's Bookmark property to the value of that variable.

To make sure the recordset supports bookmarks, inspect the value of the Bookmarkable property before you use the Bookmark property.  If Bookmarkable is False, the recordset doesn't support bookmarks.

Between a Dynaset and a duplicate Dynaset created with the Clone method, the bookmark values are identical and can be used interchangeably.  You cannot use bookmarks from different Dynasets, even if they are created from the same table or with the same SQL statement.

A bookmark may become invalid if the underlying record is deleted by another user.

The value of the Bookmark property is not the same as a record number.

Data Type

The value is a string of binary data, but can be stored in a variable of String or Variant data type.  The length of the string cannot be predicted, so if you use a string variable, do not use a fixed-length string.


proBookmarkSee
See Also

Help:

Bookmarkable Property

Clone Method

LastModified Property

Recordset Property

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


proBookmarkX
Bookmark and Bookmarkable Properties Example

This example gets the bookmark for a record and then uses the Bookmark property to return to that record.

Dim MyMark As Variant
Data1.DatabaseName = "BIBLIO.MDB"
Data1.RecordSource = "Titles"
...
Data1.Recordset.FindFirst "State = 'NY'"	' Locate a NY publisher.
If Data1.Recordset.Bookmarkable And Not Data1.Recordset.NoMatch Then
MyMark = Data1.Recordset.Bookmark	' Get current Bookmark.
' Move to different record.
Data1.Recordset.FindFirst "City = 'Los Angeles'"
...
Data1.Recordset.Bookmark = MyMark	' Return to NY record.
End If


Bookmarkable Property

See Also	Example

Applies To

Table object, Dynaset object, Snapshot object.

Description

Indicates whether a recordset supports bookmarks.  Not available at design time; read-only at run time.

Syntax

recordset.Bookmarkable

Setting

The Bookmarkable property settings are:

Setting	Description

True	The recordset supports bookmarks.

False	The recordset doesn't support bookmarks.

Remarks

Inspect the value of the Bookmarkable property before you use the Bookmark property to make sure the recordset supports bookmarks.

For a recordset based entirely on Microsoft Access tables, the value of the Bookmarkable property is always True and bookmarks can be used.  Other databases may not support bookmarks.  For example, you cannot use bookmarks in a recordset based on an attached Paradox table that has no primary index.


proBookmarkableSee
See Also

Help:

Bookmark Property

Recordset Property

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


proBookmarkableX
Bookmarkable Property Example

See the example for the Bookmark property.


DateCreated, LastUpdated Properties

See Also

Applies To

Table object, TableDef object.

Description

Contains the date and time a table was created, or when its definition was last changed.  Not available at design time; read-only at run time.

Syntax

{tabledefobject | tableobject}.DateCreated

{tabledefobject | tableobject}.LastUpdated

Remarks

When a table is created in the database, the values of DateCreated and LastUpdated are the same.  When you change the structure of a table through a TableDef object, the LastUpdated property is set to the current date and time.  You can change the structure of tables only with the Professional Edition.

The date and time are taken from the computer which created the Table.  If various users maintain different dates and times on their workstations, these property settings may be inaccurate.

Data Type

Variant of VarType 7 (Date)


proDateCreatedSee
See Also

Help:

TableDef Object

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


EOF Property

See Also	Example

Applies To

Table object, Dynaset object, Snapshot object.

Description

After using the MoveNext method, indicates whether the current record position is after the last record in a recordset.  Not available at design time; read-only at run time.

Syntax

recordset.EOF

Setting

The EOF property settings are:

Setting	Description

True	The current record position is after the last record in a recordset.

False	The current record position is on or before the last record in a recordset.

Remarks

Check the EOF property before using the MoveNext method to avoid moving beyond the limits of a recordset as you move from record to record.  If the current record is the last record, then EOF will be True after you use MoveNext.  If you use MoveNext while EOF is True, an error occurs and EOF remains True.  There is no current record when EOF is True.

When you create or open a recordset containing at least one record, the first record is the current record and EOF is False.  If the recordset contains no records, both BOF and EOF are True.

Data Type

Integer (Boolean)


proEOFSee
See Also

Help:

BOF Property

EOF Function

MoveFirst, MovePrevious, MoveNext, MoveLast Methods

NoMatch Property

Recordset Property

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


Filter Property (Professional Edition Only)

See Also	Example

Applies To

Dynaset object, Snapshot object.

Description

Sets a filter for creating a Dynaset or Snapshot.  The Filter property setting is the WHERE clause in an SQL statement (without the word "WHERE").  Not available at design time; read/write at run time.

Syntax

recordset.Filter [ = criteria ]

Remarks

You can use the Filter property to select records or to refine the selection of records in a Dynaset or Snapshot.  The Filter property affects only recordsets subsequently created from recordset with CreateDynaset or CreateSnapshot.

You can create a Dynaset or Snapshot, set its Filter property, and then create a new Dynaset or Snapshot.  If you create a Dynaset or Snapshot using an SQL statement, there is no need to set this property.  The Filter property of the new recordset is empty.

Data Type

String


proFilterSee
See Also

Help:

CreateDynaset Method(Professional Edition Only)

CreateSnapshot Method(Professional Edition Only)

Index Property (Data Access)

Recordset Property

Sort Property(Professional Edition Only)

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


proFilterX
Filter Property Example

This example creates a Snapshot, sets the Filter property then recreates it.

Dim Db As Database, Sn As Snapshot
Set Db = OpenDatabase("BIBLIO.MDB")
Set Sn = Db.CreateSnapshot("Publishers")
Sn.Filter = "State = 'NY'"
Set Sn = Sn.CreateSnapshot()


LockEdits Property

See Also

Applies To

Table object, Dynaset object.

Description

Determines which locking condition is in effect during editing.  Not available at design time; read/write at run time.

Syntax

recordset.LockEdits [ = {True | False}]

Setting

The LockEdits property settings are:

Setting	Description

True	(Default) Pessimistic locking is in effect for all editing.  The page containing the record you are editing is locked while in edit mode (EditMode property setting = 1).

False	Optimistic locking is in effect for all editing.  The page containing the record is locked only while you actually update the record with the Update method.

Remarks

If a page is locked (LockEdits is True), then no other user can edit records on the same page.  If you set LockEdits to True and another user already has the page locked, an error occurs when you use the Edit method.

If you set LockEdits to False and later use Update while the page is locked by another user, an error occurs.


proLockEditsSee
See Also

Help:

Edit Method

EditMode Property

Update Method

UpdateControls Method

UpdateRecord Method

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


NoMatch Property

See Also	Example

Applies To

Table object, Dynaset object, Snapshot object.

Description

Indicates whether the FindFirst, FindPrevious, FindNext, FindLast, or Seek method was successful in finding a record.  Not available at design time; read-only at run time.

Syntax

recordset.NoMatch

Setting

The NoMatch property settings are:

Setting	Description

True	A Find method or the Seek method failed (the desired record wasn't found).

False	A Find method or the Seek method was successful (the desired record was found).

Remarks

When you first open or create a recordset or data control, NoMatch is False.

With the Recordset property of a data control, use one of the Find methods to make a specific record current.  In the Professional Edition only, you can also use any of the Find methods with a Dynaset or Snapshot object, or the Seek method with a Table object.

After using a Find method or the Seek method, inspect the NoMatch property to see whether the record was found.  If the operation fails (no matching record is found), the NoMatch property setting is True and the current record is undetermined.  If a matching record is found, NoMatch is False.

Data Type

Integer (Boolean)


proNoMatchSee
See Also

Help:

BOF Property

EOF Property

FindFirst, FindLast, FindNext, FindPrevious Methods

Seek Method

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


proNoMatchX
NoMatch Property Example

This example uses the NoMatch property to cycle through all records matching specific criteria.

Dim Criteria As String
Data1.DatabaseName = "BIBLIO.MDB"
Data1.RecordSource = "Titles"
Criteria = "Title = 'Database Design'"	' Define search criteria.
...
Data1.Recordset.FindFirst Criteria	' Locate first occurrence.
' Loop until no matching records.
Do Until Data1.Recordset.NoMatch
...
MySet.FindNext Criteria	' Locate next record.
Loop	' End of loop.


RecordCount Property

See Also

Applies To

Table object, Dynaset object, Snapshot object.

Description

Indicates the approximate number of records in a recordset.  Not available at design time; read-only at run time.

Syntax

recordset.RecordCount

Remarks

The recordset is the Recordset property of a data control.  In the Professional Edition, it can also be an object variable identifying a Table, Dynaset or Snapshot.

With the Recordset property of a data control, the RecordCount property indicates approximately how many records are in the Recordset property at the time the control was loaded.  As you add and delete records with the data control in a single-user environment, the RecordCount property changes.  However, in a multiuser environment, the RecordCount property may need to be updated more often.  To update the current value of RecordCount, use MoveLast and then inspect the RecordCount value.

The total number of records in a Snapshot doesn't change even if the number of records in the underlying Tables changes.

A recordset with no records has a RecordCount value of 0.  When you first open or create a recordset containing at least one record, RecordCount is 1 until you use one of the Move methods.

Tip   Do not use the RecordCount property to cycle through records in a recordset.  Use Do While Not EOF...Loop to cycle toward the last record, or Do While Not BOF...Loop to cycle toward the first record.

Data Type

Long


proRecordCountSee
See Also

Help:

Do...Loop Statement

FindFirst, FindLast, FindNext, FindPrevious Methods

Move First, MoveLast, MoveNext. MovePrevious Methods

Seek Method

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


Sort Property (Professional Edition Only)

See Also	Example

Applies To

Dynaset object, Snapshot object.

Description

Determines the order of records in a recordset.  It is the ORDER BY clause in an SQL statement (without the words "ORDER BY").  Not available at design time; read/write at run time.

Syntax

{dynasetobject | snapshotobject}.Sort [ = orderbystring ]

Remarks

You can use the Sort property to sort records in a Dynaset or Snapshot.  The Sort property affects only recordsets subsequently created from recordset with CreateDynaset or CreateSnapshot.

You can create a Dynaset or Snapshot, set its Sort property, and then create a new Dynaset or Snapshot.  If you create a Dynaset or Snapshot using an SQL statement, there is no need to set this property.  The Sort property of the new recordset is empty.  The Sort property overrides any sorting specified in the underlying QueryDef.

The default sort order is ascending.  The following examples show how you can set the sort order to ascending and descending.  The first two create identical results.

Data1.Recordset.Sort = "[Ship Country]"	' Ascending order.
Data1.Recordset.Sort = "[Ship Country] Asc"	' Ascending order.
Data1.Recordset.Sort = "[Ship Country] Desc"	' Descending order.

The Sort property doesn't apply to Tables. To sort on a Table index, use the Index property of a TableDef.

The Sort property of a new Dynaset or Snapshot is blank because the records were sorted during the creation process.


proSortSee
See Also

Help:

CreateDynaset Method

CreateSnapshot Method

Filter Property

Index Property (Control Arrays)

Recordset Property

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


proSortX
Sort Property Example

This example uses the Sort property to create a Dynaset with a specific sort order.

Dim Db As Database, Dn As Dynaset, I As Integer
Set Db = OpenDatabase("BIBLIO.MDB")	' Open database.
Set Dn = Db.CreateDynaset("Publishers")	' Create Dynaset.
Cls	' Clear Form.
For I = 0 to 4	' Print 5 records.
Print Dn.Fields("Name")
Dn.MoveNext
Next I
Print	' Print a blank line.
Dn.Sort = "Name Desc"	' Set Sort property.
Set Dn = Dn.CreateDynaset()	' Recreate Dynaset.
For I = 0 to 4	' Print 5 records.
Print Dn.Fields("Name")
Dn.MoveNext
Next I


SQL Property (Professional Edition Only)

See Also	Example

Applies To

QueryDef object.

Description

Defines a QueryDef.  Not available at design time; read/write at run time.

Syntax

querydef.SQL [ = sqlstatement ]

Remarks

The SQL property contains the SQL statement that determines how records are selected, grouped, and ordered when you use the query.  You can use the query to select records for a Dynaset or Snapshot or to update a recordset.

If the SQL statement includes parameters for the query, you must set the parameters before you use the query.  Until you reset the parameters, the same parameter values are applied each time you use the query.  You set the parameters using the following syntax:

querydef ! parameter = parametervalue

Data Type

String


proSQLSee
See Also

Help:

CreateDynaset Method

CreateSnapshot Method

Filter Property

OpenQueryDef Method

How to Query a Database

Sort Property

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


proSQLX
SQL Property Example

The example creates a blank QueryDef, then sets the SQL property and creates a Snapshot based on the query.  The query selects all Titles published after 1988, and prints the Title and Year Published in the Debug window.

Dim MyDB As Database, MyQuery As QueryDef, MySnapshot As Snapshot
Set MyDB = OpenDatabase("BIBLIO.MDB")
' Save query in the database.
Set MyQuery = MyDB.CreateQueryDef("New TitlesA")
MyQuery.SQL = "SELECT * FROM Titles WHERE [Year Published] > 1988;"
Set MySnapshot = MyQuery.CreateSnapshot()	' Create Snapshot.
Do While Not EOF
Debug.Print MySnapshot.Fields("Title"),
Debug.Print MySnapShot.Fields("Year Published")
MySnapShot.MoveNext
Loop


Transactions Property

See Also

Applies To

Table object, Dynaset object.

Description

Indicates whether a Table or Dynaset supports the recording of a series of changes that can later be rolled back (canceled) or committed (saved).  Not available at design time; read-only at run time.

Syntax

recordset.Transactions

Setting

The Transactions property settings are:

Setting	Description

True	The Table or Dynaset supports transactions.

False	The Table or Dynaset doesn't support transactions.

Remarks

The recordset is the Recordset property of a data control.  In the Professional Edition, it can also be an object variable identifying an open Table or Dynaset.

If the recordset is based entirely on Microsoft Access tables, the value of the Transactions property is True and you can use transactions.  Tables created by other database products may not support transactions.  For example, you cannot use transactions on a Paradox table.

Before you use the BeginTrans statement, inspect the value of the Transactions property to make sure the recordset supports transactions.  If Transactions is False, using BeginTrans or Rollback has no effect on this object.  It may, however, affect other objects since the scope of transactions covers all database items.


proTransactionsSee
See Also

Help:

BeginTrans, CommitTrans, Rollback Statements

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


Updatable Property

See Also

Applies To

Table object, Dynaset object.

Description

Indicates whether records can be updated.  Not available at design time; read-only at run time.

Syntax

recordset.Updatable

Setting

The Updatable property settings are:

Setting	Description

True	The records can be changed.

False	The records cannot be changed.

Remarks

The recordset is the Recordset property of a data control.  In the Professional Edition, it can also be an object variable identifying an open Table or Dynaset.

A Dynaset may contain fields that can't be updated.  These fields might be fixed or contain auto-incrementing data, or the Dynaset might be the result of a query combining updatable and non-updatable Tables.

If a Dynaset contains any non-updatable fields, the value of the Updatable property on the Dynaset is False.  You can, however, edit the individual updatable fields.  You can use the Fields collection of a recordset to inspect the Attributes property of each Field and identify updatable fields before you edit a record.  As long as you edit only updatable fields, no error occurs when you use the Update method, even if the Updatable property of the recordset is False.

If you change the value of a non-updatable field and then use the Update method, an error occurs.


proUpdatableSee
See Also

Help:

AddNew Method

Edit Method

Fields Collection

Update Method

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


DataField Property

See Also

Applies To

Check box, image, label, picture box, text box, and other bound controls as they become available.

Description

Binds a control to a Field.  Read/write at both design time and run time.

Syntax

[form.] control.DataField [ = fieldname ]

Remarks

Bound controls provide access to specific data in your database.  Each bound control typically displays the value of a different field in the current record.  The DataSource property of a bound control specifies a valid data control name, and the DataField property specifies a valid field name in the data control's Recordset property.  Together, these properties specify which data appears in the control.

Note   Make sure each bound control has a valid setting for its DataField property.  If you change the setting of a data control's RecordSource property, when you use Refresh, the Recordset then identifies the new object.  This may invalidate the DataField settings of bound controls and produce an error.

Data Type

String


proControlSourceSee
See Also

Help:

Binding a Control to a Data Control

DataSource Property

Recordset Property

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


RecordSource Property

See Also

Applies To

Data control.

Description

Specifies the underlying table, SQL statement, or QueryDef for a data control.  Read/write at both design time and run time.

Syntax

[form.]datactrl.RecordSource [ = {tablename | sqlstatement | queryname}]

Remarks

The RecordSource property specifies the source of the records accessible through bound controls on your form.  After changing the value of this property at run time, you must use the Refresh method to enable the change.

Note   Make sure each bound control has a valid setting for its DataField property.  If you change the setting of a data control's RecordSource property, when you use Refresh, the Recordset then identifies the new object.  This may invalidate the DataField settings of bound controls.

Data Type

String


proRecordSourceSee
See Also

Help:

How to Query a Database

DatabaseName Property

DataField Property

DataSource Property

How to Query a Database

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


Recordset Property

See Also	Example

Applies To

Data control.

Description

A Dynaset defined by a data control's Connect, DatabaseName, and RecordSource properties.  Not available at design time.

Syntax

[formname.]datactrl.Recordset.propertyname [ = propertyvalue ]

[formname.]datactrl.Recordset.methodname [ argumentlist ]

Remarks

The Recordset property is a reference to the underlying database object of a data control.  It has all the same properties and methods of its underlying Dynaset.  Setting its properties is the same as setting the properties of the underlying Dynaset.  Likewise, you can use any methods of a Dynaset as well.

The following example shows how you can combine the RecordCount property of a Dynaset with the Recordset property to display the number of records in a data control's recordset:

Data1.Recordset.MoveLast
MsgBox "Records: " & Data1.Recordset.RecordCount


vbproRecordsetSee
See Also

Help:

FindFirst, FindLast, FindNext, FindPrevious Methods

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

RecordCount Property

RecordSource Property

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


vbproRecordsetEx
Recordset Property Example

The example cycles through the records in the Recordset and automatically displays the data from the current record in controls bound to the data control.

Data1.Recordset.MoveFirst
Do Until Data1.Recordset.EOF
...
Data1.Recordset.MoveNext
Loop


Common Dialog Control

See Also	Print Dialog Properties	Font Dialog Properties
Color Dialog Properties	File Dialog Properties

Description

The common dialog control provides a standard set of dialog boxes for operations such as opening, saving, and printing files or selecting colors and fonts.

Remarks

The common dialog control provides an interface between Visual Basic and the routines in the Windows dynamic-link library COMMDLG.DLL.  To create a common dialog using this control, COMMDLG.DLL must be in your WINDOWS directory.

Before you can use a common dialog box in your application, you must add CMDIALOG.VBX to your project using the Add File command on the File menu.  To automatically include CMDIALOG.VBX in new projects, put it in an AUTOLOAD.MAK file.

You create common dialog boxes for your application by adding the common dialog control to a form and setting its properties.  The type of dialog box displayed is determined by the Action property.  At run time, a dialog box is displayed when the Action property is set to a valid value; at design time, the common dialog control appears as an icon on a form.  This icon cannot be sized.

Note   You cannot specify where a common dialog box is displayed.

Distribution Note   When you create and distribute applications that use the common dialog control, you should install the files CMDIALOG.VBX and COMMDLG.DLL in the customer's Microsoft Windows \SYSTEM subdirectory.  The Visual Basic Setup Kit provides tools to help you write setup programs that install your applications.


CmnDlgSee
See Also

Help:

Action Property

Call Statement

Error Messages

Declare Statement

Setup Kit Contents


CmnDlgProps1
Print Dialog Properties

Action	hDC	MaxFileSize

CancelError	HelpCommand	Max

Copies	HelpContext	Min

DialogTitle	HelpFile	PrinterDefault

Flags	HelpKey	ToPage

FromPage


CmnDlgProps4
File Dialog Properties

Action	FileTitle	HelpContext

CancelError	FilterIndex	HelpFile

DefaultExt	Filter	HelpKey

DialogTitle	Flags	InitDir

FileName	HelpCommand	MaxFileSize


CmnDlgProps3
Color Dialog Properties

Action	DialogTitle	HelpContext

CancelError	Flags	HelpFile

Color	HelpCommand	HelpKey


CmnDlgProps2
Font Dialog Properties

Action	FontName	HelpContext

CancelError	FontSize	HelpFile

DialogTitle	FontStrikethru	HelpKey

Flags	FontUnderline	Max

FontBold	HelpCommand	Min

FontItalic


Action Property (Common Dialog)

Applies To

Common dialog.

Description

Specifies the type of dialog to be displayed.  Not available at design time.

Usage

[form.]CMDialog.Action[ = setting ]

Remarks

The Action property settings are:

Setting 	Dialog displayed

0	No action

1	Open

2	Save As

3	Color

4	Font

5	Printer

6	Invokes WINHELP.EXE

A dialog box is displayed at run time when the Action property is set to a valid value.

Data Type

Integer (Enumerated)


CancelError Property

Applies To

Common dialog.

Description

Determines whether an error is generated when the user selects the Cancel button.

Usage

[form.]CMDialog.CancelError[ = {True | False}]

Remarks

The CancelError property settings are:

Setting	Description

True	An error is generated.

False	(Default) No error is generated.

When this property is set to True, error number 32755 (CDERR_CANCEL) occurs whenever the user selects the Cancel button.

Data Type

Integer (Boolean)


HelpCommand Property

Example

Applies To

Common dialog.

Description

Specifies the type of Help requested.

Usage

[form.]CMDialog.HelpCommand[ = setting ]

Remarks

The HelpCommand property settings are:

Setting	Description

HELP_CONTEXT	Displays Help for a particular context.  When using this setting, you must also specify a context using the HelpContext property.

HELP_HELPONHELP	Displays Help for using the Help application itself.

HELP_INDEX	Displays the index of the specified Help file.  An application should use this value only for a Help file with a single index.

HELP_KEY	Displays Help for a particular keyword.  When using this setting, you must also specify a keyword using the HelpKey property.

HELP_QUIT	Notifies the Help application that the specified Help file is no longer in use.

HELP_SETINDEX	Sets the context specified by the HelpContext property as the current index for the Help file specified by the HelpFile property.  This index remains current until the user accesses a different Help file.  Use this value only for Help files with more than one index.

The values for the HelpCommand property constants are defined in the Visual Basic file CONSTANT.TXT.

Data Type

Integer


Help Example, Common Dialog Control
HelpCommand, HelpFile, HelpKey Properties Example, Common Dialog Control

The example executes WINHELP.EXE and displays the Help topic for the MouseDown event from the Visual Basic Help file (VB.HLP) when the user clicks a command button.

Sub Command1_Click ()
Const HELP_KEY = &H101
CMDialog1.HelpFile = "VB.HLP"	' Specify the Help file to open.
CMDialog1.HelpCommand = HELP_KEY	' When WINHELP.EXE is executed, Help for a specified keyword will be displayed.
CMDialog1.HelpKey = "MouseDown"	' Specify the keyword.
CMDialog1.Action = 6	' Execute WINHELP.EXE.
End Sub


HelpContext Property

Applies To

Common dialog.

Description

Specifies the context ID of the requested Help topic.

Usage

[form.]CMDialog.HelpContext[ = contextid ]

Remarks

Use this property with the HelpCommand property (set HelpCommand = HELP_CONTEXT) to specify the Help topic to be displayed.

Data Type

Integer


HelpKey Property

Example

Applies To

Common dialog.

Description

Specifies the keyword that identifies the requested Help topic.

Usage

[form.]CMDialog.HelpKey[ = keyword ]

Remarks

Use this property with the HelpCommand property (set HelpCommand = HELP_KEY) to specify the Help topic to be displayed.

Data Type

String


DefaultExt Property

Applies To

Common dialog(file dialog).

Description

Sets the default file-name extension for the dialog box.

Usage

[form.]CMDialog.DefaultExt[ = extension ]

Remarks

Use this property to specify a default file-name extension such as .TXT or .DOC.

When a file with no extension is saved, the extension specified by this property is automatically appended to the file name.

Data Type

String


DialogTitle Property

Applies To

Common dialog.

Description

Sets the string displayed in the title bar of the dialog box.

Usage

[form.]CMDialog.DialogTitle[ = title ]

Remarks

Use this property to display the name of the dialog box in the title bar.

The default title for an Open dialog box is Open; the default title for a Save As dialog box is Save As.

Data Type

String


FileTitle Property

Applies To

Common dialog (file dialog).

Description

Returns the name (without the path) of the file to open or save.  Not available at design time and read-only at run time.

Usage

[form.]CMDialog.FileTitle

Remarks

When the user selects a file and clicks the dialog box's OK button, the FileTitle property takes a value that can then be used to open or save the selected file.

Note	If the OFN_NOVALIDATE flag is set, the FileTitle property will not return a value.

Data Type

String


Filter Property (Common Dialog)

Applies To

Common dialog (file dialog).

Description

Specifies the filters that are displayed in the dialog box's Type list box.

Usage

[form.]CMDialog.Filter[ = description1 |filter1 |description2 |filter2 ...]

Remarks

A filter specifies the type of files that are displayed in the dialog box's file list box.  For example, selecting the filter *.TXT displays all text files.

Use this property to provide the user with a list of filters that can be selected when the dialog box is displayed.

Use the pipe ( | ) symbol (ASCII 124) to separate the description and filter arguments.  Don't include spaces before or after the pipe symbol, because these spaces will then appear with the description and filter values.

The following code shows an example of a filter that allows the user to choose text files or picture files that include bitmaps and icons:

Text (*.txt)|*.txt|Pictures(*.bmp;*.ico)|*.bmp;*.ico

When you specify more than one filter for a dialog box, use the FilterIndex property to determine which filter is displayed as the default.

Data Type

String


FilterIndex Property

Applies To

Common dialog (file dialog).

Description

Specifies a default filter.

Usage

[form.]CMDialog.FilterIndex[ = index ]

Remarks

This property specifies the default filter when you use the Filter property to specify filters for an Open or Save As dialog box.

The index for the first defined filter is 1.

Data Type

Integer


Flags Property (File Dialogs)

Example

Applies To

Common dialog.

Description

Sets the options for the Open and Save As dialog boxes.

Usage

[form.]CMDialog.Flags[ = flag ]

Remarks

The following constants are available for the Open and Save As dialog boxes:

Constant	Value	Description
OFN_ALLOWMULTISELECT	&H200&	Specifies that the File Name list box allows multiple selections. The user can select more than one file at run time by pressing the Shift key and using the Up and Down Arrow keys to select the desired files. When this is done, the FileName property returns a string containing the names of all selected files. The names in the string are delimited by spaces.
OFN_CREATEPROMPT	&H2000&	Specifies that the dialog box should ask if the user wants to create a file that does not currently exist. This flag automatically sets the OFN_PATHMUSTEXIST and OFN_FILEMUSTEXIST flags.
OFN_EXTENSIONDIFFERENT	&H400&	Indicates that the extension of the returned file name is different from the extension specified by the DefaultExt property. This flag is not set if the DefaultExt property is Null, if the extensions match, or if the file has no extension. This flag value can be checked upon returning from the dialog box.
OFN_FILEMUSTEXIST	&H1000&	Specifies that the user can enter only names of existing files in the File Name text box. If this flag is set and the user enters an invalid file name, a warning is displayed. This flag automatically sets the OFN_PATHMUSTEXIST flag.
OFN_HIDEREADONLY	&H4&	Hides the Read Only check box.
OFN_NOCHANGEDIR	&H8&	Forces the dialog box to set the current directory to what it was when the dialog box was invoked.
OFN_NOREADONLYRETURN	&H8000&	Specifies that the returned file will not have the Read Only attribute set and will not be in a write-protected directory.
OFN_NOVALIDATE	&H100&	Specifies that the common dialog box allows invalid characters in the returned file name.
OFN_OVERWRITEPROMPT	&H2&	Causes the Save As dialog box to generate a message box if the selected file already exists. The user must confirm whether to overwrite the file.
OFN_PATHMUSTEXIST	&H800&	Specifies that the user can enter only valid path names. If this flag is set and the user enters an invalid path name, a warning message is displayed.
OFN_READONLY	&H1&	Causes the Read Only check box to be initially checked when the dialog box is created. This flag also indicates the state of the Read Only check box when the dialog box is closed.
OFN_SHAREAWARE	&H4000&	Specifies that sharing violation errors will be ignored.
OFN_SHOWHELP	&H10&	Causes the dialog box to display the Help button.
These flags are defined in the Visual Basic CONSTANT.TXT file.

You can also define selected flags.  Use the Const keyword in the Declarations section of the startup form to define the flags you want to use.  For example:

Const OFN_READONLY  = &H00000001&
Const CF_EFFECTS    = &H00000100&
CMDialog1.Flags = &H10& Or &H200&

Adding the desired constant values produces the same results.  The following is equivalent to the preceding example:

CMDialog1.Flags = &H210&

Data Type

Long


exFlags_CDlgFil
Flags Property (File Dialogs) Example, Common Dialog Control

The example displays an Open dialog box when the user clicks the form.  The dialog box contains a Help button.  The dialog box's Read Only check box is not displayed.  When the user selects the Help button, WINHELP.EXE is executed and displays the topic for the MouseDown event.

Sub Form_Click ()
Const HELP_KEY = &h0101
Const OFN_SHOWHELP = &h00000010&
Const OFN_HIDEREADONLY = &h00000004&

CMDialog1.HelpFile = "VB.HLP"	' Set Help properties.
CMDialog1.HelpCommand = HELP_KEY
CMDialog1.HelpKey = "MouseDown"

' Set flag to display the dialog with a Help button.
CMDialog1.Flags = OFN_SHOWHELP Or OFN_HIDEREADONLY
CMDialog1.Action = 1	' Display Open dialog.
End Sub


InitDir Property

Applies To

Common dialog (file dialog).

Description

Specifies the initial file directory.

Usage

[form.]CMDialog.InitDir[ = dirpath ]

Remarks

If this property is not specified, the current directory is used.

Data Type

String


MaxFileSize Property

Applies To

Common dialog (file dialog).

Description

Specifies the maximum length of the file name specified by the FileName property.

Usage

[form.]CMDialog.MaxFileSize[ = bytes ]

Remarks

The range for this property is 1K [image] 2K.

The default is 256.

Data Type

Integer


Color Property

Applies To

Common dialog (color dialog).

Description

Sets or returns the selected color.

Usage

[form.]CMDialog.Color[ = color ]

Remarks

In order for this property to return a color in a Color dialog box, the CC_RGBINIT flag must be set.  In the Font dialog box, the CF_EFFECTS flag must be set.

Data Type

Long


Flags Property (Color Dialog)

Example

Applies To

Common dialog.

Description

Sets the options for the Color dialog box.

Usage

[form.]CMDialog.Flags[ = flag ]

Remarks

The following constants are available for the Color dialog box:

Constant	Value	Description
CC_FULLOPEN	&H2&	Causes the entire dialog box, including the portion that allows the user to create custom colors, to appear when the dialog box is created. Without this flag, the user must choose the Define Custom Colors command button to display this portion of the dialog box.
CC_PREVENTFULLOPEN	&H4&	Disables the Define Custom Colors command button and prevents the user from defining custom colors.
CC_RGBINIT	&H1&	Sets the initial color value for the dialog box.
CC_SHOWHELP	&H8&	Causes the dialog box to display a Help button.
These flags are defined in the file CONSTANT.TXT.

You can also define selected flags.  Use the Const keyword in the declarations section of the startup form to define the flags you want to use.

You can set more than one flag for a dialog box using the Or operator.  For example:

CMDialog1.Flags = &H10& Or &H200&

Adding the desired constant values produces the same results.  The following is equivalent to the preceding example:

CMDialog1.Flags = &H210&

Data Type

Long


exFlags_CDlgClr
Flags Property (Color Dialog) Example, Common Dialog Control

The following example displays a Color dialog box when a command button is chosen.  When the user selects a color and clicks OK, the BackColor property for a form is set.

' Declarations section  Open dialog flags.
Const CC_RGBINIT = &H1&

Sub Command1_Click ()
CMDialog1.Color = &HFF&	' Set initial color selection for dialog.
CMDialog1.Flags = CC_RGBINIT
CMDialog1.Action = 3	' Display color dialog.
Form1.BackColor = CMDialog1.Color	' Set the form's BackColor.
End Sub


Flags Property (Font Dialog)

Applies To

Common dialog.

Description

Sets the options for the Font dialog box.

Usage

[form.]CMDialog.Flags[ = flag ]

Remarks

The following constants are available for the Font dialog box:

Constant	Value	Description
CF_APPLY	&H200&	Specifies that the dialog box should enable the Apply button.
CF_ANSIONLY	&H400&	Specifies that the dialog box should allow only a selection of the fonts that use the Windows character set. If this flag is set, the user will not be able to select a font that contains only symbols.
CF_BOTH	&H3&	Causes the dialog box to list the available printer and screen fonts. The hDC property identifies the device context associated with the printer.
CF_EFFECTS	&H200&	Specifies that the dialog box should enable strikethrough, underline, and color effects.
CF_FIXEDPITCHONLY	&H4000&	Specifies that the dialog box should select only fixed-pitch fonts.
CF_FORCEFONTEXIST	&H10000&	Specifies that an error message box is displayed if the user attempts to select a font or style that does not exist.
CF_LIMITSIZE	&H2000&	Specifies that the dialog box should select only font sizes within the range specified by the Min and Max properties.
CF_NOSIMULATIONS	&H1000&	Specifies that the dialog box should not allow GDI (graphic device interface) font simulations.
CF_NOVECTORFONTS	&H800&	Specifies that the dialog box should not allow vector-font selections.
CF_PRINTERFONTS	&H2&	Causes the dialog box to list only the fonts supported by the printer, specified by the hDC property.
CF_SCALABLEONLY	&H20000&	Specifies that the dialog box should allow only the selection of fonts that can be scaled.
CF_SCREENFONTS	&H1&	Causes the dialog box to list only the screen fonts supported by the system.
CF_SHOWHELP	&H4&	Causes the dialog box to display a Help button.
CF_TTONLY	&H40000&	Specifies that the dialog box should allow only the selection of TrueType fonts.
CF_WYSIWYG	&H8000&	Specifies that the dialog box should allow only the selection of fonts that are available on both the printer and the display. If this flag is set, the CF_BOTH and CF_SCALABLEONLY flags should also be set.
These flags are defined in the file CONSTANT.TXT.

You can also define selected flags.  Use the Const keyword in the Declarations section of the startup form to define the flags you want to use.  For example:

Const OFN_READONLY  = &H00000001&
Const CF_EFFECTS    = &H00000100&

You can set more than one flag for a dialog box using the Or operator.  For example:

CMDialog1.Flags = &H10& Or &H200&

Adding the desired constant values produces the same results.  The following is equivalent to the preceding example:

CMDialog1.Flags = &H210&

Data Type

Long


Max, Min Properties (Common Dialog)

Applies To

Common dialog (print, font dialogs).

Description

Font dialog [image] Determines the smallest and largest font sizes displayed in the Size list box.

Print dialog [image] Determines the minimum and maximum allowed values for the print range.

Usage

[form.]CMDialog.Min[ = points ]

[form.]CMDialog.Max[ = points ]

[form.]CMDialog.Min[ = pagenumber ]

[form.]CMDialog.Max[ = pagenumber ]

Remarks

With the Font dialog, the CF_LIMITSIZE flag must be set before using these properties.

With the Print dialog, the Min property determines the smallest number the user can specify in the From text box.  The Max property determines the largest number the user can specify in the To text box.

Data Type

Integer


Copies Property

Applies To

Common dialog (print dialog).

Description

Sets or returns the number of copies to be printed.

Usage

[form.]CMDialog.Copies[ = pages ]

Remarks

This property returns the number of copies specified by the user in the Copies text box.

If the PD_USEDEVMODECOPIES flag is set, this property always returns 1.

Data Type

Integer


Flags Property (Print Dialog)

Applies To

Common dialog.

Description

Sets the options for the Print dialog box.

Usage

[form.]CMDialog.Flags[ = flag ]

Remarks

The following constants are available for the Print dialog box:

Constant	Value	Description
PD_ALLPAGES	&H0&	Sets or returns the state of the All Pages option button.
PD_COLLATE	&H10&	Sets or returns the state of the Collate check box.
PD_DISABLEPRINTTOFILE	&H80000&	Disables the Print to File check box.
PD_HIDEPRINTTOFILE	&H100000&	The Print to File check box is not displayed.
PD_NOPAGENUMS	&H8&	Disables the Pages option button and the associated edit control.
PD_NOSELECTION	&H4&	Disables the Selection option button.
PD_NOWARNING	&H80&	Prevents a warning message from being displayed when there is no default printer.
PD_PAGENUMS	&H2&	Sets or returns the state of the Pages option button.
PD_PRINTSETUP	&H40&	Causes the system to display the Print Setup dialog box rather than the Print dialog box.
PD_PRINTTOFILE	&H20&	Sets or returns the state of the Print to File check box.
PD_RETURNDC	&H100&	Returns a device context for the printer selection made in the dialog box. The device context is returned in the dialog boxs hDC property.
PD_RETURNIC	&H200&	Returns an information context for the printer selection made in the dialog box. An information context provides a fast way to get information about the device without creating a device context. The information context is returned in the dialog boxs hDC property.
PD_SELECTION	&H1&	Sets or returns the state of the Selection option button. If neither PD_PAGENUMS nor PD_SELECTION are specified, the All option button is in the selected state.
PD_SHOWHELP	&H800&	Causes the dialog box to display the Help button.
PD_USEDEVMODECOPIES	&H40000&	If a printer driver does not support multiple copies, setting this flag disables the copies edit control. If a driver does support multiple copies, setting this flag indicates that the dialog box should store the requested number of copies in the Copies property.
These flags are defined in the file CONSTANT.TXT.

You can also define selected flags.  Use the Const keyword in the declarations section of the startup form to define the flags you want to use.  For example:

Const OFN_READONLY  = &H00000001&
Const CF_EFFECTS    = &H00000100&

You can set more than one flag for a dialog box using the Or operator.  For example:

CMDialog1.Flags = &H10& Or &H200&

Adding the desired constant values produces the same results.  The following is equivalent to the preceding example:

CMDialog1.Flags = &H210&

Data Type

Long


FromPage, ToPage Properties

Applies To

Common dialog (print dialog).

Description

Set or return the values for the From and To text boxes.

Usage

[form.]CMDialog.FromPage[ = page ]

[form.]CMDialog.ToPage[ = page ]

Remarks

Use these properties to determine the beginning and ending pages to be printed.  These properties are valid only when the PD_PAGENUMS flag has been set.

Data Type

Integer


PrinterDefault Property

Applies To

Common dialog (print dialog).

Description

Determines if the user's selections in the Print dialog box are used to change the system's default printer settings.

Usage

[form.]CMDialog.PrinterDefault[ = {True | False}]

Remarks

When this property is set to True, any selections the user makes in the Setup portion of the Print dialog box (printer selection, orientation, and so on) are used to change the printer settings in the user's WIN.INI file.

When PrinterDefault is True, you can write code to print directly to the Visual Basic Printer object.  Otherwise, you must use the Windows graphic device interface (GDI) calls to print to the printer specified by the control's hDC property.

Note   If you have previously printed to the Printer object, make sure you have ended that print job using Printer.EndDoc.  This releases the hDC associated with that printer.  You will get a new hDC for the default printer the next time you print to the Printer object.  If you don't do this, it is possible for the user to select a new printer while the Printer object contains a handle to the old printer.

Data Type

Integer (Boolean)


Error Messages (Common Dialog)

The following table lists the trappable errors for the common dialog control.

Error

number	Message explanation

32765 	CDERR_INITIALIZATION

The common dialog function failed during initialization.  This error often occurs when sufficient memory is not available.

32761	CDERR_FINDRESFAILURE

The common dialog function failed to load a specified string.

32760	CDERR_LOADRESFAILURE

The common dialog function failed to load a specified resource.

32759	CDERR_LOCKRESFAILURE

The common dialog function failed to lock a specified resource.

32758	CDERR_MEMALLOCFAILURE

The common dialog function was unable to allocate memory for internal data structures.

32757	CDERR_MEMLOCKFAILURE

The common dialog function was unable to lock the memory associated with a handle.

32755	CDERR_CANCEL

Cancel was selected.

32752	CDERR_ALLOC

Couldn't allocate memory for FileName or Filter.

32751	CDERR_HELP

The call to WinHelp failed.  Check the Help property values.

28671	PDERR_PRINTERCODES

The PD_RETURNDEFAULT flag was set in the Flags member of the PRINTDLG data structure, but either the hDevMode or hDevNames field was nonzero.

28670	PDERR_SETUPFAILURE

Load of the required resources failed.

28669	PDERR_PARSEFAILURE

The common dialog function failed to parse the strings in the [devices] section of the file WIN.INI.

28668	PDERR_RETDEFFAILURE

The PD_RETURNDEFAULT flag was set in the Flags member of the PRINTDLG data structure, but either the hDevMode or hDevNames field was nonzero.

28667	PDERR_LOADDRVFAILURE

The PRINTDLG function failed to load the specified printer's device driver.

28666	PDERR_GETDEVMODEFAIL

The printer device driver failed to initialize a DEVMODE data structure.  (This error constant applies only to printer drivers written for Windows version 3.0 or later).

28665	PDERR_INITFAILURE

The PRINTDLG function failed during initialization.

28664	PDERR_NODEVICES

No printer device drivers were found.

28663	PDERR_NODEFAULTPRN

A default printer does not exist.

28662	PDERR_DNDMMISMATCH

The data in the DEVMODE and DEVNAMES data structures describes two different printers.

28661	PDERR_CREATEICFAILURE

The PRINTDLG function failed when it attempted to create an information context.

28660	PDERR_PRINTERNOTFOUND

The [devices] section of the file WIN.INI did not contain an entry for the requested printer.

24574	CFERR_NOFONTS

No fonts exist.  Before displaying the Font dialog box, you must set one of these flags: CF_BOTH, CF_PRINTERFONTS, or CF_SCREENFONTS.

20478	FNERR_SUBCLASSFAILURE

An attempt to subclass a list box failed due to insufficient memory.

20477	NERR_INVALIDFILENAME

File name is invalid.

20476	FNERR_BUFFERTOOSMALL

The buffer at which the member lpstrFile points is too small.  When this error occurs, the minimum required string length is displayed in the first few characters of the FileName property.


Other Information Sources

All help and text files included with the Standard Edition are also included with the Professional Edition.

Standard Edition

Help Files

Text Files

Professional Edition

Help Files

Text Files

Note   When Visual Basic is installed, as each Help file is installed, it is listed in WINHELP.INI, located in your Windows directory.  If you move a Help file to a different directory, be sure to change the path in WINHELP.INI.  If a Help file does not exist, is not in your path, or is not in the directory specified in WINHELP.INI, WinHelp displays an appropriate message.


Standard Edition Help Files

You can click on any help file to go to the main table of contents of that file.  If the file is not available, an error occurs.

Visual Basic Help [image] Documents Visual Basic for Windows.

SetupWizard [image] Documents the SetupWizard application.  For information about the Setup Toolkit, search for Setup in the Visual Basic help file.

Data Manager [image] Documents the Data Manager application.

Note   When Visual Basic is installed, as each Help file is installed, it is listed in WINHELP.INI, located in your Windows directory.  If you move a Help file to a different directory, be sure to change the path in WINHELP.INI.  If a Help file does not exist, is not in your path, or is not in the directory specified in WINHELP.INI, WinHelp displays an appropriate message.


Professional Edition Help Files

In addition to the help files provided with the Standard Edition, these help files are included with the Professional Edition.  You can click on any help file to go to the main table of contents of that file.  If the file is not available, an error occurs.

Crystal Reports [image] Documents the Crystal Reports application.

Custom Control Reference [image] Documents each of the cusom controls provided with the Professional Edition.

Help Compiler Reference [image] Documents the Windows Help application for Help writers and programmers.

Hotspot Editor [image] Documents the segmented hypergraphic editor for creating hotspots within graphics for use in authoring Help files.

KnowledgeBase [image] A collection of articles from Microsoft Technical Support with tips, ideas and solutions.

ODBC Installation Help [image] Documents the installation tools for ODBC.

Oracle ODBC Driver [image] Documents the ODBC driver for Oracle databases.

SQL Server ODBC Driver [image] Documents the ODBC driver for SQL Server databases.

Visual Basic API Reference [image] Documents the Custom Control Development Kit.

Windows 3.1 API for Visual Basic [image] Declarations, structures, and constants for the Windows API as used in Visual Basic.

Windows 3.1 SDK Help [image] Documents Windows functions as used in the C programming language.

Note   When Visual Basic is installed, as each Help file is installed, it is listed in WINHELP.INI, located in your Windows directory.  If you move a Help file to a different directory, be sure to change the path in WINHELP.INI.  If a Help file does not exist, is not in your path, or is not in the directory specified in WINHELP.INI, WinHelp displays an appropriate message.


Standard Edition Text Files

You can click on any of these files to launch Notepad and load the file.

README.TXT [image] Information on last minute changes to Visual Basic, as well as additional information.

CONSTANT.TXT [image] Global symbolic constants for Visual Basic properties, events, functions and statements.

DATACONS.TXT [image] Global symbolic constants for the data access features of Visual Basic.

EXTERNAL.TXT [image] Additional README information about connecting to external databases.

PACKING.LST [image] List of all files on the distribution disks provided with Visual Basic.


Professional Edition Text Files

In addition to the text files provided with the Standard Edition, these text files are included with the Professional Edition.  You can click on any file to launch Notepad and load that file.  If the file is too large for Notepad, you may have to use a different word processor.

BTRIEVE.TXT [image] Supplementary information on importing, exporting, or attaching Btrieve tables with Visual Basic.

ORACLE.TXT [image] Setup information for the ODBC Oracle driver to run with your ORACLE RDBMS software.  If you installed ODBC, this file is in your Windows\SYSTEM directory.

PERFORM.TXT [image] Performance tuning tips for Visual Basic version 3.0 and Microsoft Access (TM) Relational Database System for Windows version 1.1.

SAMPLES.TXT [image] List of applications written in Visual Basic that demonstrate techniques discussed in the printed documentation.

WIN30API.TXT [image] Global symbolic constants for Windows 3.0 API functions.

WIN31API.TXT [image] Global symbolic constants for Windows 3.1 API functions.

WINMMSYS.TXT [image] Type declarations and global symbolic constants for Windows 3.1 multimedia API functions.


action query

A query that performs an action, such as update, delete, or insert, but returns no records.  A query that returns records is not an action query.


aggregate function

A function, such as Count, Avg, and Var, used in creating a query that calculates totals.  You can select aggregate functions in the Total row of the QBE grid.  In writing expressions and in programming, you can use SQL aggregate functions (including the three listed above) and domain aggregate functions to determine various statistics.


attached table

A table in another database linked to the current database.  You have the same access to the data in an attached table as in a normal table.


Bookmark

A property of a recordset object (Table, Dynaset, or Snapshot) that contains a string identifying the current record.  If you assign the bookmark value to a variable and then move to another record, you can make the earlier record current again by assigning the value of the string variable to the Bookmark property.


bound control

A control that provides access to a specific field in a database through a data control on the same form.  A control is bound to a data control through its DataSource and FieldSource properties.  When a data control moves from one record to the next, all bound controls on the same form change to display data from fields in the current record.  When users change data in a bound control and then move to a different record, the changes are automatically saved in the database.


consistent

The state of a multiple-table Dynaset that allows you to update only fields whose records can be represented by only one record in the Dynaset.  For example, in a Dynaset that is a join of two tables (a one-to-many relationship), only the fields from the "many" side of the join can be changed.


copy buffer

A location for the contents of a record that is open for editing.  The Edit method copies the current record to the copy buffer; the AddNew method clears the buffer for a new record; and the Update method saves the data from the copy buffer to the database, replacing the current record.


counter

A Long data-type field in a table where the DB_AUTOINCREMENT attribute has been set.  A  counter field is automatically incremented by 1 when a new record is added to the table and no specific value is provided for the counter field.


current index

For an indexed Table, the index indicated by the Index property.  The current index is the basis for ordering records in a Table and is used by the Seek method to locate records.  A Table can have more than one index, but only one is current at any given time.


current record

The record in a recordset that would be changed if the Edit and Update methods were invoked and to which the Move methods are relative.  Only one record in a recordset can be the current record.


current transaction

All changes made to a recordset since you used the last BeginTrans statement and before you use the Rollback or CommitTrans statement.


data page

A portion of the database file in which record data is stored.  Depending on the size of the records, a data page may contain more than one record.  A data page is 2K in size.


database

A collection of data related to a particular topic or purpose.  A database contains tables and can also contain queries and indexes.


Database object

A database is a collection of data related to a specific topic or purpose.  A database can contain tables, queries, and indexes.  A Database object is a logical representation of a physical database.


database objects

The database objects are Dynaset, Field, Index, QueryDef, Snapshot, Table, and TableDef.


domain

A set of records defined by a table, a query, or an SQL expression.  Domain aggregate functions, such as DMax and DStDev, return statistical information about a specific domain.


domain function

A function used to aggregate data over a certain set of records (the domain).  The domain functions are DAvg, DCount, DFirst, DLast, DLookup, DMax, DMin, DStDev, DStDevP, DSum, DVar, and DVarP.  These functions can be used in SQL statements but not in Visual Basic code.


Dynaset

A type of recordset that has updatable records.  Like a Table, a Dynaset has data in records (rows) and fields (columns).  Unlike a Table, a Dynaset can be the result of a query that joins two or more tables.


exclusive

Indicates whether a database or a table can be shared by other users in a multiuser environment.  If the database or table is opened for exclusive use, it cannot be shared by other users.


external database

Either an ODBC database such as SQL Server or Oracle that resides in a remote location, or one of the external databases such as Btrieve, Paradox, dBASE, FoxPro, or Microsoft Access.


Field

A category of information stored in a table in a database.  In a spreadsheet, it would be represented as a column of information.


field data types

The following table lists the field data types and their equivalent Visual Basic data types.

Field data type	Visual Basic data type

True/False	Integer

Byte	Integer

Integer	Integer

Long	Long

Currency	Double

Single	Single

Double	Double

Date/Time	Variant

Text	String

Long Binary	String or Variant; can be longer than 64K

Memo	String or Variant; can be longer than 64K

Note that any kind of value can be stored in a Variant data type.


filter

A set of criteria applied to records in order to create a subset of the records.


inconsistent

The state of a multiple-table Dynaset that allows you to update all fields, even if such updates affect other records in the Dynaset.  For example, in a Dynaset that is a join of two tables (a one-to-many relationship), the fields from the "one" side and the "many" side of the join can both be changed.


index (Data Access)

A feature that speeds data access by ordering values in a field.


join

A database operation that combines some or all records from two or more tables.  There are several types of joins:

An equi-join, which combines records from two tables whenever there are matching values in the joined fields.

An outer join, which includes all the records from one table and only those records from the second table in which the joined fields are equal.

A self-join, which is a table joined to itself.  A self-join is useful when you ask hierarchical questions, such as a query that shows all the managers and the people who report to them.

You create a join with an SQL statement.


object variable

A variable containing an object recognized by Visual Basic.  You can declare variables of object data types with the Dim, Global, or Static statements.

You can create variables of these object types:

CheckBox	FileListBox	MDIForm

ComboBox	Form	OptionButton

CommandButton	Frame	PictureBox

CommonDialog	Grid	TextBox

Control	HScrollBar	Timer

Data	Image	VScrollBar

DirListBox	Label

DriveListBox	ListBox

In the Professional Edition, you can also create variables of these object types:

Database	Index	Table

Dynaset	Indexes	TableDef

Field	QueryDef	TableDefs

Fields	Snapshot


ODBC (Open Database Connectivity)

A standard protocol for SQL database servers, such as Microsoft SQL Server or Oracle.  You can install ODBC drivers that connect to these SQL database servers and access the data in SQL databases.


one-to-many relationship

A relationship between tables in which each record in the primary table can be associated with many records in the related table (each primary key value can appear many times in the related table).


one-to-one relationship

A relationship between tables in which each record in the primary table can be associated with only one record in the related table.


optimistic

A type of locking in which the page containing one or more records, including the record being edited, is unavailable to other users only while the record is being updated by the Update method.


parameter

An element containing a value that you can change to affect the results of the query.  For example, a query returning data about an employee might have a parameter for the employee's name.  You can then use one QueryDef to find data about any employee by setting the parameter to a specific name before running the query.


pessimistic

A type of locking in which the page containing one or more records, including the record being edited, is unavailable to other users when you use the Edit method and remains unavailable until you use the Update method.


Procedure box <definition>
Procedure box

A list box at the upper-right of the Code window that displays the procedures recognized for the object displayed in the Object box.


query

A formalized instruction to a database to either return a set of records as specified in the query, or perform a specified action on a set of records as specified in the query.  For example, this is an SQL query statement that returns records: SELECT [Company Name] FROM Publishers WHERE State = 'NY'


QueryDef

An object that contains the SQL statement describing a query.  The QueryDef is stored in the database.


read-only

A type of access to records whereby users can view but not modify data.


recordset

A group of records.  The three types of recordsets are Dynasets, Snapshots, and Tables.


referential integrity

Rules that you follow to preserve relationships between tables when you add, change, or delete records.  Enforcing referential integrity involves prohibiting users from adding records to a related table for which there is no primary record, changing values in a primary table that would result in orphan records in a related table, and deleting records from a primary table when there are matching related records.


server

In an active data link of a dynamic data exchange (DDE) conversation, refers to an application furnishing data in response to a request from a client application.  In DDE terminology, the terms "server" and "client" have been replaced by source and destination.


Snapshot

A type of recordset whose records are not updatable.  A Snapshot is a static image of a set of records.


source

The program that sends information and commands when two or more programs that support dynamic data exchange (DDE) are running simultaneously.


SQL statement

An expression that defines a Structured Query Language (SQL) command, such as SELECT, UPDATE, or DELETE, and includes clauses such as WHERE and ORDER BY.  SQL strings and statements are typically used in queries and in aggregate functions.


table

A recordset in a database that stores data in records (rows) and fields (columns).  The data is usually about a particular category, such as employees or parts.


Table object

A type of recordset that is a logical representation of a physical object within a database that contains data about a particular subject.  Like all recordsets, a Table object has records (rows) and fields (columns).


tabledef object

An object in a database that defines the structure of a table.  In contrast, a Table object is the physical container of the data in a Database.


text box

A control that provides a place to display or enter text.


transaction

A series of changes made to a recordset.  You mark the beginning of a transaction with the BeginTrans statement.  To commit the transaction, use the CommitTrans statement.  To undo all your changes since BeginTrans, use the Rollback statement.

There is an implicit transaction while queries are running.  If a query does not complete for any reason, it is automatically rolled back.

Transactions are optional and can be nested up to five levels.


update

The process that saves changes to data in a record.  Until the record is saved, changes are stored in a temporary record called the copy buffer.


variant expression

Any expression that can evaluate to numeric, string, or date data as well as the special values Empty and Null.


verb

Specifies the operation an object performs when it is activated.  To activate an object, set Action = 7 (OLE_ACTIVATE).  Use the Verb property to specify the action to perform when an object is activated.


Index already exists.

Error 3284

You tried to create an index on a field for which an index is already defined.


Can't delete an index that is used in a relationship.

Error 3281

Referential integrity does not allow you to delete an index that is part of a relationship.


Invalid object type; Menu control required

Error 427

The first argument for the Popup Menu method must be a menu control.


Invalid property value.

Error 3271

You have assigned a value to this property which is not a legal value.  Check the documentation for acceptable values for this property.


Invalid reference in SELECT statement.

Error 3242

You entered an invalid field or table reference in the SELECT statement.

See Also

SELECT Statement (SQL)


Database engine has already been initialized.

Error 3279

You attempted to initialize the data access engine, but it has already been initialized.


Method not applicable for this object.

Error 3273

The method specified does not exist for an object of this type.


Name not found in this collection.

Error 3265

The name specified does not exist in this collection of objects.


No Defined Value

Error 390

No value has been defined for the specified property.


No fields defined - cannot append table.

Error 3264

The append operation cannot be executed because you did not specify any fields.  A TableDef object must contain at least one field before it can be appended to the TableDefs collection.  Define a field object, append it to the TableDef, and try again.


OLE Automation argument type mismatch

Error 439

You have referred to a method or a property array of an object variable with the wrong number of arguments or with an argument of the wrong type.


OLE Automation file or object name syntax error

Error 432

The class parameter of the GetObject function contains an error, or specifies an invalid class name.


OLE Automation Lbound or Ubound on non Array value

Error 442

The LBound or UBound function was used with a property or method of an OLE object (object.property, object.method), but the return value was not an array.


OLE Automation method did not return a value

Error 437

A Visual Basic statement refers to a method of an object variable as if it returned a value. However, the method does not return a value when it is called.


OLE Automation method returned unsupported type

Error 436

An OLE Automation method or property returned an array or an unsupported data type.

Visual Basic allows you to read and write elements of arrays but not whole arrays. Try to read one element from the array at a time. If the size of the array is known this may be as simple as supplying a subscript to the array reference. The documentation of the application that created the object may indicate how to determine the size of the array.


OLE Automation no such property or method

Error 438

A Visual Basic statement refers to a non-existing method or property of an object variable.


OLE Automation object does not exist

Error 433

The object specified in the GetObject function does not exist.

Make sure the file specified in the GetObject function exists. If it does, start the application that created the file and view the file from that application to check for the existence of the specified object.


OLE Automation Object does not have a default value

Error 443

Visual Basic cannot determine the default value for the property of the specified object.


OLE Automation server cannot create object

Error 429

OLE 2.0 was unable to locate or run the application associated with the specified object. Check that the associated application is correctly registered in the OLE2 registration database (REG.DAT). In addition, act on any error messages from the OLE Automation application which might indicate why it failed to start.


OLE Automation server cannot load file

Error 431

OLE 2.0 could not load the file specified in the GetObject function. Check that the specified file can be read and is in the correct format (try opening the file in the application that created it).


OLE Automation error.  Item

Error 440

An error occurred while executing a method or accessing a property of an object variable. The error was reported by the application that created the object.


OLE initialization error

Error 435

Visual Basic can not initialize OLE2.  Make sure all the current OLE 2.0 files are in the \SYSTEM directory of your main Windows directory, and that no other copies of these files exist elsewhere on your system.

OLE 2.0 requires Microsoft Windows version 3.1 or later.


Paradox: No primary index.

Error 3289

You attempted to create a Paradox table without a primary index.  All Paradox tables must have a primary index.


Popup menu must have at least one submenu

Error 428

You have defined a Popup menu with no submenus.


Property not found.

Error 3270

The property you specified does not exist for this object.


Property value only valid when Field is part of a recordset.

Error 3267

You can't access or store values in a Field object unless it is part of a Table, Dynaset or Snapshot.


Table 'Item1' is exclusively locked by user 'Item3' on machine 'Item2'.

Error 3189

You cannot access the specified table because it is currently exclusively locked by another user.  Wait for the other user to release the lock, then try the operation again.


Can't have more than 10 fields in an index.

Error 3277

You defined an index with more than ten fields.  Reduce the number of fields to ten or less.


Can't have action query 'Item' as an input.

Error 3069

You can't use the name of an action query as input to the FROM clause.  Instead, use the name of a SELECT query.


'Item' is a class name

Error 3769

The specified identifier is already in use as the name of a class of control or form.  Use another name.


A module with this name exists

Error 3739

You cannot have two modules with the same name.  Save the module with another name.


Bad file mode: 'Item'

Error 3709

Map to 54


Bad file name or number: 'Item'

Error 3707

Map to 52


Bad record length: 'Item'

Error 3714

Map to 59


Bad record number: 'Item'

Error 3718

Map 63


Between operator without And

Error 2430

When using the Between operator to test whether a value of an expression lies within a specified range of values, you specify the upper and lower limits of the range separated with the word "AND". For example, to test for a range of "A" to "C" code:

WHERE MyField BETWEEN "A" AND "C"


Can't delete module; must Re-Initialize first

Error 3736

Visual Basic cannot delete this module without returning to design time.


Can't refer to Dynaset property in Design view.

Error 2460

This property cannot be accessed until runtime.


Can't refer to Parent property in Design view.

Error 2459

This property cannot be accessed until runtime.


Can't set value.

Error 2448

Visual Basic cannot assign a value to this object.


Device unavailable: 'Item'

Error 3724

The specified device is unavailable, either because it was physically open or disconnected, or because the required software drivers have not been loaded.


Disk not ready: 'Item'

Error 3726

Map to 71


Expression too complex

Error 2445

This expression is too complex for Visual Basic. Simplify it or break the operation down into more discrete steps.


Extra )

Error 2435

There is currently no help for this error.


File previously loaded: 'Item'

Error 3721

This file has already been loaded.


Function isn't available in expressions

Error 2426

You cannot use this function in an expression in Visual Basic.


IIF function without ()

Error 2440

The IIF function requires parenthesis around its arguments (as shown below).

IIf( expr, truepart, falsepart )

The IIf function has the following parts:

Argument	Description
expr	Expression you want to evaluate.
truepart	Value or expression returned if expr is True.
falsepart	Value or expression returned if expr is False.


In operator without ()

Error 2429

When coding an SQL statement that includes the "IN" operator you must surround the list of items to test with parenthesis. For example, to see if a value is one of a set of values you could code in the WHERE clause of an SQL query:

WHERE Publishers.State IN ('TX', 'CA', 'WA')

This code tests to see if the State Field is either Texas, California, or Washington.


Incompatible version of WIN87EM.DLL; quitting

Error 3701

Your system contains a version of WIN87EM.DLL that is incompatible with Visual Basic. Make sure you have only one copy of this file (keep only the latest version).


Input past end of file: 'Item'

Error 3717

Map to 62


Invalid argument used with DatePart, DateAdd or DateDiff function.

Error 2468

One of the parameters passed to a DatePart, DateAdd or DateDiff function function was invalid.


Invalid arguments used with domain function

Error 2428

One or more of the arguments used with an SQL domain function was invalid. Search Help for the function used for more information.


Invalid control number reference.

Error 2458

Not supported in VB3.


Invalid form number reference.

Error 2456

Not supported in VB3.


Invalid group level number reference.

Error 2464

Not supported in VB3.


Invalid group level reference.

Error 2463

The reference to a group level was invalid.


Invalid method in expression.

Error 2449

You cannot use the method specified in this expression.


Invalid reference to '!Item'.

Error 2454

There is currently no help for this error.


Invalid reference to control 'Item'.

Error 2453

There is currently no help for this error.


Invalid reference to Dynaset property.

Error 2466

Not supported in VB3.


Invalid reference to field 'Item'.

Error 2465

Not supported in VB3.


Invalid reference to form 'Item'.

Error 2450

Not supported in VB3.


Invalid reference to Parent property.

Error 2452

Not supported in VB3.


Invalid reference to property 'Item'.

Error 2455

Not supported in VB3.


Invalid reference to report 'Item'.

Error 2451

Not supported in VB3.


Invalid report number reference.

Error 2457

Not supported in VB3.


Invalid section number reference.

Error 2462

Not supported in VB3.


Invalid section reference.

Error 2461

Not supported in VB3.


Invalid subclass 'Item' referred to in TypeOf function.

Error 2477

There is currently no help for this error.


Invalid use of '.', '!', or '()'.

Error 2447

Map to 2423


Invalid use of '.', '!', or '()'.

Error 2423

The expression does not use delimiters correctly. To reference the properties of data objects, it is recommended that you use the ."<name>" syntax. See the Programmer's Reference "Accessing the Recordset Object" for more information.


Invalid use of Is operator

Error 2443

The IS  operator is used to determine if an expression is NULL.


Invalid use of parentheses

Error 2442

The expression does not have balanced parenthesis "( )" or uses parenthesis in some other invalid manner.


Invalid use of vertical bars

Error 2437

The expression uses the vertical bar "|" in some invalid manner.


Item in linked master field.

Error 2472

Not supported in VB3.


Item in query.

Error 2471

The specified item is invalid in the context of a query.


Item in validation rule.

Error 2470

Not supported in VB3.


Item1 in 'Item2' expression.

Error 2473

There is currently no help for this error.


Item1 in validation rule: 'Item2'.

Error 2469

There is currently no help for this error.


Missing ), ], or Item

Error 2436

There is currently no help for this error.


No control is active.

Error 2474

Not supported in VB3.


No form is active.

Error 2475

Not supported in VB3.


No report is active.

Error 2476

Not supported in VB3.


Not enough memory to run; quitting

Error 3703

Visual Basic could not obtain enough memory to run. Close other applications and try again.


Object has no value

Error 2427

There is currently no help for this error.


Object referred to in expression no longer exists.

Error 2467

An object ceases to exist when it is destroyed  when its associated data object is closed or is no longer defined in the current scope.


Out of Memory - insufficient variable space

Error 3761

There are too many large variables in this module. Reduce the size of some variables (declare them as a data type other than Variant), or make some ot them into an array.


Out of Memory - too many global symbols

Error 3759

There are too many global variables, constants, declarations, and procedure names.  Make some of them module-level or Private.


Out of Memory - too many global variables, Global CONST, & Types

Error 3762

There are too many global variables, constants, and Type declarations.  Make some of them module-level.


Out of Memory - too many procedures, forms & modules

Error 3763

There are too many procedures, forms, and modules.  Merge some procedures or modules together.


Out of Memory - too many symbols in form or module

Error 3760

There are too many variables, constants, declarations, and procedure names in the module. Replace some with globals, or move some to another module.


Out of Memory - too much code in procedure: 'Item'

Error 3758

The specified procedure contains too much code.  Move some of the code into another procedure and call it from this one.


Out of Memory - too much form/mod-level code in: 'Item'

Error 3759

This module contains too many module-level declarations.  Move some to another module.


Out of memory during calculation

There was insufficient memory to complete the specified calculation. Reduce the number of programs running or the size of other memory-consuming variables.

Other kinds of memory problems may also create this error.


Search string has unmatched brackets

Error 3751

When performing pattern matching, you must supply matching open and closed square brackets.


Stop statement encountered

Error 3704

Visual Basic encountered a Stop statement in the program and halted execution normally.


Syntax error

Error 2438

The statement contains a syntax error.


Syntax error

Error 2432

Map to 2438.


Syntax error

Error 2431

Map to 2438.


Syntax error

Error 2434

Map to 2438.


Syntax error

Error 2433

Map to 2438.


Syntax error in date

Error 2421

Date syntax incorrect.


Syntax error in number

Error 2420

A number was called for here; it is invalid.


Syntax error in string

Error 2422

A string was called for here; it is invalid.


Tried to load module with duplicate procedure definition: 'Item'

Error 3720

The module contained the specified procedure name, which already exists in a loaded module.  Rename one of the conflicting procedures.


Unexpected error; quitting

Error 3702

An unexpected error occured, and Visual Basic was unable to continue. This may be a hardware problem or an effect of other software in your system.


Unknown function name

Error 2425

The function specified was not recognized.


Unknown name

Error 2424

The name specified was not recognized.


Wrong number of arguments used with function

Error 2439

The function specified was not passed the right number of arguments.


Wrong version of run-time DLL

Error 3705

Visual Basic cannot find VBRUN300.DLL, or it is finding the wrong version of one of the custom control .VBX files. Make sure your system contains only one copy of these files (the latest version) in your WINDOWS\SYSTEM directory.


Couldn't delete from specified tables.

Error 3086

You tried to delete data from one or more tables, but the deletion couldn't be completed.

Possible causes:

You don't have permission to modify the table.  To change your permissions assignments, see your system administrator or the table's creator.

The database was opened for read-only access.  The database is read-only for one of these reasons:

You used the OpenDatabase function and opened the database for read-only access.

You used the Data control and set the ReadOnly property to True..

The database file has been defined as read-only in the database server operating system or by your network.

In a network environment, you don't have write privileges for the database file.

To delete the data, close the database, resolve the read-only condition, and then reopen the file for read/write access.


Can't input from internal report query (Item).

Error 3124

You tried to use an SQL statement that includes an explicit reference to a disallowed internal report query.


Can't insert into action query.

Error 3084

You tried to run an append query using an action query for the input.  Replace the action query with a select query and then try the operation again.


Duplicate output destination 'Item'.

Error 3063

You tried to execute a query that contains more than one output field with the same name.

Possible cause:

You created an SQL statement that includes an INSERT INTO Statement (SQL), SELECT...INTO Statement (SQL), or UPDATE Statement (SQL) statement listing the specified field name more than once.

Remove the duplicate fields, and then try the operation again.


Invalid argument.

Error 3001

You tried to perform an operation that involves a routine in a DLL, and one of the arguments to the routine is invalid.  Check your entry to make sure you have specified the correct arguments, and then try the operation again.


Query contains ambiguous (outer) joins.

Error 3285

You tried to execute an SQL statement that contains multiple joins, and the results of the query can differ depending on the order in which the joins are performed.  For example, this error can occur if you execute the following SQL statement:

SELECT * FROM Customers, Orders, [Order Details],
Customers LEFT JOIN Orders
ON Customers.[Customer ID] = Orders.[Customer ID],
Orders INNER JOIN [Order Details]
ON Orders.[Order ID] = [Order Details].[Order ID];

Execution of this statement produces an error because the order of the joins is ambiguous.  To force one of the joins to be performed first, create a separate query that performs the first join and then include that query in your SQL statement.  The following queries illustrate how you might construct the preceding query so that the INNER JOIN Operation (SQL) operation is performed before the LEFT JOIN, RIGHT JOIN Operations (SQL) operation:

Query1

SELECT * FROM Orders, [Order Details],
Orders INNER JOIN [Order Details]
ON Orders.[Order ID] = [Order Details].[Order ID];

Query2

SELECT * FROM Customers, Query1,
Customers LEFT JOIN Query1
ON Customers.[Customer ID] = Orders.[Customer ID];


Can't open any more databases.

Error 3048

You've reached the limit on the number of databases that can be opened at one time.  Close one or more open databases, and then try the operation again.


AddNew or Edit already used.

Error 3023

You haven't saved or rolled back the current changes and are trying to add or change another record.  Use Rollback or Update, and then use the AddNew or Edit method.


Can't execute a non-action query.

Error 3065

You tried to use the Execute method with a select query.  The Execute method is valid only with action queries.


Can't group on Memo or Long Binary (Item).

Error 3119

The GROUP BY Clause (SQL) of an SQL statement can't include Memo or Long Binary fields.


Can't have action query 'Item' as an input.

Error 3069

You can't use the name of an action query here.  Instead, use the name of a select query.  To run an action query, use the Execute method.


Can't have aggregate function in expression (Item).

Error 3095

You can't use an aggregate function in this expression.

See Also

SQL Aggregate Functions


Can't have aggregate function in GROUP BY clause (Item).

Error 3098

You can't use an aggregate function in the GROUP BY Clause (SQL) of an SQL statement.

See Also

SQL Aggregate Functions


Can't have aggregate function in JOIN operation (Item).

Error 3099

You can't use an aggregate function in the JOIN operation of an SQL statement.

See Also

LEFT JOIN, RIGHT JOIN Operations (SQL)

SQL Aggregate Functions


Can't have aggregate function in ORDER BY clause (Item).

Error 3097

You can't use an aggregate function in the ORDER BY Clause (SQL) of an SQL statement.

See Also

SQL Aggregate Functions


Can't have aggregate function in WHERE clause (Item).

Error 3096

You can't use an aggregate function in the WHERE Clause (SQL) of an SQL statement.

See Also

SQL Aggregate Functions


Can't have Memo or Long Binary in aggregate argument (Item).

Error 3115

You can't include Memo or Long Binary fields in an aggregate function.

See Also

SQL Aggregate Functions


Can't join on Memo or Long Binary (Item).

Error 3118

You can't join Memo or Long Binary fields.

See Also

LEFT JOIN, RIGHT JOIN Operations (SQL)


Can't join more than one table with the same name (Item).

Error 3081

You tried to join more than one table that has the same name.  Select different tables, rename one of the tables, or use an alias; and then try the operation again.

See Also

LEFT JOIN, RIGHT JOIN Operations (SQL)


Can't open action query 'Item'.

Error 3064

You tried to open an action query using the OpenQueryDef method.  This method is valid only with select queries.  Instead, use the Execute method with action queries.


Can't open any more files.

Error 3025

You've reached the limit on the number of files that can be opened at one time.  Close one or more open files, and then try the operation again.


Can't open any more tables.

Error 3014

You've reached the limit on the number of tables that can be opened at one time.  Close one or more open tables, and then try the operation again.


Can't open any more tables or queries.

Error 3037

You've reached the limit on the number of tables and queries that can be opened at one time.  Close one or more open tables or queries, and then try the operation again.


Can't sort on Memo or Long Binary (Item).

Error 3117

The ORDER BY Clause (SQL) of an SQL statement can't include Memo or Long Binary fields.


Couldn't find database 'Item'.

Error 3004

The database you're trying to use couldn't be found.  It may have been deleted, or you may have misspelled the name.  Check the name and path to make sure you entered it correctly.


Couldn't lock file; SHARE.EXE hasn't been loaded.

Error 3050

To enable file and record locking in a multiuser environment, you must first load SHARE.EXE.

To load SHARE.EXE

1	Exit Microsoft Windows.

2	Add the following line to your AUTOEXEC.BAT file:

SHARE.EXE /L:500

If you don't have an AUTOEXEC.BAT file on your system, enter the preceding line at the command prompt before you start Windows.  The number of locks you use depends on the particular applications you run and the number of files locked at any given time.  If other applications require file locks, you may need to specify more than 500 locks.

3	Reboot your system, then try the operation again.


Couldn't lock table 'Item'; currently in use.

Error 3009

You tried to lock a table while opening it, but the table cannot be locked because it is currently in use.  Wait a moment, and then try the operation again.


Couldn't save; currently locked by user 'Item2' on machine 'Item1'.

Error 3186

You tried to save a record that is currently locked by the specified user.  Wait for the other user to finish working with the record, and then try the operation again.


Can't repeat table name 'Item' in FROM clause.

Error 3074

You can't list the table name more than once.  Remove the extra occurrences of the table name, or use an alias.

See Also

FROM Clause (SQL)

Using SQL (Structured Query Language)


Characters found after end of SQL statement.

Error 3142

SQL statements can't have any characters following the semicolon (;).  Unlike lines of code in Visual Basic, SQL statements can't include remarks.  Remove the extra characters.

See Also

Using SQL (Structured Query Language)


Commit or Rollback without BeginTrans.

Error 3034

You tried to commit or roll back a transaction that you haven't started with a BeginTrans statement.

See Also

CommitTrans Statement

Rollback Statement


Couldn't update; currently locked by another session on this machine.

Error 3188

You tried to update information that is currently locked by another session.  Wait for the other session to finish; or close the other session, and then try the operation again.


Couldn't read; currently locked by user 'Item2' on machine 'Item1'.

Error 3187

You tried to read information that is currently locked by the specified user.  Wait for the other user to finish, and then try the operation again.


Couldn't save; currently locked by another user.

Error 3046

You tried to save information that is currently locked by another user.  To save your changes, wait for the other user to finish, and then try the operation again.


Couldn't save record; currently locked by another user.

Error 3158

You tried to save a record that is currently locked by another user.  To save your changes, wait for the other user to finish working with the record, and then try the operation again.  If you want to move to another record without saving your changes, choose Undo from the Edit menu.


Couldn't start transaction; too many transactions already nested.

Error 3003

You tried to nest a transaction more than five levels deep.  Use CommitTrans or Rollback to save or roll back the current transaction before you begin another.


Couldn't update; database is read-only.

Error 3027

You tried to save changes in a database that was opened for read-only access.

The database is read-only for one of these reasons:

You used the OpenDatabase function and opened the database for read-only access.

You are using the Data Control, and you set the ReadOnly property to True..

The database file has been defined as read-only in the operating system or by your network.

In a network environment, you don't have write privileges for the database file.

Close the database, resolve the read-only condition, and then reopen the file for read/write access.


'Item' isn't an index in this table.

Error 3015

You tried to use a field that isn't an index.  You can determine the valid index names by looking in the Indexes collection of the TableDef object.


Item in expression.

Error 3077

The expression you entered isn't valid for the reason indicated in the message.  Make sure you entered field names and punctuation correctly, and then try the operation again.


Item1 parameters were expected, but only Item2 were supplied.

Error 3061

This parameter query requires the specified number of parameters, and you supplied too few.  Provide the expected number of parameters, and run the query again.

See Also

OpenQueryDef Method

PARAMETERS Declaration (SQL)


Circular reference caused by alias 'Item' in query definition's SELECT list.

Error 3103

The specified alias created an unresolvable reference.  For example, this error can occur if you enter the following SQL statement, in which A is the circular reference:

SELECT A + B AS C, C + D AS E, E + F AS A
FROM MyTable;

See Also

SELECT Statement (SQL)


'Item' isn't a valid account name.

Error 3030

The specified account (user) name isn't valid.  User names can be from 1 to 20 characters long and can include alphabetic characters, accented characters, numbers, spaces, and symbols, with the following exceptions:

The characters "  /  \  [  ]  |  <  >  +  =  ;  ,  :  ?  *

Leading spaces

Control characters

User names are not case-sensitive.


Can't bind name 'Item'.

Error 3070

The specified name isn't a recognized field name or a valid expression.  In a query, this error can occur if you enter a name that improperly refers to a database, table, or field.  For example, BIBLIO.* produces this error.


Can't define field more than once.

Error 3191

You tried to create a table, and more than one field was defined with the same name.  Each field name in a table must be unique.


Can't group on fields selected with '*'.

Error 3121

You tried to execute a select that groups or totals fields selected with an asterisk ( * ).

Possible cause:

You created an SQL statement that includes an aggregate function or GROUP BY Clause (SQL) that refers to a field you selected with an asterisk.   This error occurs, for example, if you enter the following SQL statement:

SELECT * FROM Orders GROUP BY [Ship Via];


Can't group on fields selected with '*' (Item).

Error 3120

You tried to execute a select that groups or totals fields selected with an asterisk ( * ).  For example, this error occurs if you use the following SQL statement:

SELECT Orders.* FROM Orders GROUP BY [Ship Via];


Can't have duplicate key; index changes were unsuccessful.

Error 3022

You tried to duplicate a value in a field that is the underlying table's primary key or an index that doesn't allow duplicates.


Can't have Memo or Long Binary in criteria (Item) for aggregate function.

Error 3116

The HAVING Clause (SQL) of an SQL statement can't include Memo or Long Binary fields.


Can't include Memo or Long Binary when you select unique values (Item).

Error 3114

Remove the DISTINCT reserved word.

See Also

ALL, DISTINCT, DISTINCTROW Predicates (SQL)

SELECT Statement (SQL)


Can't perform operation; it is illegal.

Error 3219

You tried to use a method or property with or on a recordset, and it isn't valid for that object.

See Also

Programming Language

Properties Reference


Can't specify Fixed Column Heading 'Item' in a crosstab query more than once.

Error 3104

When you create a crosstab query that has fixed column headings, the values you specify must be unique.  Change one or more of the duplicate column headings, and then try the operation again.


Can't specify subquery in expression (Item).

Error 3203

The specified expression contains a subquery or other expression that functions as a subquery.

Possible cause:

You used a SELECT Statement (SQL) that includes an aggregate function that evaluates another aggregate function.  This error occurs, for example, if you execute the following statement:

TRANSFORM Sum([OrderAmount]) AS Sum1
SELECT Sum([Sum1]) AS Sum2, [Order ID], Sum([Sum2]) AS Expr1
FROM Orders
GROUP BY [Order ID]
PIVOT [Ship Name];

See Also

Using SQL (Structured Query Language)


Couldn't open file 'Item'.

Error 3051

Possible causes:

You must have Read Data permission for the specified file in order to view its data.  To change your permission assignments, see your system administrator or the table's or query's creator.

You tried to open the indicated file exclusively, but another user already has the file open.


Couldn't open PARADOX.NET.

Error 3172

Possible causes:

The ParadoxNetPath entry in the [Paradox ISAM] section in the .INI file isn't valid.  This error occurs if you're using the Paradox external database, and the Paradox entry points to a nonexistent directory.  Exit the application, correct the invalid entry using Microsoft Windows Notepad or another text editor, then try the operation again.

The ParadoxNetPath entry in the [Paradox ISAM] section in the .INI file points to a network drive, and that network drive isn't connected.  Check to make sure the network drive is available, and then try the operation again.


Couldn't delete; no delete permission for table or query 'Item'.

Error 3109

You must have Modify Data permission for the specified table or query in order to delete data.  To change your permission assignments, see your system administrator or the table's or query's creator.


Couldn't find installable ISAM.

Error 3170

An installable ISAM dynamic link library (DLL) file couldn't be found.  This file is required for operations such as attaching external tables (other than ODBC and Visual Basic/Microsoft Access tables).

Possible causes:

An entry in the [Installable ISAM] section in the .INI file isn't valid.  For example, this error occurs if you're using a Paradox external database, and the Paradox entry points to a nonexistent directory.  Exit the application, correct any invalid entries using Microsoft Windows Notepad or another text editor, and try the operation again.

One of the entries in the [Installable ISAM] section in the .INI file points to a network drive, and that network isn't connected.  Check to make sure the network is available, and then try the operation again.


Couldn't find output table 'Item'.

Error 3192

You tried to use INSERT INTO Statement (SQL) with the specified table and that table doesn't exist.  Check to make sure you entered the name correctly, and then try the operation again.


Couldn't insert; no insert permission for table or query 'Item'.

Error 3107

You must have Modify Data permission for the specified table or query in order to insert data into it.  To change your permission assignments, see your system administrator or the table's or query's creator.


Couldn't insert or paste; data too long for field.

Error 3163

The field into which you tried to insert or paste data isn't large enough to hold the data.  Try inserting or pasting less data.


Couldn't lock table 'Item'; currently in use.

Error 3211

To complete this operation, a table currently in use by another user must be locked.  Wait for the other user to finish working with the table, and then try the operation again.


Couldn't open database 'Item'.

Error 3007

The specified database is an internal Microsoft Access library database, and you can't open such databases.


Couldn't read; no read permission for table or query 'Item'.

Error 3112

You must have Read Data permission for the specified table or query in order to view its data.  To change your permission assignments, see your system administrator or the table's or query's creator.


Couldn't read definitions; no read definitions permission for table or query 'Item'.

Error 3110

You must have Read Definitions permission for the specified table or query in order to read its definition.  To change your permission assignments, see your system administrator or the table's or query's creator.


Couldn't save; currently locked by user 'Item2' on machine 'Item1'.

Error 3202

Possible causes:

You tried to save a record that is currently locked by another user.  Wait for the other user to finish working with the record, and then try the operation again.

The MS-DOS file sharing count has been exceeded.  You need to increase the number of locks installed with SHARE.EXE.

To load SHARE.EXE

1	Exit Microsoft Windows.

2	Using a text editor, add the following line to your AUTOEXEC.BAT file:

SHARE.EXE /L:500

If you don't have an AUTOEXEC.BAT file on your system, enter the preceding line at the command prompt before you start Microsoft Windows.  The exact number of locks you use depends on the particular applications you run and the number of files that are locked at any given time.  If other applications require file locks, you may need to specify more than 500 locks.

3	If you added SHARE.EXE to your AUTOEXEC.BAT file, reboot your system.

4	Restart Microsoft Windows, and try the operation again.


Couldn't replace; no replace permission for table or query 'Item'.

Error 3108

You must have Modify Data permission for the specified table or query in order to replace data in it.  To change your permission assignments, see your system administrator or the table's or query's creator.


Couldn't update; currently locked.

Error 3218

You tried to update data that is currently locked.

Possible causes:

You tried to save a query that is in use by another user.  To save your query, wait for the other user to finish or enter a different name, and then try the operation again.

You tried to use the Edit method on a record that is already open or locked.  Move to another record on the form and then try the edit operation again.


Couldn't initialize data access because file 'SYSTEM.MDA' couldn't be opened.

Error 3028

In order to insure referential integrity in databases created by Microsoft Access, Visual Basic must read the Access SYSTEM.MDA file.  Make sure the file is in  the location specified in the SystemDB entry in the [Options] section in the .INI file.


Couldn't start session.

Error 3002

You tried to initiate an operation that would require a new session, but you've reached the maximum number of sessions that can be active at one time.  Wait for other operations to finish, or stop other operations, and then try the operation again.


Couldn't use 'Item'; database already in use.

Error 3196

The specified database is currently in use by another user or session.  Wait for the other user or session to finish working with the database, and then try the operation again.


Couldn't use 'Item'; file already in use.

Error 3045

The specified file is currently in use by another user or session.  Wait for the other user or session to finish working with the file, and then try the operation again.


Database has reached maximum size.

Error 3036

To add data to this database, you must first reduce its size by deleting data.


Database 'Item' is exclusively locked.

Error 3006

You tried to use a database that is currently open for exclusive access by another user.  Wait for the other user to finish working with the database, and then try the operation again.


Date is out of range or is in an invalid format.

Error 3175

Only dates from January 1, 100, through December 31, 9999 are recognized.

Possible causes:

You entered a date that was outside the valid range.

You entered a valid date, but it wasn't in a recognized format.  Check the date to make sure you entered it correctly, and then try the operation again.


Duplicate output alias 'Item'.

Error 3062

You tried to execute an SQL statement that has more than one alias with the same name.  The following example produces this error:

SELECT [Last Name] AS Name, [First Name] AS Name FROM Employees;

Rename one or more of the aliases, and then try the operation again.

See Also

SELECT Statement (SQL)


Invalid CollatingSequence entry in [Paradox ISAM] section in INI file.

Error 3228

You have an incorrect value for the Collating Sequence intry in the .INI file..

To complete this operation

1	Exit the application.

2	Use Microsoft Windows Notepad or another text editor to change the CollatingSequence entry in the [Paradox ISAM] section in the .INI file to either Ascii or International.

3	Restart the application, and then try the operation again.


Invalid entries in [Btrieve ISAM] section in WIN.INI.

Error 3221

An entry in the [Btrieve] section in WIN.INI isn't valid.  For example, this error occurs if the /l: or /f: settings in the options entry are invalid.  Exit the application, correct any invalid entries using Microsoft Windows Notepad or another text editor, and then restart the application to try the operation again.


Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.

Error 3129

Your SQL statement couldn't be recognized because it doesn't begin with one of the specified reserved words.

See Also

DELETE Statement (SQL)

INSERT INTO Statement (SQL)

PROCEDURE Clause (SQL)

Using SQL (Structured Query Language)

SELECT Statement (SQL)

UPDATE Statement (SQL)


MS-DOS file sharing lock count exceeded.  You need to increase the number of locks installed with SHARE.EXE.

Error 3052

To load SHARE.EXE

1	Exit Microsoft Windows.

2	Using a text editor, add the following line to your AUTOEXEC.BAT file:

SHARE.EXE /L:500

If you don't have an AUTOEXEC.BAT file on your system, enter the preceding line at the command prompt before you start Microsoft Windows.  The exact number of locks you use depends on the particular applications you run and the number of files that are locked at any given time.  If other applications require file locks, you may need to specify more than 500 locks.

3	If you added SHARE.EXE to your AUTOEXEC.BAT file, reboot your system.

4	Restart Microsoft Windows, and try the operation again.


Must specify tables to delete from.

Error 3128

You tried to execute a delete query but the query doesn't specify the name of the table containing the records you want to delete.

Possible cause:

You didn't type an asterisk for each table in the ALL, DISTINCT, DISTINCTROW Predicates (SQL).  Instead, you typed field names (for example, Customers.Address instead of Customers.*).


'Item' isn't a valid parameter name.

Error 3223

This error can occur if the parameter name is longer than 64 characters, or contains invalid characters.  Correct the name, and then try the operation again.


'Item' not part of aggregate function or grouping.

Error 3122

You tried to execute a query that doesn't include the specified expression as part of an aggregate function or grouping.

Possible cause:

You didn't enter an aggregate function in the TRANSFORM

Statement (SQL).

See Also

GROUP BY Clause (SQL)

Using SQL (Structured Query Language)


Not a valid account name or password.

Error 3029

You entered an invalid account (user) name or password.

User names

User names can be from 1 to 20 characters long and can include alphabetic characters, accented characters, numbers, spaces, and symbols, with the following exceptions:

The characters "  /  \  [  ]  |  <  >  +  =  ;  ,  :  ?  *

Leading spaces

Control characters

User names are not case-sensitive.

Passwords

Passwords can be any combination of 14 or fewer characters; passwords can't contain control characters.  Passwords are case-sensitive.


Not enough space on disk.

Error 3026

You tried to perform an operation that requires more disk space than is available.  Remove unused files from your disk, and then try the operation again.


Not enough space on temporary disk.

Error 3183

You tried to perform an operation that requires more space than is available on the temporary disk.  For example, you may be trying to print a report that creates temporary files larger than the temporary disk.  Reduce the size of the temporary files by printing smaller amounts of data at one time, or increase the size of the temporary disk.

You can increase the amount of available temporary disk space in several ways:

Select a different drive for your temporary disk.

If the temporary disk is a RAM disk, increase the size of the disk.

You can also free some space by deleting data or by removing unneeded tables, queries, forms, macros, and modules from your database.

If you still need additional space, consider removing other unused files from your disk.


Operation must use an updatable query.

Error 3073

You tried to run, open, or modify a query that isn't updatable.

Possible causes:

You attempted to run a query that tried to update a field that cannot be updated.  For example, you may have created the query in such a way that you tried to update a field on the "one" side of a one-to-many relationship.

You tried to use the OpenQueryDef method on a query that is in a database opened for read-only access.

The database is read-only for one of these reasons:

You used the OpenDatabase function or Data Control, and opened the database for read-only access.

The database file has been defined as read-only in MS-DOS or your network operating system.

In a network environment, you don't have write privileges for the database file.

Close the database, resolve the read-only condition, and then reopen it for read/write access.

You must have Modify Definitions permission for the query in order to make changes.  To change your permission assignments, see your system administrator or the query's creator.


Parameter 'Item' specified where a database name is required.

Error 3217

You created a parameter query that specifies an invalid parameter type.  The following example produces this error:

PARAMETERS Param1 Text;
SELECT [Customer ID]
FROM Customers IN Param1;

Param1 is a text parameter, but the FROM Clause (SQL) requires a database parameter.

Change the parameter type from Text to Database, and then try the operation again.


Parameter 'Item' specified where a table name is required.

Error 3216

You created a parameter query that specifies an invalid parameter type.  The following example produces this error.

PARAMETERS Param1 Text;
INSERT INTO Param1
SELECT *
FROM Customers;

Param1 is a text parameter, but the INSERT INTO Statement (SQL) expects a table name.

Change the parameter type from Text to TableID, and then try the operation again.


SELECT INTO remote database tried to produce too many fields.

Error 3185

Microsoft Access databases support up to 255 fields per table, but the other database supports fewer.  A SELECT...INTO Statement (SQL) created a table with more fields than the remote database can support.  Reduce the number of columns produced by the SELECT INTO statement, and then try the operation again.


Syntax error in PROCEDURE clause.

Error 3140

You entered an SQL statement that has an invalid PROCEDURE Clause (SQL).

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in SELECT statement.

Error 3141

You entered an SQL statement that has an invalid SELECT Statement (SQL).

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in TRANSFORM statement.

Error 3143

You entered an SQL statement that has an invalid TRANSFORM Statement (SQL).

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in UPDATE statement.

Error 3144

You entered an SQL statement that has an invalid UPDATE Statement (SQL).

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in WHERE clause.

Error 3145

You entered an SQL statement that has an invalid WHERE Clause (SQL).

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Table 'Item' already exists.

Error 3010

You tried to create or rename a table with a name that already exists in this database.  Choose another name, and then try the operation again.

In a multiuser database, this error can also occur if you delete a table, another user creates a table with the same name, and then you try to Rollback the deletion of your table.  To restore your table, the other user must first delete or rename the new table.  Then, try the Rollback operation again.


Table 'Item' is exclusively locked.

Error 3008

You tried to use a table that is currently open for exclusive access by another user.  Wait for the other user to finish working with the table, and then try the operation again.


Item

Error 3261

You tried to use a table that is currently open for exclusive access by the specified user.  Wait for the other user to finish working with the table, and then try the operation again.


Too many crosstab column headers (Item).

Error 3205

You executed an SQL statement that tried to create too many columns.  The specified value is the one that produced this error.

You can reduce the number of columns by adding additional conditions to the WHERE Clause (SQL); if there is no WHERE clause, add one.


Too many fields defined.

Error 3190

You tried to perform an operation that involves more than 255 fields.  Reduce the number of fields, and then try the operation again.


Too many Memo or Long Binary fields.

Error 3054

You tried to perform a Btrieve operation that involves more Memo or Long Binary fields than is possible.  Reduce the number of Memo and Long Binary fields involved, and then try the operation again.


Undefined function 'Item' in expression.

Error 3085

You entered an SQL expression that includes a function procedure name that can't be recognized.  Make sure the function exists, or check the expression to make sure you entered the name correctly.


Update without AddNew or Edit.

Error 3020

You didn't use either the AddNew or Edit method before trying to save changes to a record.  Use AddNew or Edit, and then use Update.


Wrong data type for parameter 'Item'.

Error 3060

You tried to use an argument that has a data type that conflicts with the data type defined for this parameter.  For example, you might have tried to use a numeric argument with a parameter that expects a string expression.  Use an argument that has the correct data type, and then try the operation again.


Wrong Paradox sort sequence.

Error 3220

You tried to attach a Paradox table that was created with an international sort order that isn't the same as the one you are using.


Syntax error in LEVEL clause.

Error 3136

You entered an SQL statement that has an invalid Visual Basic SQL Reserved Words clause.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Reserved error (Item); there is no message for this error.

Error 3000

An unexpected error occurred.  The specified code identifies the conditions under which this error can occur.

See Also

Microsoft Technical Support Services


Btrieve--missing WBTRCALL.DLL.

Error 3240

You tried to perform an operation that requires the specified file.  To use data access to read and write data to a Novell Btrieve file, you must have a copy of the stand-alone Btrieve for Windows WBTRCALL.DLL file (about 52K in size).  This file must be in your \WINDOWS\SYSTEM directory.

You may already have a copy of this file on your hard drive.  To find it, at the root directory type:

dir wbtrcall.dll /s

Copy this file to your \WINDOWS\SYSTEM directory.

Important:   If you already have a copy of WBTRCALL.DLL in your \WINDOWS\SYSTEM directory, contact your system administrator before copying over it.  This file may be used by other programs on your computer.

If you don't have a copy of this file, you can purchase Btrieve for Windows from Novell Inc. by calling 800-453-1267 or by contacting your local software dealer.


Can't create a relationship between a field and itself.

Error 3206

You tried to create a relationship between a field and itself.  Choose a different field for the primary or related table, and then try the operation again.


Can't set field 'Item' in join key to Null.

Error 3100

When you join tables, the fields you join can't contain any null values.  Either select different fields or enter data in the fields, and then try the operation again.


Can't update 'Item'; field not updatable.

Error 3113

Possible causes:

The specified field is part of a Table or Dynaset that can't be updated.  For example, this error occurs if you try to update a Counter.

You executed a query that combines updatable and nonupdatable Tables, and you tried to update one of the fields in the query's resulting Dynaset.


Couldn't find field 'Item'.

Error 3018

Possible causes:

The specified field doesn't exist.

You misspelled the field name.  Check for missing underscores ( _ ) or other punctuation, and make sure you didn't enter leading spaces.

You entered an invalid field identifier.  For example, [My Table]_[My Field] instead of MyTable![My Field].


Couldn't find file 'Item'.

Error 3024

Possible causes:

The specified file doesn't exist.

You misspelled the file name.  Check for missing underscores ( _ ) or other punctuation,  and make sure you didn't enter leading spaces.

You entered an invalid file specification that contains an invalid path.  For example, you might have entered a path that doesn't exist or misspelled an element in the path specification.

The specified file is on a network drive, and that network isn't connected.  Check to make sure the network is available, and then try the operation again.


Couldn't find input table or query 'Item'.

Error 3078

Possible causes:

The specified table or query doesn't exist.

You misspelled the table or query name.  Check for missing underscores  ( _ ) or other punctuation, and make sure you didn't enter leading spaces.


Couldn't find object 'Item'.

Error 3011

Possible causes:

The specified object doesn't exist.

You misspelled the object name.  Check for missing underscores ( _ ) or other punctuation, and make sure you didn't enter leading spaces.

If you're trying to open a Btrieve table, the paths indicated in the data definition file FILE.DDF may be incorrect. Be sure your data (.DAT) files are in the correct directories.


Couldn't open table 'MSysAccounts' in SYSTEM.MDA.

Error 3173

This operation requires the SYSTEM.MDA file, which contains the security and option settings for Visual Basic database tables.

Possible causes:

The SystemDB entry in the [Options] section in the .INI file points to a network drive that isn't connected.  Check to make sure the network drive is available, and then try the operation again.

The SYSTEM.MDA file is corrupted.  If you have a backup copy of SYSTEM.MDA, copy it to the location specified in the SystemDB entry in the [Options] section in the .INI file.


Couldn't open table 'MSysGroups' in SYSTEM.MDA.

Error 3174

This operation requires the SYSTEM.MDA file, which contains the security and option settings for Visual Basic database tables.

Possible causes:

The SystemDB entry in the [Options] section in the .INI file points to a network drive that isn't connected.  Check to make sure the network drive is available, and then try the operation again.

The SYSTEM.MDA file is corrupted.  If you have a backup copy of SYSTEM.MDA, copy it to the location specified in the SystemDB entry in the [Options] section in the .INI file.


Couldn't update field.

Error 3164

Possible causes:

You tried to update a field in a record or table that is currently locked by another user.  Wait for the other user to finish working with the record or table, and then try the operation again.

You tried to change the value of a control whose Locked property is set to Yes.


Couldn't start session.  Too many sessions already active.

Error 3198

You tried to perform an operation that would have started a new session, but too many sessions are already active.  Wait for one or more sessions to finish, and then try the operation again.


'Item' isn't a valid database name.

Error 3005

The specified database name doesn't follow the standard naming conventions for file names.  Enter a new name, and then try the operation again.


'Item' is corrupted or isn't a Microsoft Access database.

Error 3049

Possible causes:

You tried to open a Btrieve, dBASE, or Paradox database or table.  Instead, attach the database or table to an existing Visual Basic database.

You tried to import or attach a Paradox database or table, and the associated .PX file couldn't be found.  Check to make sure the .PX file is in the same directory as the Paradox database or table, and then try the operation again.

If the specified database is a Visual Basic database, that database has become corrupted.  You should attempt to repair the database.  If the database can't be repaired, restore the database from a backup copy; or create a new database.


Disk or network error.

Error 3043

Visual Basic either couldn't read from or write to the disk due to an internal disk or drive failure.

Possible causes:

You tried to use a network drive, and the network is temporarily busy; or you're no longer connected to the network.  Check the network connection, and then try the operation again.

The disk or drive has failed.


Disk I/O error during read.

Error 3040

Visual Basic couldn't read the disk due to an internal disk or drive failure.

Possible causes:

You tried to read from a network drive, and the network is temporarily busy; or you're no longer connected to the network.  Check the network connection, and then try the operation again.

The disk or drive has failed.


HAVING clause (Item) without grouping or aggregation.

Error 3091

You tried to execute an SQL statement that contains a HAVING Clause (SQL) but doesn't contain a GROUP BY Clause (SQL) or an aggregate function in the SELECT Statement (SQL).  For example, this error occurs if you execute this SQL statement:

SELECT [Last Name]
FROM Employees
HAVING [Last Name] > "M";

If you don't want to perform grouping or include an aggregate function, you can apply the same condition by entering a WHERE Clause (SQL).  The next example shows how you might enter the preceding SQL statement correctly.

SELECT [Last Name]
FROM Employees
WHERE [Last Name] > "M";

See Also

Using SQL (Structured Query Language)


Invalid file format.

Error 3182

Possible causes:

The file you tried to read or attach is corrupted.  Restore a backup copy of the file to your disk, and then try the operation again.

Visual Basic can't recognize the file format.  If the file is a Btrieve, dBASE, or Paradox file, run Setup to install the installable ISAM, and then attach the file.


Not a valid table name.

Error 3177

The name you entered doesn't follow standard naming conventions.  Enter a new name, and then try the operation again.


ODBC--data type not supported on server.

Error 3235

The ODBC (Open Database Connectivity) server doesn't support the same SQL data types as Visual Basic.  The data has not been placed on the server.


ODBC--field would be too long; data truncated.

Error 3231

You tried to perform an ODBC (Open Database Connectivity) operation that would have resulted in a field that is too long.  The data has been truncated to the maximum allowable length.


ODBC--incorrect driver version.

Error 3233

You tried to perform an ODBC (Open Database Connectivity) operation that requires a different driver.  Reinstall the ODBC driver, and then try the operation again.


ODBC--remote query timeout expired.

Error 3234

The ODBC (Open Database Connectivity) server may not be properly installed, or a required network connection isn't active.  Check the network connection or contact your system administrator, and then try the operation again.


Syntax error in DELETE statement.

Error 3130

You entered an SQL statement that has an invalid DELETE Statement (SQL).  Visual Basic can't determine what action to take.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in FROM clause.

Error 3131

You entered an SQL statement that has an invalid FROM Clause (SQL).

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in GROUP BY clause.

Error 3132

You entered an SQL statement that has an invalid GROUP BY Clause (SQL).

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in HAVING clause.

Error 3133

You entered an SQL statement that has an invalid HAVING Clause (SQL).

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in INSERT statement.

Error 3134

You entered an SQL statement that has an invalid INSERT INTO Statement (SQL).

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in JOIN operation.

Error 3135

You entered an SQL statement that has an invalid join operation.  It could be an equi-join, an outer-join or a self-join.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in ORDER BY clause.

Error 3138

You entered an SQL statement that has an invalid ORDER BY Clause (SQL).

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in PARAMETER clause.

Error 3139

You entered an SQL statement that has an invalid PARAMETERS Declaration (SQL) clause.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Too many expressions in DISTINCT output.

Error 3089

You created an SQL statement that has a ALL, DISTINCT, DISTINCTROW Predicates (SQL) clause with more than ten expressions.  Remove the DISTINCT reserved word, or remove some of the fields listed in the DISTINCT clause.


Too many expressions in GROUP BY clause.

Error 3087

You created an SQL statement that has more than 10 fields listed in the GROUP BY Clause (SQL).  Remove some of the fields listed in the GROUP BY clause.


Too many expressions in ORDER BY clause.

Error 3088

You created an SQL statement that has an ORDER BY Clause (SQL) with more than ten expressions.  Remove some of the fields listed in the ORDER BY clause.


Can't evaluate expression.

Error 3071

Possible causes:

You typed an expression that has invalid syntax.  For example, an operand or operator may be missing, you may have typed an invalid character or comma, or you may have typed text without enclosing it with quotation marks ( " ).  Check the expression to make sure you typed it correctly.

You typed an expression that is too complex.  For example, a numeric expression may contain too many complicated subexpressions.  Try simplifying the expression by assigning some subexpressions to variables.


Can't have Null value in index.

Error 3058

Possible causes:

You tried to add a primary key to a field that contains a Null value.

You tried to add a new record but didn't enter a value in the column that contains the primary key.

You executed a query that tried to create a primary key field that contains a Null value.


Couldn't create; no create permission for table or query 'Item'.

Error 3111

You tried to create the specified table or query, but you don't have the required Modify Definitions permission.  To change your permission assignments, see your system administrator or the query's creator.


Couldn't create index; too many indexes already defined.

Error 3039

You can't create another index for this table.  Consider deleting an existing index to make room for the new index.


Couldn't repair this database.

Error 3056

This database is corrupted or isn't a Visual Basic database.  If it is a Visual Basic database, restore the database from a backup copy; or create a new database.


Field length is too long.

Error 3017

You tried to define or create a Text field longer than 255 characters.  Use a number between 0 and 255, and then try the operation again.


Field won't fit in record.

Error 3016

You tried to import or paste a field that is too large.  Consider breaking the field into smaller pieces and then importing or pasting the data to multiple fields.


INSERT INTO statement contains unknown field name 'Item'.

Error 3127

You tried to use INSERT INTO Statement (SQL) with the specified field name, but that field doesn't exist in the output table.  Check to make sure you've typed the name correctly, and then try the operation again.


Invalid bracketing of name 'Item'.

Error 3126

The specified name either can't have brackets around it or the brackets are mismatched.  Check your entry to make sure the brackets are properly matched, and then try the operation again.


Invalid range.

Error 3181

You attempted to import an invalid range of spreadsheet cells  This error should never occur in Visual Basic, since importing of spreadsheets is not supported.


Item1 in query expression 'Item2'.

Error 3075

The expression you typed isn't valid for the reason indicated in the message.  Check your typing to make sure you have typed field names and punctuation correctly, and then try the operation again.


Missing semicolon (;) at end of SQL statement.

Error 3137

SQL statements must include a trailing semicolon.  Add a semicolon, and then try the operation again.


'Item' isn't a valid name.

Error 3125

The specified name doesn't follow standard naming conventions or isn't a valid parameter or alias name.  Check your entry to make sure you haven't included invalid characters or punctuation and that the name isn't too long.


No permission for 'Item'.

Error 3033

You don't have the necessary permissions for the specified object.  To change your permission assignments, see your system administrator or the object's creator.


Not a valid bookmark.

Error 3159

You tried to set a bookmark to an invalid string.

This error can occur in Visual Basic if you set the Bookmark property to a string that wasn't saved from previously reading a Bookmark property.  The following code produces this error:

Sub MyFunction

Dim MyDB As Database, MySet As Dynaset

Dim Placeholder As String

Set MyDB = CurrentDB( )

Set MySet = MyDB.CreateDynaset("Employees")

Placeholder = "1"

MySet.Bookmark = Placeholder ' Not a valid bookmark.

End Sub


Not a valid file name.

Error 3055

You tried to use a file name that doesn't follow the naming conventions for your operating system.  Reenter the file name, and then try the operation again.


Not a valid password.

Error 3031

You've typed an invalid password.  Passwords can be any combination of 14 or fewer characters, except control characters.  Passwords are case-sensitive.


ORDER BY clause (Item) conflicts with DISTINCT.

Error 3093

You created an SQL statement that has a ALL, DISTINCT, DISTINCTROW Predicates (SQL) and an ORDER BY Clause (SQL) that contains a field not listed in the SELECT Statement (SQL).  Remove the DISTINCT reserved word, or remove the specified field from the ORDER BY clause.


ORDER BY clause (Item) conflicts with GROUP BY clause.

Error 3094

This error can occur when you create a select query and specify grouped fields after sorted fields that are not grouped.  For example:

You created an SQL statement with the specified field out of sequence in the ORDER BY Clause (SQL).  Move the specified field to the left of the ungrouped fields, or remove the specified field from the ORDER BY clause


Out of MS-DOS file handles.

Error 3042

Either close some files in Visual Basic or other applications, close other applications, or increase the number of available MS-DOS file handles.

To increase the number of file handles

1	Edit your CONFIG.SYS file using Microsoft Windows Notepad or another text editor.  The CONFIG.SYS file is usually located in the root directory of your boot drive.  If you don't have a CONFIG.SYS file on your system, you must create one that contains the line listed in step 2.

2	Look for the line that reads FILES = x, where x is some number.  Increase the number specified by the FILES command; the exact number of handles you enter depends on the particular applications you run and the number of files that are open at any given time.  If other applications open multiple files, you may need to specify more file handles.

As you increase the number of file handles, remember that each handle consumes more memory.  For additional information, refer to your operating system manual.

3	Exit Microsoft Windows.

4	Reboot your system, and then try the operation again.


'Item' isn't a valid path.

Error 3044

Possible causes:

The specified path doesn't exist.  Check your entry to make sure it is spelled correctly.

The specified path points to a network drive that isn't connected.  Check to make sure the network is available.


Resultant table may not have more than one Counter field.

Error 3090

You tried to execute a query that would result in a table with more than one field that has a Counter data type.  Change the query to include only one Counter field.


Table isn't open.

Error 3160

You tried to perform an operation on a table that hasn't been opened.  Open the table, and then try the operation again.


Btrieve--data dictionary is corrupted.

Error 3224

Restore a backup copy of the DDF file, and then try the operation again.


Can't use '*' in crosstab query.

Error 3123

You tried to execute a query that groups or totals fields selected with an asterisk ( * ).  Choose specific fields, and then try the operation again.


Invalid Century entry in [dBASE ISAM] section in INI file.

Error 3227

To complete this operation

1	Exit Visual Basic.

2	Using Microsoft Windows Notepad or another text editor, correct the Century entry in the [dBASE ISAM] section in the .INI file.

3	Restart Visual Basic, and then try the operation again.


Invalid Date entry in [dBASE ISAM] section in INI file.

Error 3213

To complete this operation

1	Exit Visual Basic.

2	Using Microsoft Windows Notepad or another text editor, correct the Date entry in the [dBASE ISAM] section in the .INI file.

3	Restart Visual Basic, and then try the operation again.


Invalid Deleted entry in [dBASE ISAM] section in INI file.

Error 3208

To complete this operation

1	Exit Visual Basic.

2	Using Microsoft Windows Notepad or another text editor, correct the Deleted entry in the [dBASE ISAM] section in the .INI file.

3	Restart Visual Basic, and then try the operation again.


Invalid Mark entry in [dBASE ISAM] section in INI file.

Error 3214

To complete this operation

1	Exit Visual Basic.

2	Using Microsoft Windows Notepad or another text editor, correct the Mark entry in the [dBASE ISAM] section in the .INI file.

3	Restart Visual Basic, and then try the operation again.


Invalid Stats entry in [dBASE ISAM] section in INI file.

Error 3209

To complete this operation

1	Exit Visual Basic.

2	Using Microsoft Windows Notepad or another text editor, correct the Stats entry in the [dBASE ISAM] section in the .INI file.

3	Restart Visual Basic, and then try the operation again.


Joined table 'Item' not listed in FROM clause.

Error 3080

|Add the specified table name to the query, and then try the operation again.

See Also

FROM Clause (SQL)


Missing destination field name in SELECT INTO statement (Item).

Error 3105

Enter a destination field name in the specified statement, and then try the operation again.

See Also

SELECT...INTO Statement (SQL)


Missing destination field name in UPDATE statement (Item).

Error 3106

Enter a destination field name in the specified statement, and then try the operation again.

See Also

UPDATE Statement (SQL)


Item in criteria expression.

Error 3076

The expression you entered isn't valid for the reason indicated in the message.  Check your typing to make sure you entered field names and punctuation correctly, and then try the operation again.


No current record.

Error 3021

This error occurs following the unsuccessful application of one of the FindFirst, FindLast, FindNext, FindPrevious Methods or the Seek Method, or when the underlying recordset contains no records.  Move to or select a record, and then try the operation again.


Not a valid alias name.

Error 3068

The alias you entered doesn't follow standard naming conventions.  Enter a new name, and then try the operation again.


Null is invalid.

Error 3162

You tried to assign the Null value to a variable that isn't a Variant data type.  Use the Dim statement to declare the variable as a Variant, and then try the operation again.


Object 'Item' already exists.

Error 3012

You tried to create an object with the name that already exists in this database.  Choose a different name, and then try the operation again.


Operation invalid without a current index.

Error 3019

Set the index, and then try the operation again.


Operation not supported on attached tables.

Error 3057

Import the table, and then try the operation again.


Operation not supported on Paradox table with no primary key.

Error 3207

Run the application that created the table, and add a primary key.  Then, try the operation again.


Query input must contain at least one table or query.

Error 3067

This error occurs if you don't select a table name when you create a query.  Select at least one table or query.


Query must have at least one output field.

Error 3066

This error occurs if you don't specify any output field names when you create a query.  Select at least one output field.


Record is deleted.

Error 3167

You referred to a record that you deleted or that another user in a multiuser environment deleted.  Move to another record, and then try the operation again.


Ambiguous field reference 'Item'.

Error 3079

The specified field reference could refer to more than one table listed in the FROM Clause (SQL) of your SQL statement.  In the following example, the Order ID field exists in both the Orders and Order Details tables.  Because the statement doesn't specify which table Order ID belongs to, it produces this error.

SELECT [Order ID]
FROM Orders, [Order Details];

To complete this operation, fully qualify the field reference by adding a table name.  For example:

SELECT Orders.[Order ID]
FROM Orders, [Order Details];

See Also

SELECT Statement (SQL)


Can't import password-protected spreadsheet.

Error 3244

Return to the application that was used to save the spreadsheet, save the spreadsheet again without a password, and then try to import the spreadsheet again.


Can't use HAVING clause in TRANSFORM statement.

Error 3092

If you want to specify selection criteria, use a WHERE Clause (SQL).


Circular reference caused by 'Item'.

Error 3102

You tried to execute a query that depends on itself for data.  For example, this error occurs if you execute either of the following queries:

Query1

SELECT * FROM Employees, Query2;

Query2

SELECT * FROM Query1;

Redesign the queries to eliminate the dependency.


Couldn't execute query; couldn't find linked table.

Error 3184

Possible causes:

The attached table no longer exists, or has been renamed or moved.  Reattach the table and then try to execute the query again.

The attached table is on a network drive and the network isn't connected.  Check to make sure the network is available, and then try to execute the query again.

This error should not occur in Visual Basic, because importing tables is not supported.


Couldn't parse field names from first row of import table.

Error 3245

The first row of data contains invalid field names, such as quoted and unquoted strings in the same field name.  In the following example, the third and fourth field names are unparsable:

"Name", Date, "ID " Number, Phone" Number"

The first two fields are valid, but the third and fourth aren't because they contain non-space characters outside of the quotation marks.

Check the import table for properly matched quotation marks, then try the import operation again.

This error should not occur in Visual Basic, because importing tables is not supported.


Database already exists.

Error 3204

You tried to create or rename a database using a name that already exists.  Enter a different name, and then try the operation again.


Encountered unexpected end of file.

Error 3179

You tried to import a file that contains an end-of-file marker in an unexpected position.

Possible causes:

The import file is corrupted.  Restore a backup copy of the import file, and then try the operation again.

The import/export specifications you're using don't match the data in the import file.  Edit the import/export specifications, and then try the operation again.

This error should not occur in Visual Basic, because importing tables is not supported.


Invalid NetworkAccess entry in INI file.

Error 3248

To complete this operation

1	Exit the application.

2	Using Microsoft Windows Notepad or another text editor, correct the NetworkAccess entry in your .INI file.  The entry must be either ON or OFF.

Depending on which installable ISAM you're trying to use, the invalid entry is in the [Btrieve], [dBASE ISAM], or [Paradox ISAM] section.

3	Restart your application, and then try the operation again.


Invalid PageTimeout entry in INI file.

Error 3249

To complete this operation

1	Exit the application.

2	Using Microsoft Windows Notepad or another text editor, correct the NetworkAccess entry in your .INI file.  The entry must be either ON or OFF.

Depending on which installable ISAM you're trying to use, the invalid entry is in the [Btrieve], [dBASE ISAM], or [Paradox ISAM] section.

3	Restart your application, and then try the operation again.


None of the import field names match fields in the appended table.

Error 3243

At least one field name in the import table and the appended table must match.  This error should not occur in Visual Basic, because importing tables is not supported.


ODBC--call failed.

Error 3146

Using ODBC (Open Database Connectivity), you tried to perform an operation on data in an SQL database.  This error may occur when the SQL database is on a network drive and the network isn't connected.  Check to make sure the network is available, and then try the operation again.


ODBC--connection failed.

Error 3148

Using ODBC (Open Database Connectivity), the connection to the SQL database server couldn't be made.  If the SQL database is on a network drive, check to make sure the network is available, and then try the operation again.


ODBC--connection to 'Item' failed.

Error 3151

Using ODBC (Open Database Connectivity), the connection to the specified SQL database or table couldn't be made.  If the SQL database is on a network drive, check to make sure the network is available, and then try the operation again.


ODBC--couldn't create table.

Error 3232

You tried to export a table to an SQL database and the table couldn't be created.  This error can occur if the SQL database is read-only, or you don't have permission to create a table in that database.  Resolve the read-only condition, or see your system administrator or the person who created the database to obtain the necessary permissions.


ODBC--couldn't find DLL 'Item'.

Error 3154

Using ODBC, you tried to perform an operation that requires the specified DLL.

Possible causes:

The DLL file is on a network drive and the network isn't connected.  Check to make sure the network is available, and then try the operation again.

The DLL file wasn't installed properly; reinstall the ODBC driver, and then try the operation again.


ODBC--data buffer overflow.

Error 3147

Using ODBC (Open Database Connectivity), you tried to perform an operation that would have resulted in a record larger than the SQL database can support.  Not including Memo and Long Binary fields, a record can't be larger than approximately 2 kilobytes.  Consider breaking the data into smaller records.


ODBC--data out of range.

Error 3238

Using ODBC (Open Database Connectivity), you tried to read from or write to an SQL database, and the data isn't within the prescribed limits.


ODBC--delete failed.

Error 3156

Using ODBC (Open Database Connectivity), you tried to delete data from an SQL database and that deletion couldn't be completed.

Possible causes:

The deletion would have caused a rule violation and thus couldn't be completed.

The SQL database is read-only, or you don't have permission to delete data in that database.  Resolve the read-only condition, or see your system administrator or the person who created the database to obtain the necessary permissions.

The SQL database is on a network drive and the network isn't connected.  Check to make sure the network is available, and then try the operation again.


ODBC--encountered unexpected Null value.

Error 3236

Using ODBC (Open Database Connectivity), you tried to read data from an SQL database, and that data contains a Null value in an unexpected position.

This error can occur if the data is corrupted.  Restore a backup copy of the SQL database or table, and then try the operation again.


ODBC--incorrect DLL.

Error 3149

The DLL file has become corrupted or isn't the correct one for this SQL database.  Reinstall the ODBC (Open Database Connectivity) driver, and then try the operation again.


ODBC--incorrect driver version 'Item1'; expected version 'Item2'.

Error 3152

The installed driver has become corrupted or isn't  the correct one for this SQL database.  Reinstall the ODBC (Open Database Connectivity) driver, and then try the operation again.


ODBC--incorrect server version 'Item1'; expected version 'Item2'.

Error 3153

The installed driver has become corrupted or isn't  the correct one for this SQL database.  Reinstall the ODBC (Open Database Connectivity) driver, and then try the operation again.


ODBC--insert failed.

Error 3155

Using ODBC (Open Database Connectivity), you tried to insert data into an SQL database and that insertion couldn't be completed.

Possible causes:

The insertion would have caused a rule violation and thus couldn't be completed.

The SQL database is read-only, or you don't have permission to insert data in that database.  Resolve the read-only condition, or see your system administrator or the person who created the database to obtain the necessary permissions.

The SQL database is on a network drive and the network isn't connected.  Check to make sure the network is available, and then try the operation again.


ODBC--linked table definition has changed.

Error 3247

The definition or structure of an attached table changed since you created the link.  Delete the link, and then reattach the table.

This error should not occur in Visual Basic, because importing/attaching tables is not supported.


ODBC--unexpected type.

Error 3237

Using ODBC (Open Database Connectivity), you tried to read from or write to an SQL database or table, and the field data types aren't compatible.  This error can occur if the data types don't match or if the data has become corrupted.


ODBC--update failed.

Error 3157

Using ODBC (Open Database Connectivity), you tried to update data in an SQL database and that update couldn't be completed.

Possible causes:

The update would have caused a rule violation and thus couldn't be completed.

The SQL database is read-only, or you don't have permission to update data in that database.  Resolve the read-only condition, or see your system administrator or the person who created the database to obtain the necessary permissions.

The SQL database is on a network drive and the network isn't connected.  Check to make sure the network is available, and then try the operation again.


Operation not supported in transactions.

Error 3246

You tried to perform an operation that isn't valid within a transaction.  A transaction can be one you create using a BeginTrans, Commit Trans, Rollback Statements, or an internal transaction created by Microsoft Access, such as when you delete multiple records in a single operation.


Query can't contain a Database parameter.

Error 3222

Change the parameter field data type for this parameter query to a valid field data type and then try the operation again.

See Also

PARAMETERS Declaration (SQL)


Too many active users.

Error 3239

In a multiuser environment, Visual Basic databases support up to 255 concurrent users.  Wait for one or more users to stop using the system, and then try the operation again.


Btrieve--can't change field.

Error 3229

You tried to update a field in a Btrieve table that is part of a nonmodifiable index.  Use Novell Xtrieve or another program to change the nonmodifiable attribute of the index, and then try the operation again.


Btrieve--out of resources.

Error 3241

While working with a Btrieve file, Visual Basic ran out of resources.  Exit Visual Basic and use Microsoft Windows Notepad or another text editor to increase one or more of the settings in the Options entry in the [Btrieve] section in your WIN.INI file.  Then restart Visual Basic and try the operation again.

Visual Basic requires the following minimum values:

[Btrieve]

Options=/m:38 /p:4096 /b:16 /f:4 /l:8 /n:4 /t:<pathname>

For more information, refer to your Btrieve documentation.


ODBC--Can't change connect string parameter.

Error 3255

Using ODBC (Open Database Connectivity), you tried to change a connect string parameter other than the Login ID or Password.  If you need to change one of the other parameters, you must delete and then reattach the table.


Can't delete account.

Error 3032

You tried to delete the only user account in the group Admins.  The group Admins must have at least one user account.  If you want to delete this user account, create a new account and add that account to the group Admins, or add an existing account to the group Admins, and then delete the account.


ODBC--Can't lock all records.

Error 3254

Using ODBC (Open Database Connectivity), you tried to lock all of the records in an SQL database.  This error can occur if you base a form on an SQL database and then set the form's RecordLocks property to All Records.  Set the RecordLocks property to either No Locks or Edited Record, and then try the operation again.


Can't add or change record.  Referential integrity rules require a related record in table 'Item'.

Error 3201

You tried to perform an operation that would have violated referential integrity rules for related tables.  For example, this error occurs if you try to change or insert a record in the "many" table in a one-to-many relationship, and that record doesn't have a related record in the table on the "one" side.

If you want to add or change the record, first add a record to the "one" table that contains the same value for the matching field.


Can't delete or change record. Since related records exist in table 'Item', referential integrity rules would be violated.

Error 3200

You tried to perform an operation that would have violated referential integrity rules for related tables.  For example, this error occurs if you try to delete or change a record in the "one" table in a one-to-many relationship when there are related records in the "many" table.

If you want to delete or change the record, first delete the related records from the "many" table.


Can't use internal report query.

Error 3083

You tried to use an SQL statement that includes an explicit reference to a disallowed internal report query.  Remove the invalid reference and then try the operation again.


Connect string too long.

Error 3210

The connect string in the IN Clause (SQL) of an SQL statement can't be longer than 255 characters.  Correct your entry, and then try the operation again.


Couldn't decrypt file.

Error 3161

You tried to access an encrypted Btrieve or Paradox table, but the password you provided is not correct.  Try the operation again by entering the correct password.


Couldn't find net path or user name.

Error 3171

One or more entries in the [Paradox ISAM] section in your .INI file is invalid.  Using Microsoft Windows Notepad or another text editor, correct the invalid entries, and then try the operation again.


Couldn't find reference.

Error 3199

You entered a file, table, or field reference that couldn't be found.  Check the spelling and punctuation to make sure you entered the reference correctly, and then try the operation again.


Couldn't open file 'Item'.

Error 3176

The specified text or spreadsheet file couldn't be opened.  The specified file specification may be invalid, another user may be accessing the file, or you may not have read privileges for the file.  Wait for the other user to finish using the file and then try the operation again, or contact your system administrator or network administrator.


Couldn't open .INF file.

Error 3165

You tried to attach a dBASE table, but Microsoft Visual Basic couldn't open or create the associated.INF file that contains index information about that table.

Possible causes:

There isn't enough disk space available to create the .INF file.

In a network environment, you don't have write privileges for the network drive.


Couldn't rename installable ISAM file.

Error 3013

You tried to rename a Btrieve, dBASE, or Paradox table, but the file that contains that table couldn't be renamed.

Possible causes:

The file has been defined as read-only in the operating system or by your network.

In a network environment, you don't have write privileges for the file.


Couldn't write to file 'Item'.

Error 3180

You tried to export data to the specified text or spreadsheet file, but the file couldn't be modified.

Possible causes:

Another user is currently accessing the file.  Wait for the other user to finish using the file and then try the operation again.

The file has been defined as read-only in the operating system or by your network.  Resolve the read-only condition and then try the operation again.

In a network environment, you don't have write privileges for the file.

You may need to contact your system administrator or network administrator.


Data has changed; operation stopped.

Error 3197

This error can occur in a multiuser environment.

Another user has changed the data you are trying to update.  This error can occur in Visual Basic when multiple users open a table or create a dynaset and use optimistic locking.  Between the time you used the Edit Method method and the Update Method, another user changed the same data.

To overwrite the other user's changes with your own, execute the Update method again.


Encountered record locking deadlock while performing Btrieve operation.

Error 3225

You tried to lock a record during an update, insert, or delete operation on an attached Btrieve table, and another user is also trying to lock the same record.  Cancel the operation, wait for the other user to finish, and then try the operation again.


Errors encountered while using the Btrieve DLL.

Error 3226

An unexpected error occurred when you tried to access data in an attached Btrieve table.  Try the operation again, or contact your system administrator or network administrator.


Illegal reentrancy during query execution.

Error 3252

This error can occur if you execute a query that includes a user-defined function in its output and then create a form based on that query.


Illegal type in expression.

Error 3169

You tried to execute an SQL statement that contains a field that has an invalid field data type.

Possible causes:

You included a Memo or Long Binary field in an expression where it is not allowed.

You included a numeric aggregate function, such as Sum or StDev, that tried to perform a calculation on a Text field.  Choose a different aggregate function.


Index file not found.

Error 3256

You tried to access a dBASE table, but one of the indexes listed in the table's associated .INF file couldn't be found.  The index may have been renamed, moved, or deleted.  Either reattach the table, or use Microsoft Windows Notepad or another text editor to update the .INF file.


Invalid .INF file.

Error 3168

You tried to access a dBASE table, but its associated .INF file is invalid or has become corrupted.  Reattach the table, making sure you specify the correct indexes.


Join is broken by value(s) in fields 'Item'.

Error 3101

In a one-to-many relationship, you entered data on the "many" side that doesn't exist on the "one" side.  For example, this error occurs if you join the Customers table and the Orders table on the Customer ID field, and then add an order using a Customer ID that doesn't exist in the Customers table.


JOIN operation 'Item' refers to a non-joined table.

Error 3082

You tried to execute an SQL statement that contains an invalid join.  This error occurs when you try to create a join on a field that isn't in one of the joined tables.  The following example produces this error.

SELECT Authors.[First Name], Titles.[ISBN]
FROM Authors, Titles, AuthorTitles,
Authors INNER JOIN Titles ON Authors.ID = AuthorTitles.ISBN;

The error occurs because the join involves the Authors and Titles tables, but the joined fields are in the Authors and AuthorTitles tables.

See Also

INNER JOIN Operation (SQL)

LEFT JOIN, RIGHT JOIN Operations (SQL)


Missing memo file.

Error 3166

You tried to access a dBASE (.DBF) file, but the file's associated memo (.DBT) file couldn't be found.  Check to make sure the .DBT file is in the same directory as the .DBF file, and then try the operation again.


Operation canceled by user.

Error 3059

You stopped the operation before its normal completion.  Some data changes may not have been saved.


Incompatible database version.

Error 3041

You tried to access a database that is in an outdated format.  Compact the database and then try the operation again.


Out-of-date Paradox lock file.

Error 3230

You tried to use a Paradox table, but the table's associated lock (.LCK) file is outdated.  Delete the .LCK file and then try the operation again.


Record is too large.

Error 3047

You defined a table with records larger than Visual Basic can support.  This error occurs when you enter data into such a record [image] not when you define the table structure.  Redefine the table by making some fields shorter or by removing unneeded fields.


Syntax error in WITH OWNERACCESS OPTION declaration.

Error 3257

Possible causes:

The WITH OWNERACCESS OPTION Declaration (SQL) is incomplete or includes a space between OWNER and ACCESS.

The declaration appears in an unexpected and disallowed position in the SQL statement.  For example:

SELECT * WITH OWNERACCESS OPTION FROM [My Table];

The WITH OWNERACCESS OPTION declaration should appear at the end of the SQL statement, usually after the ORDER BY Clause (SQL), if present:

SELECT * FROM [My Table] WITH OWNERACCESS OPTION;


Too many Btrieve tasks.

Error 3215

This error occurs when you run too many applications that use the Btrieve driver.  In a multiuser environment, this error can occur when too many users access the same server.  Contact your system administrator or network administrator.


Too many client tasks.

Error 3053

You have too many copies of Visual Basic or Visual Basic applications running at the same time.  Close one or more instances.


Creating a Database

See Also	Example

A database file can contain a number of objects, and some of those objects can contain other objects or collections of objects.  Before you create a database, you should have a good idea about what information will be stored in your database and what kinds of tables, fields, and indexes you'll need to store and track that information.

Data Manager

The easiest way to create or modify the structure of your database is to use Microsoft Access or the Data Manager, which you can open by choosing the Data Manager command on the Window menu.

Professional Edition

If you have the Professional Edition, you can write code to create and modify the structure of a database.  After you have planned the structure of your tables, the basic steps to create a database are:

1.	Dim a variable for the Database object you want to create.

2.	Use CreateDatabase to create an empty database, and Set to assign it to your Database object variable.

3.	Create new TableDef objects for each table and add them to the TableDefs collection of the Database with the Append method.  Creating a table involves the following steps:

a.	Create new TableDef objects.  For each one, set the Name property to the name you want for the table.

b.	Create new Field objects for each table.  For each Field, set the following properties:
Name
Type
Size (optional)
Attributes (optional)

c.	Add each Field to the Fields collection of a TableDef with the Append method.  Repeat steps a [image] c for each Field in a TableDef.

d.	Create one or more new Index objects for each table.  For each Index, set the following properties:
Name
Fields
Primary (optional, and for only one Index per table)
Unique (optional)

e.	Add each Index object to the Indexes collection of the TableDef with the Append method.  A table can have none or several indexes.

f.	Add the TableDef object to the Database with the Append method.  This is the step that actually creates the object in the database file.


vbhowCreateDatabaseSee
See Also

Help:

CreateDatabase Function (Professional Edition Only)

Data Access

Data Control

Dim Statement

Set Statement

Data Access Guide:

Chapter 2, "Creating a Database"


vbhowCreateDatabaseEx
Creating a Database Example

This example creates a database with two tables, each containing three fields and two indexes.

Sub CreateNewDB ()
    Dim Db As Database, Dbname As String
    Dbname = "C:\VB\MYDB.MDB"
    Set Db = CreateDatabase(Dbname, DB_LANG_GENERAL)
    NewPeopleTable Db
    NewAddressTable Db
    MsgBox "Your database, " & UCase(Dbname) & ", is ready."
End Sub
'
'
Sub NewAddressTable (D As Database)
    Dim Td As New TableDef, Fld() As New Field
    Dim Idx() As New Index, I As Integer

    ReDim Fld(1 To 5), Idx(1 To 2)

    Td.Name = "Addresses"   ' Set the table name.
    ' Create Fields.
    Fld(1).Attributes = DB_AUTOINCRFIELD    ' Counter field.
    For I = 1 To 5  ' Set properties for fields.
        Fld(I).Name = Choose(I, "ANum", "Addr1", "Addr2", "CityState", "ZIP")
        Fld(I).Type = Choose(I, DB_LONG, DB_TEXT, DB_TEXT, DB_TEXT, DB_TEXT)
        Fld(I).Size = Choose(I, 4, 30, 30, 30, 10)
        Td.Fields.Append Fld(I)
    Next I

    ' Create Indexes.
    Idx(1).Name = "PrimaryKey"
    Idx(1).Fields = "ANum"
    Idx(1).Primary = True
    Idx(1).Unique = True
    Idx(2).Name = "City"
    Idx(2).Fields = "CityState"
    For I = 1 To 2
        Td.Indexes.Append Idx(I)
    Next I

    ' Create Table.
    D.TableDefs.Append Td
End Sub
'
'
Sub NewPeopleTable (D As Database)
    Dim Td As New TableDef, Fld() As New Field
    Dim Idx() As New Index, I As Integer

    ReDim Fld(1 To 5), Idx(1 To 2)

    Td.Name = "People"  ' Set the table name.
    ' Create Fields.
    For I = 1 To 4  ' Set properties for fields.
        Fld(I).Name = Choose(I, "PNum", "LName", "FName", "Phone")
        Fld(I).Type = Choose(I, DB_LONG, DB_TEXT, DB_TEXT, DB_TEXT)
        Fld(I).Size = Choose(I, 4, 30, 30, 15)
    Next I
    Fld(1).Attributes = DB_AUTOINCRFIELD    ' Counter field.
    For I = 1 To 4
        Td.Fields.Append Fld(I)
    Next I

    ' Create Indexes.
    Idx(1).Name = "PrimaryKey"
    Idx(1).Fields = "PNum"
    Idx(1).Primary = True
    Idx(1).Unique = True
    Idx(2).Name = "Full Name"
    Idx(2).Fields = "LName,FName"
    For I = 1 To 2
        Td.Indexes.Append Idx(I)
    Next I

    ' Create Table.
    D.TableDefs.Append Td
End Sub


Querying a Database

See Also

To work with the data in a database, you can use queries to manipulate or extract data.  A query either asks the database for a set of records matching specified criteria (a SELECT query), or tells the database to perform a specified operation on a set of records that match specified criteria (an action query).

You can use a data control's RecordSource property to query the database, or you can use one of the Find methods with a data control's Recordset property.

Using an SQL query with a data control

1.	Design your query so the database returns only the records you want.

2.	Enter the SQL statement in the RecordSource property.  You can do this at design time or run time.  At run time, you can use this code:

Data1.RecordSource = "SELECT * FROM Publishers WHERE State = 'NY'"

3.	At run time, use the Refresh method to recreate the underlying Dynaset in the data control:

Data1.Recordset.Refresh

Using an existing QueryDef in the RecordSource property

1.	Enter the name of the QueryDef in the RecordSource property.  You can do this at design time or run time.  At run time, you can use this code:

Data1.RecordSource = "Full Name"

2.	At run time, use the Refresh method to recreate the underlying Dynaset in the data control:

Data1.Recordset.Refresh

Professional Edition

You can also use SQL statements or QueryDef objects with the Professional Edition.

Creating a new QueryDef object

You can set the SQL property of a QueryDef in either of two situations:

1.	Design your query so the database returns only the records you want.

2.	Create a complete QueryDef in code:

Dim MyQuery As QueryDef, Db As Database, MySQL As String
Set Db = OpenDatabase("C:\VB\BIBLIO.MDB")
MySQL = "SELECT Author FROM Authors WHERE Author LIKE 'A*'"
Set MyQuery = Db.CreateQueryDef("A Names", MySQL)

Or you can create a blank QueryDef and set the SQL property later.

1.	Design your query so the database returns only the records you want.

2.	Create a QueryDef in code:

Dim MyQuery As QueryDef, Db As Database, Dn As Dynaset
Set Db = OpenDatabase("C:\VB\BIBLIO.MDB")
Set MyQuery = Db.CreateQueryDef("A Names")

3.	Set the SQL property later:

MyQuery.SQL = "SELECT Author FROM Authors WHERE Left(Author, 1) = 'A'"

4.	Now you can use the QueryDef to create a Dynaset with either of these lines of code:

Set Dn = MyQuery.CreateDynaset()
Set Dn = Db.CreateDynaset("A Names")

You can also create parameter queries that allow you to modify parts of a query at run time without changing the query saved in the database.

Creating a parameter QueryDef object

1.	Design your parameter query so the database returns only the records you want.

2.	Create a parameter QueryDef in code:

Dim MyQuery As QueryDef, Db As Database
Dim MySQL As String, Dn As Dynaset
Set Db = OpenDatabase("C:\VB\BIBLIO.MDB")
MySQL = "PARAMETERS Param Text;"
MySQL = MySQL & " SELECT Author FROM Authors"
MySQL = MySQL & " WHERE Author = [MyParam]"
Set MyQuery = Db.CreateQueryDef("A Name", MySQL)

2.	You must set the parameter before you use the query:

MyQuery!MyParam = "Jones, Arthur"
Set Dn = MyQuery.CreateDynaset()


See Also

Help:

CreateQueryDef Method (Professional Edition Only)

Data Access

Data Control

Name Property

OpenQueryDef Method (Professional Edition Only)

QueryDef Object

Recordset Property

SQL Property (Professional Edition Only)

Using SQL (Structured Query Language)

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


Adding and Deleting Controls at Run Time

See Also	Example

Because control arrays in Visual Basic are dynamic, you can add or delete controls in a control array at run time.  However, you must first create a control array containing at least one control at design time, and then you can write code (using the Load and Unload statements) to dynamically add or delete controls from the array at run time.

To add or delete controls in a control array at run time

1.	Create a control array.

If you create a control array only so you can add controls at run time, you can accomplish this by setting the Index property on a single control at design time.

2.	Open the Code window by double-clicking a control in the control array.

3.	Go to the event or procedure where you want to load or unload members of the control array and write the appropriate code.

Note	At run time, you cannot remove controls that were created at design time.


procDynamicControlArraySee
See Also

Help:

Creating a Menu Bar

Creating a Menu Control Array

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


procDynamicControlArrayX
Adding and Deleting Controls at Run Time Example

To try this example, paste the code into the Declarations section of a form containing one option button, two command buttons, and a large picture box.  Set the Index property for the option button to 0 to create a control array.  Set the Caption property to "Add" for one command button and "Delete" for the other.  Then press F5.  Each time an option button is clicked, the BackColor property of the picture box is reset.  Clicking a command button causes an option button to be added or deleted depending on which one is chosen.

Dim MaxId	' Declare variable.
Sub Option1_Click (Index As Integer)
Picture1.BackColor = QBColor(Index + 1)
End Sub

Sub Command1_Click ()
If MaxId >= 9 Then Exit Sub	' No more than 10 buttons.
MaxId = MaxId + 1	' Increment button count.
Load Option1(MaxId)	' Create new button.
Option1(0).SetFocus	' Reset button selection.
' Set new button under previous button.
Option1(MaxId).Top = Option1(MaxId - 1).Top + 360
Option1(MaxId).Visible = True	' Display new button.
End Sub

Sub Command2_Click ()
If MaxId = 0 Then Exit Sub	' Keep first button.
Unload Option1(MaxId)	' Delete last button.
MaxId = MaxId - 1	' Decrement button count.
Option1(0).SetFocus	' Reset button selection.
End Sub


Calling Windows API Functions

See Also

Information on the Microsoft Windows Application Programming Interface (API) is available in two Help files located in the WINAPI subdirectory of your Visual Basic directory.  The WIN31API.HLP file contains function declarations, Type declarations, and the values for global constants used in the functions for Visual Basic programs.  The WIN31WH.HLP file documents each function in terms of the C programming language.  This is the same Help file included in the Microsoft Windows Software Development Kit (SDK).

To open a WinAPI Help file from Help

1.	From the File menu in Help, choose Open.

2.	Select the WINAPI directory.

3.	Double-click a file to open it.

If you have installed the Professional Edition, you can click the file names:

WIN31API.HLP and WIN31WH.HLP.

To use a Windows API function with the Professional Edition

1.	Select the function you want from the information in WIN31WH.HLP, which gives a description of the function's purpose and requirements (in terms of the C programming language, not Basic).  For example, a useful function is GetPrivateProfileInt, which reads a specific .INI file and returns a number from a specified setting.  Be sure to find whether the function requires a STRUCT (or structure) requiring a Type declaration in Visual Basic.

2.	In WIN31API.HLP, find the desired function, such as GetPrivateProfileInt, in the Declare Statements list and click it.

3.	Click the Copy button and select the entire declaration text.  Click the Copy button, then the Close button.

4.	Paste the declaration text into the Declarations section of a module.

5.	If your function requires a Type declaration or any constant declarations, go back to WIN31API.HLP and click the Contents button, then copy the needed Type declaration and constant declarations.

For example, you can use this code to get the keyboard type from your SYSTEM.INI file:

' The Declarations section of your module:
Declare Function GetPrivateProfileInt Lib "Kernel" (ByVal lpAppName As String, ByVal lpKeyName As String, ByVal nDefault As Integer, ByVal lpFileName As String) As Integer

Sub Form_Load ()
Dim KeyboardType As Integer
KeyboardType = GetPrivateProfileInt("Keyboard", "type", 2, "C:\WINDOWS\SYSTEM.INI")
MsgBox "Your keyboard type is "; KeyboardType
End Sub

Warning   Windows functions can require long lines of code and very long declaration statements.  You must be sure you have the entire declaration or function call on one line.  You must also be very careful to provide arguments of the correct data type.  The wrong data type may cause a General Protection Fault at run time.


vbprocWinAPISee
See Also

Call Statement

Declare Statement


Loading Constants from CONSTANT.TXT or DATACONS.TXT

See Also

Two files included with Visual Basic, CONSTANT.TXT and DATACONS.TXT, provide many symbolic constants you can use in your code.  For example, to set the background color of a form to the same color as the face of command buttons, you can either set a form's BackColor property to &H800000F, or you can use the symbolic constant BUTTON_FACE supplied in CONSTANT.TXT.  Using symbolic constants in your code makes it more readable, and you may find it easier to remember the symbolic constant than the specific value while entering code.  The constants are declared as global so they must be loaded into a code module, not a form.  To limit the scope of the constants to a form or procedure, change Global to Const in the declaration and paste them into the Declaration section of a form or procedure.

File	Contains

CONSTANT.TXT	Constants used for general programming and for Visual Basic controls.

DATACONS.TXT	Constants supporting data access in Visual Basic.

To load CONSTANT.TXT or DATACONS.TXT into a code module

1.	In the development environment, choose the New Module command from the File menu.  This adds an empty code module to your project.

2.	Make sure the module is the active window, and then choose the Load Text command from the File menu.

3.	Select one of the files containing constants and choose the Replace button.  If you want to add a file to a module where you already have other declarations, choose the Merge button.


See Also

Const Statement

Entering Declarations in Code

Global Statement


Binding a Control to a Data Control

See Also

A data control opens a database and creates a Dynaset object containing data from the database.  To see this data in controls on your form, you must bind those controls to the data control.  A control is bound to a specific field in the Dynaset represented by the Recordset property of a data control.  Controls can be bound to the data control with the DataSource property only at design time, but can be bound to a field at run time with the DataField property.  You can bind the check box, image, label, picture, and text box controls.

To bind a text box to a data control at design time

1.	On your form, select a control you want to bind to a data control.

2.	In the Properties window, select the DataSource property and click the (...) button next to the Settings list box to see a list of the data controls on the form.  Select the data control you want.

3.	Select the DataField property, and click the (...) button next to the Settings list box to see a list of the available fields in the Recordset property of the data control.  (If you haven't yet set the RecordSource property of the data control, this list will be empty.)  Select the field you want.

To bind a text box to a data control in code

1.	You must set the DataSource property of the text box to the name of the data control (for example, "Data1") at design time.

2.	Set the DatabaseName and RecordSource properties of the data control.

Data1.DatabaseName = "C:\VB\BIBLIO.MDB"	' Set the database.
Data1.RecordSource = "Publishers"	' Set the table or query.

3.	Set the text box's DataField property to the name of the field in the control's Recordset property.

Text1.DataField = "State"	' Bind to State field.


vbhowBindControlSee
See Also

Help:

Data Access

Data Control

DataField Property

DataSource Property

Recordset Property

RecordSource Property

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


Filling a Grid with Data from a Database

See Also	Example

It may be convenient for your users to use a grid control to view data from your database.  You can quickly put data from a Dynaset or Snapshot into a grid.

To clear data from a grid

1.	Select all cells on the grid:

Grid1.SelStartCol = 0
Grid1.SelEndCol = Grid1.Cols - 1
Grid1.SelStartRow = 0
Grid1.SelEndRow = Grid1.Rows - 1

2.	Clear the selected cells:

Grid1.Clip = ""

To place data into a grid

1.	Determine how many rows and columns are in the recordset (the code in the example assumes one fixed column and one fixed row), then set the size of the grid.

Data1.Recordset.MoveLast
Grid1.Rows = Data1.Recordset.RecordCount + 1
Grid1.Cols = Data1.Recordset.Fields.Count + 1

2.	Move through the recordset until you reach the last record, using a Do Until...EOF loop:

Do Until Data1.Recordset.EOF

3.	For each record, put values into each column of the current row of the grid.  Values that are Null or too large will produce an error.  You can avoid such errors by using an On Error Resume Next statement.


vbhowFillGridWithDataSee
See Also

Help:

Data Access

Data Control

Grid Control

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

On...GoSub, On...GoTo Statements

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


vbhowFillGridWithDataEx
Filling a Grid with Data from a Database [image] Example

The first example accepts a grid and clears the contents of all cells in the grid.

Sub ClearGrid (G As Grid)
Dim StartCol As Integer, EndCol As Integer
Dim StartRow As Integer, EndRow As Integer
StartCol = G.SelStartCol	' Save current location.
EndCol = G.SelEndCol
StartRow = G. Row
EndRow = G.SelEndRow

G.SelStartCol = 0	' Select all cells.
G.SelEndCol = G.Cols - -1
G.SelStartRow = 0
G.SelEndRow = G.Rows - 1
G.Clip = ""	' Clear all cells.

G.SelStartCol = StartCol	' Return to starting location.
G.SelEndCol = EndCol
G.SelStartRow = StartRow
G.SelEndRow = EndRow
End Sub

This example (for the Professional Edition only) accepts a Snapshot and a grid, uses the first example to clear the grid, then fills the grid with the contents of the Snapshot.

Sub FillGrid (Sn As Snapshot, G As Grid)
Dim I As Integer
Sn.MoveLast	' Count the records.
G.Rows = Sn.RecordCount + 1	' Set the rows.
G.Cols = Sn.Fields.Count + 1	' Set the columns.
ClearGrid G
Sn.MoveFirst
Do Until Sn.EOF	' Loop through the Snapshot.
On Error Resume Next
For I = 0 to G.Cols - 1	' Cycle through the columns.
G.Col = I	' Set the column number.
If I = 0 Then	' If first column...
G.Text = I	' Set the value.
Else
G.Text = Sn(I)
End If
Next I
On Error Goto 0
Sn.MoveNext	' Move to next record.
G.Row = G.Row + 1	' Set the row number.
Loop
End Sub


Command Line Switches

See Also

Description

Determines whether Visual Basic compiles and runs a program, compiles and makes an executable (.EXE) file, or sets the argument part of the command line returned by the Command function.

Syntax

vb[.exe] [[{/run | /r} makname ] [{/make | /m } makname ] {/cmd argument | /c argument }]

Remarks

The parts of the command line switches syntax are:

Part	Description

makname	The name of your project (.MAK) file.

/run or /r	Tells Visual Basic to compile makname and run it, using the argument stored in the Command Line Argument option in the Project command of the Options menu.

/make or /m	Tells Visual Basic to compile makname and make an executable (.EXE) file from it, using the existing settings of the Path, EXEName, and Title properties of the App object.

/cmd or /c	Puts argument in the Command Line Argument option in the Project command of the Options menu.  When used, this must be the last switch on the command line.

argument	Any string expression used by your program.  You can retrieve this string with the Command function.

When used, these switches must be in a command line to run Visual Basic.  For example, you might use them in the Properties dialog of the Windows Program Manager.  Here is a valid command line that runs Visual Basic, loads a specific project, and runs it:

C:\vb.exe /r MYPROJ.MAK


See Also

Command, Command$ Function

Project Command (Options Menu)


Accessing External Databases

See Also	Example

Description

Visual Basic provides a number of ways to access data from external databases. For example, you can open a Dynaset on an external table using the data control by specifying the external database type in the Connect property and an appropriate directory or file name in the DatabaseName property of the data control.  For more information on accessing external tables, see the EXTERNAL.TXT readme file.

Professional Edition

In the Professional Edition, you can also use the OpenDatabase function to access external tables. Set the connect part to the appropriate database type and any needed connection parameters, and set the DatabaseName argument to either "ODBC;" for ODBC databases, or to the directory or file name of the external database.

In addition, you can attach an external table to an existing Visual Basic database.  This creates a link to an external table in your Visual Basic database.  You cannot open a Table object with the OpenTable method based on attached tables.  You can write code to create a database and attach external tables.

To attach tables to an existing Visual Basic database

1.	Create a variable for the Database object you are going to modify:

Dim Db As Database

2.	Use OpenDatabase to open the existing database:

Set Db = OpenDatabase("C:\VB\BIBLIO.MDB")

3.	Create a new TableDef object for the external table, set the TableDef properties to link to the attached table, and add it to the TableDefs collection with the Append method.

a.	Create a new TableDef object, and set the following TableDef properties:
Name [image] the name to be used in Visual Basic.
SourceTableName [image] the original name of the table or file name.
Connect [image] the database type and other parameters.

b.	Repeat the preceding step for each external Table, then add the TableDef object to the Database with the Append method.  This is the step that actually creates the object links in the database file.


vbhowAccessingExternalDatabasesSee
See Also

Help:

Data Access

Data Control

Dim Statement

OpenDatabase Function (Professional Edition Only)

OpenTable Method (Professional Edition Only)

Set Statement

Data Access Guide:

Appendix C, "Accessing External Databases"


vbhowAccessingExternalDatabasesEx
Accessing an External Database Example

This example opens a Paradox database and uses the OpenTable function to open a Paradox table.

Sub OpenParadoxDb ()
Dim Db As Database, Tb As Table, Conn As String
Conn = "Paradox;"	' Specify database type.
' Open the database.
Set Db = OpenDatabase("C:\PARADOX", False, False, Conn)
Set Tb = Db.OpenTable("PARATBL.DB") 	' Open Paradox table file.
...
End Sub

This example attaches a dBASE III table called Author in the C:\DATADIR directory to an existing Visual Basic database.

Sub AttachdBaseTable ()
Dim Db As Database, Td As New TableDef
Set Db = OpenDatabase("C:\VB\MYDB.MDB")
Td.Connect = "dBASE III;DATABASE=C:\DATADIR"
Td.SourceTableName = "AUTHOR.DBF"	' The name of the file.
Td.Name = "dbAuthor"	' The name in your database.
Db.TableDefs.Append Td	' Create the link.
...
End Sub


Using SQL (Structured Query Language)

See Also

You can use SQL, or Structured Query Language, to query, update, and manage relational databases.

You can use SQL statements in most places where you can enter the name of a table, query, or field.  For example, you can enter an SQL statement as the setting for the RecordSource property of a data control.  In the Professional Edition, you can also use an SQL statement in code to create a Dynaset or Snapshot.

The SQL syntax described here is for use with Visual Basic or Microsoft Access database engines. In cases where you use an external ODBC server (such as Microsoft SQL Server or Oracle) to execute SQL statements, your SQL syntax will need to conform to the SQL dialect used by the external server. In many cases, the SQL described here will function without change on external servers.

To learn more about the parts of an SQL SELECT statement, click one of the topics below.

SELECT fieldlist

FROM tablenames IN databasename

WHERE searchconditions

GROUP BY fieldlist

HAVING searchconditions

ORDER BY fieldlist

Note   Although some of the SQL statements shown in the examples are written on several lines to make them easier to read, an SQL statement  can be a single line or string.  Also, in these examples, the SQL keywords are in upper case, but case is not significant in the functionality.  The following is a valid SQL statement:

SELECT [Last Name], [First Name] FROM Employees WHERE Salary > 21000


vbhowSQLOverviewSee
See Also

Help:

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Visual Basic SQL Keywords

Data Access Guide:

Appendix B, "Microsoft Access SQL"


SELECT Statement (SQL Only)

See Also	Example

Description

SELECT specifies which fields you want to retrieve.  You use the FROM clause to indicate which tables contain those fields.  You use the WHERE clause to indicate which records are to be retrieved.

Notes

SELECT is usually the first word in an SQL statement.

If you include more than one field, separate the field names with commas.  List the fields in the order you want them to be retrieved.

If a field name appears in more than one table listed in the FROM clause, precede the field name with the table name and the . (dot) operator.  In the following example, the AU_ID field is in both the Authors table and the Titles table.  The SQL statement selects the Title field from the Titles table and the Author field from the Authors table.

SELECT Titles.Title.Dept, Author
FROM Titles, Authors
WHERE Titles.AU_ID = Authors.AU_ID

You can use an asterisk (*) to select all fields in a table.  The following example selects all of the fields in the Publishers table.

SELECT Publishers.* FROM Publishers

 You can use the AS reserved word to create an alias for a field name.  The following example uses the Year for the field name.

SELECT [Year Published] AS Year
FROM Titles

When you use a field name that contains a space or punctuation, surround the name with brackets:

SELECT [Year Published], Title
FROM Titles


vbhowSQLSELECTSee
See Also

Help:

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords

Data Access Guide:

Appendix B, "Microsoft Access SQL"


vbhowSQLSELECTEx
SELECT Statement, FROM Clause Examples

SQL statement	Description
SELECT [Last Name], [First Name] FROM Employees	Selects the Last Name and First Name fields of all records in the Employees table.
SELECT Employees.* FROM Employees	Selects all fields from the Employees table.
SELECT Orders.[Order ID], [Product ID],[Unit Price] FROM Orders, [Order Details]	Because the Order ID field appears in both the Orders and Order Details tables, this statement specifies that Order ID be retrieved from the Orders table.  Product ID and Price appear only in the Order Details table, so the name of the table doesn't have to be specified.
SELECT Count("[Postal Code]") AS Tally FROM Customer	Counts the number of records that have an entry in the Postal Code field and places the title Tally at the top of the column.
SELECT [Last Name], Salary * 1.1 AS Proposed FROM Employees	Shows what the salary would be if each employee received a 10 percent raise.  It does not change the original salary amounts.
SELECT [Last Name] AS Name, Salary FROM Employees	Places the title Name at the top of the Last Name column.  The title Salary appears at the top of the Salary column.
SELECT Count(*), Avg(Salary), Max(Salary) FROM Employees	Shows the number of employees and the average and maximum salaries.
SELECT [Last Name], 'has a salary of', Salary FROM Employees	For each record, shows the Last Name and Salary in the first and last fields.  It displays "has a salary of" in the middle field of each record.


FROM Clause (SQL Only)

See Also	Example

Description

FROM specifies the tables or queries that contain the fields listed in the SELECT statement.

Notes

FROM is required and follows SELECT.

The order of the table names is not important.

Data may be retreived from external databases if the table is attached to your database. If you wish to retrieve data from an external table that is not attached, you will need to use the IN clause with the FROM clause.

The following example shows how you can retrieve data from a table of Titles:

SELECT *	FROM Titles


vbhowSQLFROMSee
See Also

Help:

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords

Data Access Guide:

Appendix B, "Microsoft Access SQL"


IN Clause (SQL Only)

See Also	Example

Description

Use the IN clause to retrieve data stored in more than one database, such as a dBASE or Paradox database or in another Visual Basic database.  For example, you can use the IN clause to select all customers in a dBASE or Paradox table whose Customer ID has "A" as the first letter.

Notes

You can use IN to connect to only one external database at a time.  An external database is one other than the current database.

The IN clause has two parts: The databasename and connect string. The databasename is a fully-qualified path to the file or directory containing the database table and connect contains the database type and other parameters as needed.

To specify an external database, append a semicolon (;) to the connect part, and enclose it with single or double quotation marks.  For example,  'dBASE IV;' or "dBASE IV;".

The following example uses the IN clause to specify a dBASE IV database table "SALES":

SELECT CUSTOMERS.CustomerID,
FROM CUSTOMERS
IN "C:\DBASE\DATA\SALES" "dBASE IV;"
WHERE CUSTOMERS.CustomerID Like "A*"


vbhowSQLINSee
See Also

Help:

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords

Data Access Guide:

Appendix B, "Microsoft Access SQL"


vbhowSQLINEx
IN Clause Examples

The following table shows how you can use the IN clause to retrieve data from an external database.  The Customers table is stored in an external database.

External database	SQL statement

Microsoft Access 	SELECT Customers.[Customer ID],
FROM Customers,
IN MYDATA.MDB
WHERE Customers.[Customer ID] Like "A*"

MYDATA.MDB is the name of a Microsoft Access database containing the Customers table.

dBASE III+ or IV	SELECT CUSTOMERS.CustomerID,
FROM CUSTOMERS
IN "C:\DBASE\DATA\SALES" "dBASE IV;"
WHERE CUSTOMERS.CustomerID Like "A*"

To retrieve data from a dBASE III table, substitute "dBASE III;" in place of "dBASE IV;".

Paradox	SELECT CUSTOMERS.CustomerID
FROM CUSTOMERS
IN "C:\PARADOX\DATA\SALES" "Paradox;"
WHERE CUSTOMERS.CustomerID Like "A*"

Btrieve	SELECT CUSTOMERS.CustomerID
FROM CUSTOMERS
IN "C:\BTRIEVE\DATA\SALES\FILE.DDF" "Btrieve;"
WHERE CUSTOMERS.CustomerID Like "A*"

C:\BTRIEVE\DATA\SALES\FILE.DDF is the path and file name of the Btrieve data definition file.


WHERE Clause (SQL Only)

See Also	Example

Description

You can use WHERE to determine which records from the tables listed in the FROM clause will appear in the results of the SELECT statement.  Records are selected according to the conditions listed in the WHERE clause.

For example, you can select all employees in the Sales department (WHERE Dept = 'Sales') or all customers between the ages of 18 and 30 (WHERE Age BETWEEN 18 And 30).

Notes

WHERE is optional, but when included follows FROM.  If you don't include WHERE, all records are selected.

If you specify more than one table in your query with the FROM clause, and do not include a WHERE clause, Visual Basic will return a "cartesian product" of the tables. In other words, your query will contain all records from each additional table for each record of the first table. See JOIN for more information.

WHERE is similar to HAVING.  WHERE determines which records are selected.  Similarly, once records are grouped with GROUP BY, HAVING determines which records are returned.

Use the WHERE clause to eliminate rows you don't want grouped by a GROUP BY clause.

Use various expressions to determine which records the SQL statement returns.  For example, the following SQL statement selects all books which were published after 1991:

SELECT [Year Published], Title
FROM Titles
WHERE [Year Published] > 1991

When you enter a field name that contains a space or punctuation, surround the name with brackets:

SELECT [Product ID], [Units In Stock]
FROM Products
WHERE [Units In Stock] <= [Reorder Level]


vbhowSQLWHERESee
See Also

Help:

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords

Data Access Guide:

Appendix B, "Microsoft Access SQL"


vbhowSQLWHEREEx
WHERE Clause Examples

SQL statement	Description
SELECT [Last Name], [First Name] FROM Employees WHERE [Last Name] = 'King';	Selects the Last Name and First Name fields of each record in which the last name is King.
SELECT [Last Name], [First Name] FROM Employees WHERE [Last Name] Like 'S*';	Selects the Last Name and First Name fields for employees whose last names begin with the letter S.
SELECT [Last Name], Salary FROM Employees WHERE Salary Between 20000 And 30000;	Selects employees whose salaries are between $20,000 and $30,000, inclusive.
SELECT [Last Name], Salary FROM Employees WHERE [Last Name] Between 'Lon'  And 'Tol';	Selects employees whose last names fall in alphabetical order between Lon and Tol, inclusive.  It doesn't retrieve Tolstoy because Tolstoy follows Tol and therefore is outside the specified range.
SELECT [Order ID], [Order Date] FROM Orders WHERE [Order Date] Between #1-1-94# And  #6-30-94#;	Selects orders placed during the first half of 1994.
SELECT [Last Name], [First Name], City FROM Employees WHERE City In ('Interlaken', 'New York', 'Frankfurt');	Selects employees who live in Interlaken, New York, or Frankfurt.
SELECT Title, [Year Published], Author FROM Titles, Authors WHERE Titles.AU_ID = Authors.AU_ID AND Title LIKE 'A%'	Selects title, year, and author for all titles that start with the letter "A"


GROUP BY Clause (SQL Only)

See Also	Example

Description

GROUP BY combines records with identical values in the specified field list into a single record.  A summary value is created for each record if you include an aggregate function, such as Sum or Count, in the SELECT statement.  If the SQL statement includes a WHERE clause, records are grouped after applying the WHERE conditions to the records.

Notes

GROUP BY is optional but when included follows FROM and WHERE.

Summary values are omitted if there is no aggregate function in the SELECT statement.

Null values in GROUP BY fields are grouped and are not omitted.  However, Null values aren't evaluated in any aggregate function.

Use the WHERE clause to exclude rows you don't want grouped.

A field in the GROUP BY field list can refer to any field listed in the FROM clause, even if the field is not included in the SELECT statement, provided the SELECT statement includes at least one aggregate function.

All fields must be in the GROUP BY field list or must be referred to by an aggregate function in the SELECT statement.

When you type a field name that contains a space or punctuation, surround the name with brackets:

SELECT [Product Name], Sum([Units in Stock])
FROM Products
GROUP BY [Product Name]


vbhowSQLGROUPBYSee
See Also

Help:

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords

Data Access Guide:

Appendix B, "Microsoft Access SQL"


vbhowSQLGROUPBYEx
GROUP BY Clause Examples

SQL statement	Description
SELECT Dept, Count(Dept) AS Tally FROM Employees GROUP BY Dept;	Creates a list of unique department names and the number of employees in each of those departments
SELECT Title, Count(Title) AS Tally FROM Employees WHERE Dept = 'Production' GROUP BY Title;	Calculates the number of Production department employees who have the same job title
SELECT Item, Sum(Units) AS Tally FROM ItemsInStock GROUP BY Item, Color;	Calculates the number of items in stock for each combination of item number and color


HAVING Clause (SQL Only)

See Also	Example

Description

Use HAVING to specify which grouped records are displayed.  Once GROUP BY combines records, HAVING displays all records grouped by the GROUP BY clause that satisfy the conditions of the HAVING clause.

Notes

HAVING is optional but when included follows GROUP BY.

HAVING is similar to WHERE.  WHERE determines which records are selected.  Once records are grouped with GROUP BY, HAVING determines which records are displayed.

Use various expressions to determine which records are displayed.


vbhowSQLHAVINGSee
See Also

Help:

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords

Data Access Guide:

Appendix B, "Microsoft Access SQL"


vbhowSQLHAVINGEx
HAVING Clause Examples

SQL statement	Description
SELECT Title, Count(Title) FROM Employees WHERE Department = 'Production' GROUP BY Title HAVING Count(Title) > 50;	Displays the job titles in the Production department assigned to more than 50 employees
SELECT Department, Count(Department) FROM Employees GROUP BY Department HAVING Count(Department) > 100;	Displays departments with more than 100 employees


ORDER BY Clause (SQL Only)

See Also	Example

Description

ORDER BY sorts the displayed data in the order specified in the clause.

Notes

ORDER BY is optional.  If you don't include it, the data appears unsorted.

The default sort order is ascending (A-Z, 0-9).  However, you may want to include the ASC reserved word at the end of each column you want to sort in ascending order.  Both of the following examples sort employee names in last name order:

SELECT [Last Name], [First Name]
FROM Employees
ORDER BY [Last Name]

SELECT [Last Name], [First Name]
FROM Employees
ORDER BY [Last Name] ASC

To sort in reverse order (Z-A, 9-0), add the DESC reserved word to the end of each column you want to sort in descending order.  The following example selects salaries and sorts them in descending order.

SELECT [Last Name], Salary
FROM Employees
ORDER BY Salary DESC, [Last Name];

ORDER BY is usually the last item in an SQL statement.


vbhowSQLORDERBYSee
See Also

Help:

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords

Data Access Guide:

Appendix B, "Microsoft Access SQL"


vbhowSQLORDERBYEx
ORDER BY Clause Examples

SQL statement	Description
SELECT [Last Name], [First Name] FROM Employees ORDER BY [Last Name] DESC	Sorts the records by last name in descending order (Z-A)
SELECT [Category ID], [Product Name], [Unit Price] FROM Products ORDER BY [Category ID], [Product Name]	Sorts by category ID first, then by product name


SELECT...INTO Statement (SQL Only)

See Also	Example

Description

You can use SELECT...INTO to create a make-table query.  Use make-table queries to archive records, make backup copies of your tables, or make copies to export to another database or use as a basis for reports that display data from a particular point in time.  For example, you might produce a Monthly Sales by Region report by running the same make-table query each month.

Notes

The SELECT...INTO statement has the following syntax:

SELECT fieldlist INTO newtablename

The argument fieldlist is a list of fields that will be copied into the new table.  If fieldlist contains more than one field, separate the field names with commas.

The argument newtablename is the name of the table created by the query.  If the new table name you enter or select is the same as the name of an existing table. the structure and data of the old table is replaced with those of the new table.

You may want to define a primary key index for the new table.  When you create the table, the fields in the new table inherit the data type and field size of each field in the query's underlying tables, but no other field or table properties are transferred.

Use the IN clause to create the new table in another database.

To add data to an existing table, use the INSERT INTO statement instead to create an append query.


vbhowSELECTINTOSee
See Also

Help:

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords

Data Access Guide:

Appendix B, "Microsoft Access SQL"


vbhowSELECTINTOEx
SELECT...INTO Statement Examples

SQL statement	Description
SELECT Employees.* INTO [Emp Backup] FROM Employees;	Selects all records in the Employees table and copies them into a new table named Emp Backup.
SELECT Employees.* INTO Trainees FROM Employees WHERE Title = 'Trainee';	Creates a new table that contains only employee records that have the title Trainee.
SELECT Employees.* INTO Employees IN "BACKUP.MDB" FROM Employees;	Makes a copy of the Employees table and places the new table in the BACKUP database.
SELECT Employees.*, Salary INTO Trainees FROM Employees, Payroll, Employees INNER JOIN Payroll ON Employees.[Employee ID] = Payroll.[Employee ID] WHERE Title = 'Trainee';	Creates a new table that contains employee and payroll data for all trainees.  The Employees and Payroll tables have a one-to-one relationship.  The new table contains all of the data from the Employees table, plus the Salary field from the Payroll table.


UPDATE Statement (SQL Only)

See Also	Example

Description

You can use UPDATE in an action query to create an update query that changes records in the tables listed in the FROM clause.  You can use expressions to make the change.  For example, you can reduce the price of all beverages by 10 percent or increase mailing charges for all clothing items by 3 percent.

Notes

UPDATE is especially useful when you want to change many records or when the records are in multiple tables.

Use the SET reserved word to specify the new values.  In the following example, the new value for the Freight field is set to the existing value plus 3 percent.

UPDATE Orders
SET Freight = Freight * 1.03
WHERE [Ship Country] = 'UK'

You can change several fields at the same time.  The following example increases the Order Amount values by 10 percent and the Freight values by 3 percent:

UPDATE Orders
SET [Order Amount] = [Order Amount] * 1.1, Freight = Freight * 1.03
WHERE [Ship Country] = 'UK'

No records are returned when you use the UPDATE statement.

In some cases, you can edit the data in a query's Dynaset to change the data in the underlying tables;  in other cases, you cannot.

Warning   If an SQL statement changes more rows than the internal transaction log can hold, Visual Basic will force the transation to commit the transaction in stages. If your program is interrupted before the operation is completed, only the last, uncompleted stage(s) will be rolled back. In this case only some of the records to be changed will have been affected. If you use a BeginTrans statement before the SQL statement, a trappable error will occur if the transaction log fills prior to the completion of your statement, and all of the changes made by your statement will be automatically rolled back.


vbhowUPDATESee
See Also

Help:

BeginTrans, CommitTrans, Rollback Statements

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords

Data Access Guide:

Appendix B, "Microsoft Access SQL"


vbhowUPDATEEx
UPDATE Statement Examples

SQL statement	Description
UPDATE Employees SET [Reports To] = 5 WHERE [Reports To] = 2;	Changes values in the Reports To field to 5 for all employee records that currently have Reports To values of 2.
UPDATE Products SET [Unit Price] = [Unit Price] * 1.1 WHERE [Supplier ID] = 8 AND Discontinued = No;	Increases the Unit Price for all nondiscontinued products from supplier 8 by 10 percent.
UPDATE Products, Suppliers, Suppliers INNER JOIN Products ON Suppliers.[Supplier ID] = Products.[Supplier ID] SET [Unit Price] = [Unit Price] * .95 WHERE [Company Name] = 'Tokyo Traders' AND Discontinued = No;	Reduces the Unit Price for all nondiscontinued products supplied by Tokyo Traders by 5 percent.  The Products and Suppliers tables have a one-to-one relationship.


DELETE Statement (SQL)

See Also	Example

Description

You can use DELETE in an action query to create a delete query that removes records listed in the DELETE statement and from the tables listed in the FROM clause.

Notes

DELETE is especially useful when you want to delete many records or when the records are in multiple tables.

If you want to delete all of the records in a table, deleting the table itself may be more efficient than executing a delete query.  If you delete the table, however, the structure is lost.  In contrast, when you use DELETE, only the data is removed; the table structure and all of the table properties, such as field attributes and indexes, remain intact.

If you want to delete only some of the records in a table, include a WHERE clause in your SQL statement.  Only records that meet the conditions in the WHERE clause will be deleted.

No records are returned when you use the DELETE statement.

You can use DELETE to remove records from a single table or from multiple tables in a one-to-one relationship.  To remove records from tables in a one-to-many relationship (for example, records for all customers in the United Kingdom and all their orders), you must run two queries.

A delete query deletes entire records, not just data in specific fields.  If you want to delete values in a specific field, create an update query that changes the values to empty values.

Important   Once you remove records using a delete query, you can't undo the operation.  If you want to know which records will be deleted, first examine the results of a select query that uses the same criteria, and then execute the delete query.

Maintain backup copies of your data at all times.  If you delete the wrong records, you can retrieve them from your backup copies.

Warning   If an SQL statement changes more rows than the internal transaction log can hold, Visual Basic will force the transation to commit the transaction in stages. If your program is interrupted before the operation is completed, only the last, uncompleted stage(s) will be rolled back. In this case only some of the records to be changed will have been affected. If you use a BeginTrans statement before the SQL statement, a trappable error will occur if the transaction log fills prior to the completion of your statement, and all of the changes made by your statement will be automatically rolled back.


vbhowDELETESee
See Also

Help:

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords

Data Access Guide:

Appendix B, "Microsoft Access SQL"


vbhowDELETEEx
DELETE Statement Examples

SQL statement	Description
DELETE FROM Employees WHERE Title = 'Trainee';	Deletes all records for employees whose title is Trainee.  When the FROM clause includes only one table, you don't have to list the table name in the DELETE statement.
DELETE  FROM Employees, Payroll,  Employees INNER JOIN Payroll ON Employees.[Employee ID] = Payroll.[Employee ID] WHERE Title = 'Trainee';	Deletes all records for employees whose title is Trainee and who also have a record in the Payroll table.  The Employees and Payroll tables have a one-to-one relationship.


Visual Basic SQL Keywords

See Also

ALL AS ASC BINARY BIT BY BYTE CHAR[ACTER] CURRENCY DATABASE DATETIME DELETE DESC DISTINCT DISTINCTROW FLOAT FROM GROUP BY	HAVING IEEEDOUBLE IEEESINGLE IN INNER INSERT INT[EGER] INTO JOIN LEFT LEVEL* LONG LONGBINARY LONGTEXT ON OPTION ORDER BY OWNERACCESS	PARAMETERS PIVOT PROCEDURE REAL RIGHT SELECT SET SHORT SMALLINT TABLEID TEXT TRANSFORM UPDATE VALUE WHERE WITH
* Reserved for future use.  For information about other SQL keywords, consult the sources listed in the sample database, BIBLIO.MDB.


vbhowSQLReservedWordsSee
See Also

Help:

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Data Access Guide:

Appendix B, "Microsoft Access SQL"


SQL Aggregate Functions (SQL Only)

See Also

Using the SQL aggregate functions in an SQL statement, you can determine various statistics on sets of values.  You can use these functions only in SQL statements.

Avg Function

Count Function

First, Last Functions

Min, Max Functions

StDev, StDevP Functions

Sum Function

Var, VarP Functions

Domain Aggregate Functions


vbfctSQLAggregatesSee
See Also

Help:

Domain Aggregate Functions (SQL Only)

Using SQL (Structured Query Language)

Visual Basic SQL Keywords

Data Access Guide:

Appendix B, "Microsoft Access SQL"


Domain Aggregate Functions (SQL Only)

See Also

Using the domain aggregate functions, you can determine various statistics about domains.  You can use these functions in a macro or module or in a query expression.

DAvg Function

DCount Function

DFirst, DLast Functions

DLookup Function

DMin, DMax Functions

DStDev, DStDevP Functions

DSum Function

DVar, DVarP Functions

SQL Aggregate Functions


vbfctSQLDomainSee
See Also

Help:

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords

Data Access Guide:

Appendix B, "Microsoft Access SQL"


Avg Function (SQL Only)

See Also	Example

Description

Calculates the arithmetic mean of a set of values contained in a specified field on a query.

Syntax

Avg( expr )

Remarks

The Avg function uses the following argument.

Argument	Description

expr	String expression identifying the field that contains the numeric data you want to average, or an expression that performs a calculation using the data in that field.  Operands in expr can include the name of a table field, or a Visual Basic function (which can be intrinsic but not a user-defined function or one of the other domain aggregate or SQL aggregate functions).

The average calculated by Avg is the arithmetic mean (the sum of the values divided by the number of values).  You might use Avg, for example, to calculate average freight cost.

The Avg function doesn't include any Null fields in the calculation.


vbfctSQLAvgSee
See Also

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords


vbfctSQLAvgEx
Avg Function Example

This example uses an Orders table to calculate the average sale for orders over $1000.  You can enter this expression in an SQL statement.

SELECT Avg([Order Amount]) FROM Orders WHERE [Order Amount] > 1000


Count Function (SQL Only)

See Also	Example

Description

Calculates the number of selected records in a query.

Syntax

Count( expr )

Remarks

The Count function uses the following argument.

Argument	Description

expr	String expression identifying the field that contains the data you want to count, or an expression that performs a calculation using the data in the field.  Operands in expr can include the name of a table field, or a Visual Basic function (which can be intrinsic but not a user-defined function or one of the other domain aggregate or SQL aggregate functions).  You can count any kind of data, including text.

You can use Count to count the number of records in an underlying query.  For example, you could use Count to count the number of orders shipped to a particular country.

Although expr can perform a calculation on a field, Count simply tallies the number of records.  It doesn't matter what values are stored in the records.

The Count function doesn't count records that have Null fields unless expr is the wildcard character (*).  If you use the wildcard character, Count calculates the total number of records, including those that contain Null fields.  Do not enclose the wildcard character in quotation marks.  The following example calculates the number of records in the Orders table.

SELECT Count(*) FROM Orders

If expr identifies multiple fields, the Count function counts a record only if at least one of the fields is not Null.  If all of the specified fields are Null, the record isn't counted.  Separate the field names with an ampersand (&).  The following example shows how you can limit the count to records in which either Order Amount or Freight is not Null.

SELECT Count("[Order Amount] & [Freight]") FROM Orders


vbfctSQLCountSee
See Also

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords


vbfctSQLCountEx
Count Function Example

This example calculates the number of orders shipped to the United Kingdom.

SELECT Count([Ship Country]) FROM Orders WHERE [Ship Country] = 'UK'


First, Last Functions (SQL Only)

See Also

Description

Return a field value from the first or last record in a query.

Syntax

First(expr)

Last(expr)

Remarks

The First and Last functions use the following argument.

Argument	Description

expr	String expression identifying the field that contains the data you want to use, or an expression that performs a calculation using the data in that field.  Operands in expr can include the name of a table field, or a Visual Basic function (which can be intrinsic but not a user-defined function or one of the other domain aggregate or SQL aggregate functions).

You can use First and Last to determine the limits of the underlying query.  For example, the records returned by First and Last might contain order dates that you could use in a report title to identify the range for orders.

You can use First and Last in a query expression.


vbfctSQLFirstSee
See Also

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords


Min, Max Functions (SQL Only)

See Also	Example

Description

Return the minimum or maximum of a set of values contained in a specified field on a query.

Syntax

Min( expr )

Max( expr )

Remarks

The Min and Max functions use the following argument.

Argument	Description

expr	String expression identifying the field that contains data you want to evaluate, or an expression that performs a calculation using the data in that field.  Operands in expr can include the name of a table field, or a Visual Basic function (which can be intrinsic but not a user-defined function or one of the other domain aggregate or SQL aggregate functions).

You can use Min and Max to determine the smallest and largest values in a field, including a Text field.  For example, you could use Min and Max to return the lowest and highest freight cost.

You can use Min and Max in a query expression.


vbfctSQLMinSee
See Also

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords


vbfctSQLMinEx
Min, Max Functions Example

This example returns the lowest and highest sale for orders shipped to the United Kingdom.

SELECT Min([Order Amount]) FROM Orders WHERE [Ship Country] = 'UK';

SELECT Max([Order Amount]) FROM Orders WHERE [Ship Country] = 'UK';


StDev, StDevP Functions (SQL Only)

See Also	Example>Low

Description

Return estimates of the standard deviation for a population or a population sample represented as a set of values contained in a specified field on a query.

Syntax

StDev( expr )

StDevP( expr )

Remarks

StDevP evaluates a population, and StDev evaluates a population sample.

The StDev and StDevP functions use the following argument.

Argument	Description

expr	String expression identifying the field that contains the numeric data you want to evaluate, or an expression that performs a calculation using the data in that field.  Operands in expr can include the name of a table field, or a Visual Basic function (which can be intrinsic but not a user-defined function or one of the other domain aggregate or SQL aggregate functions).

If the underlying query contains fewer than two records (or no records, for StDevP), these functions return a Null (which indicates that a standard deviation can't be calculated).


vbfctSQLStDevSee
See Also

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords


vbfctSQLStDevEx
StDev, StDevP Functions Example

This example estimates the standard deviation of the sales amounts for orders shipped to the United Kingdom.

SELECT StDev([Order Amount]) FROM Orders WHERE [Ship Country] = 'UK';

SELECT StDevP([Order Amount]) FROM Orders WHERE [Ship Country] = 'UK';


Sum Function (SQL Only)

See Also	Example

Description

Returns the sum of a set of values contained in a specified field on a query.

Syntax

Sum( expr )

Remarks

The Sum function uses the following argument.

Argument	Description

expr	String expression identifying the field that contains the numeric data you want to add, or an expression that performs a calculation using the data in that field.  Operands in expr can include the name of a table field, a control on a form, a constant, or a function (which can be either intrinsic but not a user-defined function or one of the other SQL aggregate or domain aggregate functions).

Sum totals the values in a field.  For example, you can use Sum to determine the total cost of freight charges.

The Sum function treats records that contain Null fields as having a value of 0.  The following example shows how you can calculate the sum of the Order Amount and Freight fields.

SELECT Sum([Order Amount] + [Freight]) FROM Orders


vbfctSQLSumSee
See Also

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords


vbfctSQLSumEx
Sum Function Example

This example calculates the total sales (including freight costs) for orders shipped to the United Kingdom.

SELECT Sum([Order Amount] + [Freight]) FROM Orders WHERE [Ship Country] = 'UK'


Var, VarP Functions (SQL Only)

See Also	Example

Description

Return estimates of the variance for a population or a population sample represented as a set of values contained in a specified field of a query.

Syntax

Var( expr )

VarP( expr )

Remarks

VarP evaluates a population, and Var evaluates a population sample.

The Var and VarP functions use the following argument.

Argument	Description

expr	String expression identifying the field that contains the numeric data you want to evaluate, or an expression that performs a calculation using the data in that field.  Operands in expr can include the name of a table field, or a Visual Basic function (which can be intrinsic but not a user-defined function or one of the other domain aggregate or SQL aggregate functions).

If the underlying query contains fewer than two records, Var and VarP return a Null (which indicates that a variance can't be calculated).


vbfctSQLVarSee
See Also

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords


vbfctSQLVarEx
Var, VarP Functions Example

This example estimates the variance of freight costs.

SELECT Var([Freight]) FROM Orders WHERE [Ship Country] = 'UK';

SELECT VarP([Freight]) FROM Orders WHERE [Ship Country] = 'UK';


DAvg Function (SQL Only)

See Also	Example

Description

Returns the arithmetic mean of a set of values in a specified set of records (domain).

Syntax

DAvg( expr, domain [, criteria] )

Remarks

The DAvg function uses the following arguments.

Argument	Description

expr	String expression identifying the field that contains the numeric data you want to average, or an expression that performs calculations using the data in that field.  Operands in expr can include the name of a table field, or a Visual Basic function (which can be intrinsic but not a user-defined function or one of the other domain aggregate or SQL aggregate functions).

domain	String expression identifying the records that constitute the domain.  It can be a table name, a query name, or an SQL expression that returns data.

criteria	Optional string expression used to restrict the range of data on which DAvg is performed.  For example, criteria could be the WHERE clause in an SQL expression (without the word WHERE).  If criteria is omitted, DAvg evaluates expr against the entire domain.

The average calculated by DAvg is the arithmetic mean (the sum of the values divided by the number of values).  You might use DAvg to calculate average freight cost.

If the criteria argument contains non-numeric text other than field names, you must enclose the text in single quotation marks.  In the following examples, Ship Country is the name of a field, and UK is a string literal.

X = DAvg("[Freight]", "Orders", "[Ship Country] = 'UK'")

Y = DAvg("[Freight]", "Orders", "[Ship Via] = 1")

Records that contain Null fields aren't included in the calculation.


vbfctDAvgSee
See Also

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords


vbfctDAvgEx
DAvg Function Example

This example returns the average freight cost for large orders shipped to the United Kingdom.  The domain is an Orders table.  The criteria part restricts the data by making the expression apply only to records in which Ship Country equals UK and Order Amount is greater than 1000.

X = DAvg("[Freight]", "Orders", "[Ship Country] = 'UK' And [Order Amount] > 1000")


DCount Function (SQL Only)

See Also	Example

Description

Returns the number of selected records in a specified set of records (domain).

Syntax

DCount( expr, domain [, criteria] )

Remarks

The DCount function uses the following arguments.

Argument	Description

expr	String expression identifying the field that contains the data you want to count, or an expression that performs calculations using the data in that field.  Operands in expr can include the name of a table field, or a Visual Basic function (which can be intrinsic but not a user-defined function or one of the other domain aggregate or SQL aggregate functions).  You can count any kind of data, including text.

domain	String expression identifying the records that constitute the domain.  It can be a table name, a query name, or an SQL expression that returns data.

criteria	Optional string expression used to restrict the range of data on which DCount is performed.  For example, criteria could be the WHERE clause in an SQL statement (without the word WHERE).  If criteria is omitted, DCount evaluates expr against the entire domain.

If you don't need to know particular values, you can use DCount to count the number of records in a domain.  For example, you could use DCount to count the number of orders shipped to a particular region.  Although expr can perform a calculation on a field, DCount simply tallies the number of records.  It doesn't matter what values are stored in the records.

Unless expr is the asterisk (*) wildcard character, the DCount function doesn't count records that contain Null fields.  If you use an asterisk, DCount calculates the total number of records, including those that contain Null fields.  The following example calculates the number of records in the Orders table.

X = DCount("*", "Orders")

If domain is an indexed table, you can also count the total number of records by setting expr to the primary key field.  The primary key field in an indexed table will not be Null.

If the criteria argument contains non-numeric text other than field names, you must enclose the text in single quotation marks.  In the following example, Ship Country is the name of a field, and UK is a string literal.

X = DCount("[Freight]", "Orders", "[Ship Country] = 'UK'")
Y = DCount("[Freight]", "Orders", "[Ship Via] = 1")

If expr identifies multiple fields, separate the field names with either a plus sign (+) or an ampersand (&).  The following examples show the effects of each when used with a non-Null field (Ship Name) and a Null field (Ship Region).

W = DCount("[Ship Name]", "Orders")	' Returns 1078.

X = DCount("[Ship Region]", "Orders")	' Returns 834.

Y = DCount("[Ship Name] + [Ship Region]", "Orders")	' Returns 834.

Z = DCount("[Ship Name] & [Ship Region]", "Orders")	' Returns 1078.


vbfctDCountSee
See Also

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords


vbfctDCountEx
DCount Function Example

This example returns the number of large orders shipped to the United Kingdom.  The domain is an Orders table.  The criteria argument restricts the data by making the expression apply only to records in which Ship Country equals UK and Order Amount is greater than 1000.

X = DCount("[Order Amount]", "Orders", "[Ship Country] = 'UK' And [Order Amount] > 1000")


DFirst, DLast Functions (SQL Only)

See Also	Example

Description

Return a field value from the first and last record in a specified set of records (domain).

Syntax

DFirst( expr, domain [, criteria] )

DLast( expr, domain [, criteria] )

Remarks

The DFirst and DLast functions use the following arguments.

Argument	Description

expr	String expression identifying the field that contains the data you want to return, or an expression that performs calculations using the data in that field.  Operands in expr can include the name of a table field, or a Visual Basic function (which can be intrinsic but not a user-defined function or one of the other domain aggregate or SQL aggregate functions).

domain	String expression identifying the records that constitute the domain.  It can be a table name, a query name, or an SQL expression that returns data.

criteria	Optional string expression used to restrict the range of data on which DFirst or DLast is performed.  For example, criteria could be the WHERE clause in an SQL expression (without the word WHERE).  If criteria is omitted, expr is evaluated against the entire domain.

DFirst and DLast are similar to DLookup.  These functions return a field value from the record that satisfies criteria.  DFirst and DLast return values from the first and last occurrence according to the order of records in domain.  If domain is an indexed table, the order follows the current index.  Otherwise, the order follows the actual order of the records.

If more than one record satisfies criteria, DFirst returns the field value from the first occurrence.

You can use DFirst and DLast to determine the limits of a domain.  For example, the fields returned by DFirst and DLast might contain order dates that you could use in a report title to indicate the range for orders.

If the criteria argument contains non-numeric text other than field names, you must enclose the text in single quotation marks.  In the following example from an Orders, Ship Country is the name of a field, and UK is a string literal.

X = DFirst("[Freight]", "Orders", "[Ship Country] = 'UK'")

Y = DLast("[Freight]", "Orders", "[Ship Country] = 'UK'")

Z = DLast("[Freight]", "Orders", "[Ship Via] = 1")

If no record satisfies criteria, or if domain contains no records, DFirst and DLast return a Null.


vbfctDFirstSee
See Also

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords


vbfctDFirstEx
DFirst, DLast Functions Example

This example returns cost information from the Freight field of the first and last record for orders shipped to the United Kingdom.  The domain is an Orders table.  The criteria argument restricts the data by making the expression apply only to records in which Ship Country equals UK.

X = DFirst("[Freight]", "Orders", "[Ship Country] = 'UK'")

Y = DLast("[Freight]", "Orders", "[Ship Country] = 'UK'")


DLookup Function (SQL Only)

See Also	Example

Description

Returns a field value in a specified set of records (domain).

Syntax

DLookup( expr, domain [, criteria] )

Remarks

The DLookup function uses the following arguments.

Argument	Description

expr	String expression identifying the field that contains the data you want to return, or an expression that performs calculations using the data in that field.  Operands in expr can include the name of a table field, or a Visual Basic function (which can be intrinsic but not a user-defined function or one of the other domain aggregate or SQL aggregate functions).

domain	String expression identifying the records that constitute the domain.  It can be a table name, a query name, or an SQL expression that returns data.

criteria	Optional string expression used to restrict the range of data on which DLookup is performed.  For example, criteria could be the WHERE clause in an SQL expression (without the word WHERE).  If criteria is omitted, DLookup evaluates expr against the entire domain.

You can use DLookup to return a field value based on the value of another field.  In the following example, DLookup uses the Employee ID field to return the corresponding last name.

X = DLookup("[Last Name]", "Employees", "[Employee ID] = 24")

If the criteria argument contains non-numeric text other than field names, you must enclose the text in single quotation marks.  In the following example, Ship Postal Code is the name of a field, and 94117 is a string literal.

X = DLookup("[Ship Via]", "Orders", "[Ship Postal Code] = '94117'")

Y = DLookup("[Ship Via]", "Orders", "[Ship Via] = 1")

Even if more than one record satisfies criteria, DLookup returns only one field.  If no record satisfies criteria, or if domain contains no records, DLookup returns a Null.


vbfctDLookupSee
See Also

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords


vbfctDLookupEx
DLookup Function Example

This example returns name information from the Company Name field of the record satisfying the criteria.  The domain is the Shippers table.  The criteria argument restricts the data by making the expression apply only to the record in which Shipper ID equals 1.

X = DLookup("[Company Name]", "Shippers", "[Shipper ID] = 1")


DMin, DMax Functions (SQL Only)

See Also	Example

Description

Return the minimum and maximum of a set of values in a specified set of records (domain).

Syntax

DMin( expr, domain [, criteria] )

DMax( expr, domain [, criteria] )

Remarks

The DMin and DMax functions use the following arguments.

Argument	Description

expr	String expression identifying the field that contains the data you want to evaluate, or an expression that performs calculations using the data in that field.  Operands in expr can include the name of a table field, or a Visual Basic function (which can be intrinsic but not a user-defined function or one of the other domain aggregate or SQL aggregate functions).

domain	String expression identifying the records that constitute the domain.  It can be a table name, a query name, or an SQL expression that returns data.

criteria	Optional string expression used to restrict the range of data on which DMin and DMax are performed.  For example, criteria could be the WHERE clause in an SQL expression (without the word WHERE).  If criteria is omitted, DMin and DMax evaluate expr against the entire domain.

You can use DMin and DMax to return the lowest and highest value.  If expr identifies numeric data, these functions return numeric values.  If expr identifies non-numeric data, they return the string that is first or last alphabetically.  If the criteria argument contains non-numeric text other than field names, you must enclose the text in single quotation marks.  In the following example, Ship Country is the name of a field, and UK is a string literal.

X = DMin("[Freight]", "Orders", "[Ship Country] = 'UK'")

Y = DMax("[Freight]", "Orders", "[Ship Country] = 'UK'")

Z = DMax("[Freight]", "Orders", "[Ship Via] = 1")


vbfctDMinSee
See Also

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords


vbfctDMinEx
DMin, DMax Functions Example

This example returns the lowest and highest value from the Freight field for orders shipped to the United Kingdom.  The domain is an Orders table.  The criteria argument restricts the data by making the expression apply only to records in which Ship Country equals UK.

X = DMin("[Freight]", "Orders", "[Ship Country] = 'UK'")

Y = DMax("[Freight]", "Orders", "[Ship Country] = 'UK'")


DStDev, DStDevP Functions (SQL Only)

See Also	Example

Description

Return estimates of the standard deviation for a population and a population sample represented as a set of values in a specified set of records (domain).

Syntax

DStDev( expr, domain [, criteria] )

DStDevP( expr, domain [, criteria] )

Remarks

DStDevP evaluates a population, and DStDev evaluates a population sample.

The DStDev and DStDevP functions use the following arguments.

Argument	Description

expr	String expression identifying the field that contains the numeric data you want to evaluate, or an expression that performs calculations using the data in that field.  Operands in expr can include the name of a table field, or a Visual Basic function (which can be intrinsic but not a user-defined function or one of the other domain aggregate or SQL aggregate functions).

domain	String expression identifying the records that constitute the domain.  It can be a table name, a query name, or an SQL statement that returns data.

criteria	Optional string expression used to restrict the range of data on which DStDev is performed.  For example, criteria could be the WHERE clause in an SQL expression (without the word WHERE).  If criteria is omitted, DStDev evaluates expr against the entire domain.

If the criteria argument contains non-numeric text other than field names, you must enclose the text in single quotation marks.  In the following example from an Orders table, Ship Country is the name of a field, and UK is a string literal.

X = DStDev("[Freight]", "Orders", "[Ship Country] = 'UK'")

Y = DStDevP("[Freight]", "Orders", "[Ship Country] = 'UK'")

Z = DStDevP("[Freight]", "Orders", "[Ship Via] = 1")

If domain refers to fewer than two records, or if fewer than two records satisfy criteria, DStDev and DStDevP return a Null (which indicates that a standard deviation can't be calculated).


vbfctDStDevSee
See Also

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords


vbfctDStDevEx
DStDev, StDevP Functions Example

This example returns estimates of the standard deviation for a population and a population sample for orders shipped to the United Kingdom.  The domain is an Orders table.  The criteria argument restricts the data by making the expression apply only to records in which Ship Country equals UK.

X = DStDev("[Freight]", "Orders", "[Ship Country] = 'UK'")  ' Sample estimate.

Y = DStDevP("[Freight]", "Orders", "[Ship Country] = 'UK'") ' Population estimate.


DSum Function (SQL Only)

See Also	Example

Description

Returns the sum of a set of values in a specified set of records (domain).

Syntax

DSum( expr, domain [, criteria] )

Remarks

The DSum function uses the following arguments.

Argument	Description

expr	String expression identifying the field that contains the numeric data you want to add, or an expression that performs calculations using the data in that field.  Operands in expr can include the name of a table field, or a Visual Basic function (which can be intrinsic but not a user-defined function or one of the other domain aggregate or SQL aggregate functions).

domain	String expression identifying the records that constitute the domain.  It can be a table name, a query name, or an SQL expression that returns data.

criteria	Optional string expression used to restrict the range of data on which DSum is performed.  For example, criteria could be the WHERE clause in an SQL expression (without the word WHERE).  If criteria is omitted, DSum evaluates expr against the entire domain.

Unlike DCount, which returns the number of records, DSum totals the values in a field.  For example, you could use DSum to determine the total cost of freight charges.

If the criteria argument contains non-numeric text other than field names, you must enclose the text in single quotation marks.  In the following example from an Orders table, Ship Country is the name of a field, and UK is a string literal.

X = DSum("[Freight]", "Orders", "[Ship Country] = 'UK'")

Y = DSum("[Freight]", "Orders", "[Ship Via] = 1")


vbfctDSumSee
See Also

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords


vbfctDSumEx
DSum Function Example

This example totals the values from the Freight field for orders shipped to the United Kingdom.  The domain is an Orders table.  The criteria argument restricts the data by making the expression apply only to records in which Ship Country equals UK.

X = DSum("[Freight]", "Orders", "[Ship Country] = 'UK'")


DVar, DVarP Functions (SQL Only)

See Also	Example

Description

Return estimates of the variance for a population and a population sample represented as a set of values in a specified set of records (domain).

Syntax

DVar( expr, domain [, criteria] )

DVarP( expr, domain [, criteria] )

Remarks

DVarP evaluates a population, and DVar evaluates a population sample.  The DVar and DVarP functions use the following arguments.

Argument	Description

expr	String expression identifying the field that contains the numeric data you want to evaluate, or an expression that performs calculations using the data in that field.  Operands in expr can include the name of a table field, or a Visual Basic function (which can be intrinsic but not a user-defined function or one of the other domain aggregate or SQL aggregate functions).

domain	String expression identifying the records that constitute the domain.  It can be a table name, a query name, or an SQL expression that returns data.

criteria	Optional string expression used to restrict the range of data on which DVar is performed.  For example, criteria could be the WHERE clause in an SQL expression (without the word WHERE).  If criteria is omitted, DVar evaluates expr against the entire domain.

If the criteria argument contains non-numeric text other than field names, you must enclose the text in single quotation marks.  In the following example from the Orders table of the NWIND.MDB database, Ship Country is the name of a field, and UK is a string literal.

X = DVar("[Freight]", "Orders", "[Ship Country] = 'UK'")

Y = DVarP("[Freight]", "Orders", "[Ship Country] = 'UK'")

Z = DVarP("[Freight]", "Orders", "[Ship Via] = 1")

If domain refers to fewer than two records, or if fewer than two records satisfy criteria, DVar and DVarP return a Null (which indicates that a variance can't be calculated).


vbfctDVarSee
See Also

Domain Aggregate Functions (SQL Only)

SQL Aggregate Functions

Using SQL (Structured Query Language)

Visual Basic SQL Keywords


vbfctDVarEx
DVar, DVarP Functions Example

This example returns estimates of the variance for a population and a population sample for orders shipped to the United Kingdom.  The domain is an Orders table.  The criteria argument restricts the data by making the expression apply only to records in which Ship Country equals UK.

X = DVar("[Freight]", "Orders", "[Ship Country] = 'UK'")  ' Sample estimate.

Y = DVarP("[Freight]", "Orders", "[Ship Country] = 'UK'") ' Population estimate.


parameter query

A query that asks you to enter one or more criteria values, such as "Nairobi" for City, before the query is run.  A parameter query is not, strictly speaking, a separate kind of query; rather, it extends the flexibility of other queries (except for crosstab queries).


ALL, DISTINCT, DISTINCTROW Predicates (SQL)

See Also	Example

Description

When you use a SELECT or SELECT...INTO statement, you include all records unless you also use a WHERE clause.

You can also use the ALL, DISTINCT, or DISTINCTROW predicate.  These predicates are optional but when included follow SELECT.  When used, DISTINCT and DISTINCTROW are applied to the query output after all other clauses in the SQL statement.

ALL

If you don't include one of the predicates, ALL is assumed, and all of the records that meet the conditions in the SQL statement are returned.  The following two examples are equivalent and return all records from the Employees table:

SELECT ALL *
FROM Employees
ORDER BY [Employee ID]

SELECT *
FROM Employees
ORDER BY [Employee ID]

DISTINCT

Use DISTINCT when you want to omit records that contain duplicate data in the selected fields.  To appear in the results of the query, the values for each field listed in the SELECT statement must be unique.  For example, several employees listed in an Employees table may have the same last name.  If two records contain Smith in the Last Name field, the following SQL statement returns only one of the records:

SELECT DISTINCT [Last Name]
FROM Employees
WHERE [Last Name] = 'Smith';

If you omit DISTINCT, this query selects both Smith records.

The output of a query that uses DISTINCT is not updatable and doesn't reflect subsequent changes made by other users.

DISTINCTROW

Use DISTINCTROW when you want to omit data based on entire duplicate records, not just duplicate fields.  For example, you might create a query that joins the Customers and Orders tables on the Customer ID field.  The Customers table contains no duplicate Customer ID fields, but the Orders table does because each customer can have many orders.  The following SQL statement shows how you can use DISTINCTROW to produce a list of companies that have at least one order, but without any details about those orders:

SELECT DISTINCTROW [Company Name]
FROM Customers, Orders,
Customers INNER JOIN Orders
ON Customers.[Customer ID] = Orders.[Customer ID]
ORDER BY [Company Name];

If you omit DISTINCTROW, this query produces multiple rows for each company that has more than one order.

DISTINCTROW has an effect only when you select fields from some, but not all, of the tables used in the query.  DISTINCTROW is ignored if your query includes only one table.

Provided you don't select any fields from the "many" table, you can use DISTINCTROW to allow changes to the "one" table in a one-to-many relationship.  For example, the following SQL statement permits the Comments field to be changed for customers who have large orders:

SELECT DISTINCTROW Customers.[Customer ID], Comments
FROM Customers, Orders,
Customers INNER JOIN Orders
ON Customers.[Customer ID] = Orders.[Customer ID]
WHERE [Order Amount] > 10000

Removing DISTINCTROW or replacing it with ALL or DISTINCT would prevent you from changing the comments, because the Customers table is on the "one" side of a one-to-many relationship.  Including DISTINCTROW makes the "many" table read-only, but the "one" table would be updatable.


sqlAllDistinctSee
See Also

Help:

Visual Basic SQL Keywords

Using SQL (Structured Query Language)

Data Access Guide:

Appendix B, "Microsoft Access SQL"


sqlAllDistinctExamples
ALL, DISTINCT, DISTINCTROW Predicates Examples

The following examples use two tables, Customers and Orders.

Customers Table

First Name	Customer ID

Bob	1

Adam	2

Beverly	3

Bob	4

Orders Table

Customer ID	Order ID

1	1

1	2

2	3

2	4

2	5

4	6

4	7

SQL statement	Result	Updatable
SELECT ALL [First Name]  FROM Customers, Orders,  Customers INNER JOIN Orders  ON Customers.[Customer ID] = Orders.[Customer ID]	Bob Bob Adam Adam Adam Bob Bob	No
SELECT DISTINCT [First Name]  FROM Customers, Orders,  Customers INNER JOIN Orders  ON Customers.[Customer ID] = Orders.[Customer ID]	Bob Adam	No
SELECT DISTINCTROW [First Name]  FROM Customers, Orders,  Customers INNER JOIN Orders  ON Customers.[Customer ID] = Orders.[Customer ID]	Bob Adam Bob	Yes


INNER JOIN Operation (SQL Only)

See Also	Example

You can use an INNER JOIN operation to create an equi-join, which is also known as an inner join.  Equi-joins are the most common type of join.  They combine records from two tables whenever there are matching values in a field common to both tables.

For example, you might use INNER JOIN with the Departments and Employees tables to select all the employees in each department.  In contrast, to select all departments (even if some have no employees assigned to them) or all employees (even if some are not assigned to a department), you might use a LEFT JOIN or RIGHT JOIN operation to create an outer join

INNER JOIN is optional but when included is part of the FROM clause.

You use the following syntax to create an equi-join:

table1 INNER JOIN table2
ON table1.field1 = table2.field2

The arguments table1 and table2 are the names of the tables you want to join.  The arguments table1.field1 and table2.field2 identify the fields in those tables that you want to join on.  Except for numeric fields, the fields must be of the same data type and contain the same kind of data, but they don't have to have the same name.  You can join any two numeric fields, even if they are of different data types.  For example, you can join an Integer field and a Counter field.

The following example shows how you might join the Titles and Publishers tables on the PubID field:

SELECT Title, [Company Name]
FROM Titles, Publishers,
Titles INNER JOIN Publishers
ON Titles.PUBID = Publishers.PUBID

In this example, PUBID is the joined field, but it doesn't appear in the query output because it isn't included in the SELECT statement.  To include the joined field, enter the field name in the SELECT statement [image] in this case, Titles.PUBID.


sqlInnerJoinExample
INNER JOIN Operation Example

SQL statement	Description
SELECT DISTINCTROW  Sum([Unit Price] * [Quantity]) AS [Sales],  [First Name] & " " & [Last Name] AS [Name]  FROM [Order Details], Orders, Employees,  Orders INNER JOIN [Order Details]  ON Orders.[Order ID] = [Order Details].[Order ID],  Employees INNER JOIN Orders  ON Employees.[Employee ID] = Orders.[Employee ID]  GROUP BY [First Name] & " " & [Last Name]	Creates two equi-joins: one between the Order Details and Orders tables, and another between the Orders and Employees tables.  This is necessary because the Employees table doesn't contain sales data, and the Order Details table doesn't contain employee data.  The query produces a list of employees and their total sales.


sqlInnerJoinSee
See Also

Help:

LEFT JOIN (SQL)

RIGHT JOIN

SELECT Clause (SQL)

Visual Basic SQL Keywords

Using SQL (Structured Query Language)

Data Access Guide:

Appendix B, "Microsoft Access SQL"


INSERT INTO Statement (SQL Only)

See Also	Example

Description

You can use INSERT INTO to create an append query, or a query that appends records to one or more tables.

Notes

INSERT INTO is optional but when included precedes the SELECT clause.

If the table you're appending records to includes a primary key, the records you append must have the same field or an equivalent field of the same data type.  If the primary key field is numeric, the records you append must also contain a numeric field.  For example, you can append a record with an Integer primary key to a table that has a Long primary key.

No records are appended if either duplicate or empty values would result in the primary key field.

Use the IN clause to append records to a table in another database.

To create a new table, use the SELECT... INTO statement to create a make-table query.

 An append query copies records from one or more tables to another.  The tables that contain the records you append are not affected by the append query.


sqlInsertIntoSee
See Also

Help:

FROM Clause (SQL)

IN Clause (SQL)

SELECT Clause (SQL)

SELECT... INTO Clause (SQL)

Using SQL (Structured Query Language)

Visual Basic SQL Keywords

WHERE Clause (SQL)

Data Access Guide:

Appendix B, "Microsoft Access SQL"


sqlInsertIntoExample
INSERT INTO Statement Examples

SQL statement	Description
INSERT INTO Customers  SELECT [New Customers].*  FROM [New Customers]	Selects all records in the New Customers table and adds them to the Customers table
INSERT INTO Employees  SELECT Trainees.*  FROM Trainees  WHERE [Hire Date] < Now() - 30	Selects all trainees who were hired more than 30 days ago and adds their records to the Employees table


LEFT JOIN, RIGHT JOIN Operations (SQL Only)

See Also	Example

Use a LEFT JOIN operation to create a left join.  Left joins include all of the records from the first (left-hand) of two tables, even if there are no matching values for records in the second (right-hand) table.

Use a RIGHT JOIN operation to create a right join.  Right joins include all of the records from the second (right-hand) of two tables, even if there are no matching values for records in the first (left-hand) table.

For example, you might use LEFT JOIN with the Departments (left) and Employees (right) tables to select all departments, including those that have no employees assigned to them.  To select all employees, including those who aren't assigned to a department, you would use RIGHT JOIN.

To create a query that includes only records in which the data in the joined fields is the same, use an INNER JOIN operation.

LEFT JOIN and RIGHT JOIN are optional but when included are part of the FROM clause.

You use the following syntax to create a left or right join:

table1 LEFT JOIN table2
ON table1.field1 = table2.field2

table1 RIGHT JOIN table2
ON table1.field1 = table2.field2

The arguments table1 and table2 are the names of the tables you want to join.  The arguments table1.field1 and table2.field2 identify the fields in the tables you want to join on.  The fields must be of the same data type and contain the same kind of data, but they don't have to have the same name.

The following example shows how you might join the Titles and Publishers tables on the PubID field. The query produces a list of all titles, including those that contain no publisher.

SELECT Title, [Company Name]
FROM Titles, Publishers,
Titles LEFT JOIN Publishers
ON Titles.PUBID = Publishers.PUBID

In this example, PUBID is the joined field, but it doesn't appear in the query output because it isn't included in the SELECT statement.  To include the joined field, enter the field name in the SELECT statement [image] in this case, Titles.PUBID.


sqlLeftRightJoinExample
LEFT JOIN, RIGHT JOIN Operations Examples

SQL statement	Description
SELECT [Department Name],  [First Name] & " " & [Last Name] AS Name  FROM Departments, Employees,  Departments LEFT JOIN Employees  ON Departments.[Department ID] = Employees.[Department ID]  ORDER BY [Department Name]	Selects all departments, including those without employees
SELECT [Last Name] & ", " & [First Name]  AS Name, [Department Name]  FROM Departments, Employees,  Departments RIGHT JOIN Employees  ON Departments.[Department ID] = Employees.[Department ID]  ORDER BY [Last Name] & ", " & [First Name]	Selects all employees, including those not assigned to a department


sqlLeftRightJoinSee
See Also

Help:

Visual Basic SQL Keywords

Using SQL (Structured Query Language)

Data Access Guide:

Appendix B, "Microsoft Access SQL"


PARAMETERS Declaration (SQL Only)

See Also	Example

For queries that you run regularly, you can use a PARAMETERS declaration to create a parameter query.  A parameter query can help automate the process of changing query criteria.  With a parameter query,  you can set new values for the parameters each time the query is run.

In the Professional Edition only, you can set QueryDef parameters with the following syntax:

querydef ! parametername = parametertext

The PARAMETERS declaration is optional but when included precedes any other statement, including SELECT.

You use the following syntax to declare a parameter:

PARAMETERS parametertext datatype

The argument parametertext is the name of the parameter you use in the SQL statement.  Use brackets to enclose text that contains spaces or punctuation.  For example, [Low price] and [Begin report with which month?] are valid entries for parametertext.

The argument datatype is the parameter's field data type.

If the declaration includes more than one parametertext-datatype pair, separate them with commas.  The following example includes two parameters:

PARAMETERS [Low price] Currency,
[Beginning date] DateTime

You can use parametertext but not datatype in places such as a WHERE or HAVING clause.  The following example requires that your program supply two parameters and then applies the criteria to records in the Orders table:

PARAMETERS [Low price] Currency, [Beginning date] DateTime;
SELECT [Order ID], [Order Amount]
FROM Orders
WHERE [Order Amount] > [Low price]
AND [Order Date] >= [Beginning date]


sqlParametersSee
See Also

Help:

HAVING Clause (SQL)

SELECT Clause (SQL)

Using SQL (Structured Query Language)

Visual Basic SQL Keywords

WHERE Clause (SQL)

Data Access Guide:

Appendix B, "Microsoft Access SQL"


sqlParametersExample
PARAMETERS Declaration Examples

SQL statement	Description
PARAMETERS [Enter a Last Name:] Text;  SELECT *  FROM Employees  WHERE [Enter a Last Name:] = [Last Name]	Requries that your program provide the parameter and then uses that parameter as the criteria for the query
PARAMETERS [Enter a category ID:] Text;  SELECT DISTINCTROW  [Category ID], [Product Name],  Count([Order Details].[Order ID]) AS Tally  FROM Products, [Order Details], Products INNER JOIN [Order Details]  ON Products.[Product ID] = [Order Details].[Product ID]  GROUP BY [Category ID], [Product Name]  HAVING [Category ID] = [Enter a category ID:]	Requries that your program provide the category ID parameter and then uses that entry as the criteria for the query


PROCEDURE Clause (SQL Only)

See Also	Example

Description

An SQL procedure consists of a PROCEDURE clause (which specifies the name of the procedure), a list of parameter definitions, and a single SQL statement.  For example, the procedure Get_Part_Number might execute a query that retrieves a specified part number.

This version of SQL implements PROCEDURE for compatibility with SQL statements you might copy from other applications.  If you use a PROCEDURE clause, don't use the PARAMETERS declaration to specify query parameters.

Notes

PROCEDURE is optional but when included is the first clause in the SQL statement.

A PROCEDURE clause has the following syntax:

PROCEDURE procedurename [parametername parameterdatatype];

The name procedurename must follow standard naming conventions.

If the clause includes more than one parametername-parameterdatatype pair, separate them with commas.  The following are valid PROCEDURE clauses:

PROCEDURE List_Employees;

PROCEDURE Sales_By_Country [Beginning Date] DateTime, [Ending Date] 	DateTime;

When you use a PROCEDURE clause, Visual Basic removes the clause from the SQL statement.  Removing the PROCEDURE clause doesn't affect the result of the query.  If the PROCEDURE clause includes parameters, Visual Basic replaces PROCEDURE and procedurename with the PARAMETERS reserved word; the parameters are not removed.


sqlProcedureSee
See Also

Help:

PARAMETERS Declaration (SQL)

Using SQL (Structured Query Language)

Visual Basic SQL Keywords

Data Access Guide:

Appendix B, "Microsoft Access SQL"


sqlProcedureExample
PROCEDURE Clause Examples

SQL statement	Description
PROCEDURE Category_List;  SELECT DISTINCTROW  [Category Name], [Category ID]  FROM Categories  ORDER BY [Category Name]	Names the query Category_List, and the PROCEDURE clause is removed.
PROCEDURE Summary  [Beginning Date] DateTime,  [Ending Date] DateTime;  SELECT DISTINCTROW  [Shipped Date], [Order ID], [Order Amount],  Format([Shipped Date], "yyyy")  AS Year  FROM Orders  WHERE [Shipped Date]  Between [Beginning Date] And [Ending Date]	Names the query Summary and includes two parameters.  The PROCEDURE clause is changed to the following PARAMETERS declaration: PARAMETERS [Beginning Date] DateTime, [Ending Date] DateTime;


TRANSFORM Statement (SQL Only)

See Also	Example

You can use the TRANSFORM statement to create a crosstab query.  When you summarize data using a crosstab query, you select values from a specified field or expression as column headers so you can view data in a more compact format than a select query would produce.

TRANSFORM is optional but when included is usually the first statement in an SQL string.  It precedes the SELECT statement.

A TRANSFORM statement has the following syntax:

TRANSFORM  aggregatefunction
sqlstatement
PIVOT pivotcolumn

The argument aggregatefunction is an aggregate function that provides the data for pivotcolumn.

The argument sqlstatement includes a SELECT statement that specifies the fields used as row headings and a GROUP BY clause that specifies row grouping.  Optionally, you can include other clauses, such as WHERE, that specify additional selection or sorting criteria.

The argument pivotcolumn refers to the field, column, or expression you want to pivot (rotate) to form the column headings.  When you pivot a field, the unique values of pivotcolumn become columns.  For example, pivoting the sales figures on the month of the sale in a crosstab query would create twelve columns.


sqlTransformSee
See Also

Help:

FROM Clause (SQL)

GROUP BY Clause (SQL)

INNER JOIN Operation (SQL)

ORDER BY Clause (SQL)

SELECT Clause (SQL)

Using SQL (Structured Query Language)

Visual Basic SQL Keywords

WHERE Clause (SQL)

Data Access Guide:

Appendix B, "Microsoft Access SQL"


sqlTransformExample
TRANSFORM Statement Examples

SQL statement	Description
PARAMETERS [Sales for which year?] Long;  TRANSFORM Sum([Order Amount]) AS Sales  SELECT [Product Name]  FROM Orders, Products, [Order Details],  Orders INNER JOIN [Order Details]  ON Orders.[Order ID] = [Order Details].[Order ID],  Products INNER JOIN [Order Details]  ON Products.[Product ID] = [Order Details].[Product ID]  WHERE DatePart("yyyy", [Order Date]) = [Sales for which year?]  GROUP BY [Product Name]  ORDER BY [Product Name]  PIVOT DatePart("m", [Order Date])	Creates a crosstab query that shows product sales by month for an application-specified year.  The months appear from left to right (pivoted) as columns, and the product names appear from top to bottom as rows.
PARAMETERS [Sales for which year?] Long;  TRANSFORM Sum([Order Amount]) AS Sales  SELECT [Company Name]  FROM Orders, Products, [Order Details], Suppliers,  Orders INNER JOIN [Order Details]  ON Orders.[Order ID] = [Order Details].[Order ID],  Products INNER JOIN [Order Details]  ON Products.[Product ID] = [Order Details].[Product ID],  Suppliers INNER JOIN Products  ON Suppliers.[Supplier ID] = Products.[Supplier ID]  WHERE DatePart("yyyy", [Order Date]) = [Sales for which year?]  GROUP BY [Company Name]  ORDER BY [Company Name]  PIVOT "Qtr " & DatePart("q", [Order Date])  In ('Qtr1', 'Qtr2', 'Qtr 3', 'Qtr 4')	Creates a crosstab query that shows product sales by quarter for each supplier for an application-specified year.  The quarters appear from left to right (pivoted) as columns, and the supplier names appear from top to bottom as rows.


WITH OWNERACCESS OPTION Declaration (SQL Only)

See Also

Description

In a multiuser environment with a secure system, use WITH OWNERACCESS OPTION to give the user who runs the query permission to view the data in the query even if he or she is otherwise restricted from viewing the query's underlying tables.

Notes

WITH OWNERACCESS OPTION is optional but when included usually follows ORDER BY.  The following example allows salary information to be accessed, even if the user doesn't otherwise have permission to read the Payroll table.

SELECT [Last Name], [First Name], Salary
FROM Employees, Payroll
ORDER BY [Last Name]
WITH OWNERACCESS OPTION

If a user is otherwise prevented from creating or adding to a table, you can use WITH OWNERACCESS OPTION to allow the user to run a make-table or append query.

If you want to enforce system security settings and users' permissions, don't include the WITH OWNERACCESS OPTION declaration.


sqlWithOwnerAccessOptionSee
See Also

Help:

FROM Clause (SQL)

SELECT Clause (SQL)

Using SQL (Structured Query Language)

Visual Basic SQL Keywords

WHERE Clause (SQL)

Data Access Guide:

Appendix B, "Microsoft Access SQL"


Equivalent SQL Data Types

The following table lists the equivalent Microsoft SQL and ANSI SQL data types.

Microsoft  SQL	ANSI SQL
BINARY	Not supported
BOOLEAN	Not supported
BYTE	Not supported
CURRENCY	Not supported
DATETIME	Not supported
DOUBLE	REAL
LONG	INT[EGER]
LONGBINARY	Not supported
LONGTEXT	VARCHAR
SHORT	SMALLINT
SINGLE	FLOAT
TEXT	CHAR[ACTER]
Not supported	NUMBER
Not supported	NUMERIC
Not supported	DECIMAL
Not supported	DOUBLE PRECISION
Not supported	PICTURE


In Operator
In Operator (SQL Only)

See Also

Description

Determines whether the value of an expression is equal to any of several values in a specified list.  This operator can only be used within SQL statements.

Syntax

expr [Not] In (value1, value2,  . . .)

Remarks

The In operator uses the following arguments.

Argument	Description

expr	Expression identifying the field that contains the data you want to evaluate

value1, value2	Expression or list of expressions against which you want to evaluate expr

If expr is found in the list of values, the In operator returns True; otherwise, it returns False.  You can include the Not logical operator to evaluate the opposite condition (that is, whether expr is not in the list of values).

You might use In to determine whether the value of a control is in a set of specified regions.  The following example shows how you can tell if an order is shipped to a western region.  If the State is WA, CA, or OR, the IIf function returns "West".  Otherwise, it returns "Non-West".

Select IIf([State] In ('WA','CA','OR'), "West", "Non-West")
From Publishers

If expr or any of the entries in the list of values is Null, In returns a Null.


vboprInOperatorSee
See Also

Between...And Operator (SQL Only)

IIf Function

Using SQL (Structured Query Language)

Visual Basic SQL Keywords


Between...And Operator
Between...And Operator (SQL Only)

See Also

Description

Determines whether the value of an expression lies within a specified range of values.  This operator can only be used within SQL statements.

Syntax

expr [Not] Between value1 And value2

Remarks

The Between...And operator uses the following arguments.

Argument	Description

expr	Expression identifying the field that contains the data you want to evaluate

value1, value2	Expressions against which you want to evaluate expr

If the value of expr is between value1 and value2 (inclusive), the Between...And operator returns True; otherwise, it returns False.  You can include the Not logical operator to evaluate the opposite condition (that is, whether expr lies outside the range defined by value1 and value2).

You might use Between...And to determine whether the value of a field falls within a specified numeric range.  The following example determines whether an order was shipped to a location within a range of ZIP codes.  If the ZIP Code is between 98101 and 98199, the IIf function returns "Local".  Otherwise, it returns "Nonlocal".

SELECT IIf([ZIP] Between 98101 And 98199, "Local", "Nonlocal")
FROM Publishers

If expr, value1, or value2 is Null, Between...And returns a Null.


vboprBetweenAndSee
See Also

IIf Function

In Operator (SQL Only)

Using SQL (Structured Query Language)

Visual Basic SQL Keywords


Financial Functions

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


DDB Function

See Also	Example

Description

Returns the depreciation of an asset for a specific period using the double-declining balance method.

Syntax

DDB(cost, salvage, life, period)

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 DDB function uses the following numeric arguments:

Argument	Description

cost	Initial cost of the asset.

salvage	Value of the asset at the end of its useful life.

life	Length of the useful life of the asset.

period	Period for which asset depreciation is calculated.

The arguments life and period 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:

Depreciation over period = ((cost [image] total depreciation from prior periods) * 2) / life

Distribution Note   When you create and distribute applications that use any of the financial functions, you should install the file MSAFINX.DLL in the customer's Microsoft Windows \SYSTEM directory.  The Visual Basic Setup Kit provides tools to help you write setup programs that install your applications.


DDB Function See Also
See Also

Financial Functions

SLN Function

SYD Function


DDB Function Example

Using the double-declining balance method, this example returns 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 for which the depreciation is calculated (Depr), also in years.

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) & "."


FV Function

See Also	Example

Description

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

Syntax

FV(rate, nper, pmt, pv, due)

Remarks

An annuity is a series of constant 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 FV function uses the following numeric arguments:

Argument	Description

rate	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	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	Payment to be made each period.  Payments usually contain principal and interest that doesn't change over the life of the annuity.

pv	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.

due	Number indicating when payments are due. Use 0 if payments are due at the end of the payment period, and use 1 if payments are due at the beginning of the period.

The arguments rate and nper 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.

Distribution Note   When you create and distribute applications that use any of the financial functions, you should install the file MSAFINX.DLL in the customer's Microsoft Windows \SYSTEM directory.  The Visual Basic Setup Kit provides tools to help you write setup programs that install your applications.


FV Function See Also
See Also

Financial Functions

IPmt Function

NPer Function

Pmt Function

PPmt Function

PV Function

Rate Function


FV Function Example

This example returns 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 Pmt represents cash paid out, it's a negative number.

Const ENDPERIOD = 0, BEGINPERIOD = 1	' When payments are made.
Const MB_YESNO = 4	' Define Yes/No buttons.
Const ID_NO = 7	' Define No as a response.
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?", MB_YESNO)
If PayType = ID_NO 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) & "."


IPmt Function

See Also	Example

Description

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

Syntax

IPmt(rate, per, nper, pv, fv, due)

Remarks

An annuity is a series of constant 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 IPmt function uses the following numeric arguments:

Argument	Description

rate	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	Payment period in the range 1 through nper.

nper	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	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	Future value or cash balance you want after you've made the final payment.  The future value of a loan, for instance, is $0.  As another example, if you will need $50,000 in 18 years to pay for your child's education, then $50,000 is the future value.

due	Number indicating when payments are due. Use 0 if payments are due at the end of the payment period, and use 1 if payments are due at the beginning of the period.

The arguments rate and nper 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.

Distribution Note   When you create and distribute applications that use any of the financial functions, you should install the file MSAFINX.DLL in the customer's Microsoft Windows \SYSTEM directory.  The Visual Basic Setup Kit provides tools to help you write setup programs that install your applications.


IPmt Function See Also
See Also

Financial Functions

FV Function

NPer Function

Pmt Function

PPmt Function

PV Function

Rate Function


IPmt Function Example

This example calculates 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).

Const ENDPERIOD = 0, BEGINPERIOD = 1	' When payments are made.
Const MB_YESNO = 4	' Define Yes/No buttons.
Const ID_NO = 7	' Define No as a response.
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?", MB_YESNO)
If PayType = ID_NO 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

See Also	Example

Description

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

Syntax

IRR(valuearray( ), guess)

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 following arguments:

Argument	Description

valuearray( )	Array containing cash flow values.  The array must contain at least one negative value (a payment) and one positive value (a receipt).

guess	Value you guess will be returned by IRR.  In most cases, guess is 0.1 (10 percent).

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 constant, as it would 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, after 20 tries, it can't find a result, IRR fails.

Because the IRR function requires an array of cash flows, it cannot be used as an expression on a form.

Distribution Note   When you create and distribute applications that use any of the financial functions, you should install the file MSAFINX.DLL in the customer's Microsoft Windows \SYSTEM directory.  The Visual Basic Setup Kit provides tools to help you write setup programs that install your applications.


IRR Function See Also
See Also

Financial Functions

MIRR Function

NPV Function

Rate Function


IRR Function Example

This example returns the internal rate of return for a series of five cash flows contained in the array Values().  The first array element is a negative cash flow representing business start-up costs.  The remaining four cash flows represent positive cash flows for the subsequent four years.  Guess is the estimated internal rate of return.

Static Values(5) As Double	' Set up array.
Guess = .1	' Guess starts at 10%.
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.


MIRR Function

See Also	Example

Description

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

Syntax

MIRR(valuearray( ), financerate, reinvestrate)

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 (financerate) and the interest rate received on reinvestment of cash (reinvestrate).

The MIRR function uses the following arguments:

Argument	Description

valuearray( )	Array of cash flow values.  The array must contain at least one negative value (a payment) and one positive value (a receipt).

financerate	Interest rate paid as the cost of financing.

reinvestrate	Interest rate received on gains from cash reinvestment.

The arguments financerate and reinvestrate 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.

Because the MIRR function requires an array of cash flows, it can't be used as an expression on a form.

Distribution Note   When you create and distribute applications that use any of the financial functions, you should install the file MSAFINX.DLL in the customer's Microsoft Windows \SYSTEM directory.  The Visual Basic Setup Kit provides tools to help you write setup programs that install your applications.


MIRR Function See Also
See Also

Financial Functions

IRR Function

Rate Function


MIRR Function Example

This example returns 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.

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.


NPer Function

See Also	Example

Description

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

Syntax

NPer(rate, pmt, pv, fv, due)

Remarks

An annuity is a series of constant 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 NPer function uses the following numeric arguments:

Argument	Description

rate	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	Payment to be made each period.  Payments usually contain principal and interest that doesn't change over the life of the annuity.

pv	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	Future value or cash balance you want after you've made the final payment.  The future value of a loan, for instance, is $0.  As another example, if you will need $50,000 in 18 years to pay for your child's education, then $50,000 is the future value.

due	Number indicating when payments are due.  Use 0 if payments are due at the end of the payment period, and use 1 if payments are due at the beginning of the period.

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.

Distribution Note   When you create and distribute applications that use any of the financial functions, you should install the file MSAFINX.DLL in the customer's Microsoft Windows \SYSTEM directory.  The Visual Basic Setup Kit provides tools to help you write setup programs that install your applications.


NPer Function See Also
See Also

Financial Functions

FV Function

IPmt Function

Pmt Function

PPmt Function

PV Function

Rate Function


NPer Function Example

This example returns the number of periods over 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).

Const ENDPERIOD = 0, BEGINPERIOD = 1	' When payments are made.
Const MB_YESNO = 4	' Define Yes/No buttons.
Const ID_NO = 7	' Define No as a response.
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?", MB_YESNO)
If PayType = ID_NO 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

See Also	Example

Description

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

Syntax

NPV(rate, valuearray( ))

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 following arguments:

Argument	Description

rate	Discount rate over the length of the period, expressed as a decimal.

valuearray( )	Array of cash flow values.  The array must contain at least one negative value (a payment) and one positive value (a receipt).

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 valuearray( ).

The  NPV function differs from the PV function in the following ways:

Function	Payments due	Cash flow
NPV	At the end of the period.	Is variable.
PV	At the end or beginning of the period.	Is constant.
Because the NPV function requires an array of cash flows, it can't be used as an expression on a form.

Distribution Note   When you create and distribute applications that use any of the financial functions, you should install the file MSAFINX.DLL in the customer's Microsoft Windows \SYSTEM directory.  The Visual Basic Setup Kit provides tools to help you write setup programs that install your applications.


NPV Function See Also
See Also

Financial Functions

FV Function

IRR Function

PV Function


NPV Function Example

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

Static Values(5) As Double	' Set up array.
Fmt = "###,##0.00"	' Define money format.
Guess = .1	' Guess starts at 10%.
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.


Pmt Function

See Also	Example

Description

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

Syntax

Pmt(rate, nper, pv, fv, due)

Remarks

An annuity is a series of constant 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 Pmt function uses the following numeric arguments:

Argument	Description

rate	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	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	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	Future value or cash balance you want after you've made the final payment.  The future value of a loan, for instance, is $0.  As another example, if you will need $50,000 in 18 years to pay for your child's education, then $50,000 is the future value.

due	Number indicating when payments are due.  Use 0 if payments are due at the end of the payment period, and use 1 if payments are due at the beginning of the period.

The arguments rate and nper 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.

Distribution Note   When you create and distribute applications that use any of the financial functions, you should install the file MSAFINX.DLL in the customer's Microsoft Windows \SYSTEM directory.  The Visual Basic Setup Kit provides tools to help you write setup programs that install your applications.


Pmt Function See Also
See Also

Financial Functions

FV Function

IPmt Function

NPer Function

PPmt Function

PV Function

Rate Function


Pmt Function Example

This example returns the 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).

Const ENDPERIOD = 0, BEGINPERIOD = 1	' When payments are made.
Const MB_YESNO = 4	' Define Yes/No buttons.
Const ID_NO = 7	' Define No as a response.
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?", MB_YESNO)
If PayType = ID_NO 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

See Also	Example

Description

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

Syntax

PPmt(rate, per, nper, pv, fv, due)

Remarks

An annuity is a series of constant 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 PPmt function uses the following numeric arguments:

Argument	Description

rate	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	Payment period in the range 1 through nper.

nper	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	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	Future value or cash balance you want after you've made the final payment.  The future value of a loan, for instance, is $0.  As another example, if you will need $50,000 in 18 years to pay for your child's education, then $50,000 is the future value.

due	Number indicating when payments are due. Use 0 if payments are due at the end of the payment period, and use 1 if payments are due at the beginning of the period.

The arguments rate and nper 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.

Distribution Note   When you create and distribute applications that use any of the financial functions, you should install the file MSAFINX.DLL in the customer's Microsoft Windows \SYSTEM directory.  The Visual Basic Setup Kit provides tools to help you write setup programs that install your applications.


PPmt Function See Also
See Also

Financial Functions

FV Function

IPmt Function

NPer Function

Pmt Function

PV Function

Rate Function


PPmt Function Example

This example calculates 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).

Const ENDPERIOD = 0, BEGINPERIOD = 1	' When payments are made.
Const MB_YESNO = 4	' Define Yes/No buttons.
Const ID_NO = 7	' Define No as a response.
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?", MB_YESNO)
If PayType = ID_NO 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, MB_YESNO)	' See if chart is desired.
If MakeChart <> ID_NO Then
If TotPmts > 25 Then MsgBox "Only first 25 periods will be shown."
Msg = "Month  Payment  Principal  Interest" & NL
For Period = 1 To TotPmts
If Period > 25 Then Exit For	' Show only first 25.
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

See Also	Example

Description

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

Syntax

PV(rate, nper, pmt, fv, due)

Remarks

An annuity is a series of constant 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 PV function uses the following numeric arguments:

Argument	Description

rate	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	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	Payment to be made each period.  Payments usually contain principal and interest that doesn't change over the life of the annuity.

fv	Future value or cash balance you want after you've made the final payment.  The future value of a loan, for instance, is $0.  As another example, if you will need $50,000 in 18 years to pay for your child's education, then $50,000 is the future value.

due	Number indicating when payments are due. Use 0 if payments are due at the end of the payment period, and use 1 if payments are due at the beginning of the period.

The arguments rate and nper 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.

Distribution Note   When you create and distribute applications that use any of the financial functions, you should install the file MSAFINX.DLL in the customer's Microsoft Windows \SYSTEM directory.  The Visual Basic Setup Kit provides tools to help you write setup programs that install your applications.


PV Function See Also
See Also

Financial Functions

FV Function

IPmt Function

NPer Function

Pmt Function

PPmt Function

Rate Function


PV Function Example

This example 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 (20), the amount of each payment (YrIncome), the total future value of the investment (FVal), and a number that indicates whether the payment is made at the beginning or end of the payment period (PayType).  Note that because YrIncome represents cash paid out from the annuity each year, it's a negative number.

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) & "."


Rate Function

See Also	Example

Description

Returns the interest rate per period for an annuity.

Syntax

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

Remarks

An annuity is a series of constant 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 function uses the following numeric arguments:

Argument	Description

nper	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	Payment to be made each period.  Payments usually contain principal and interest that doesn't change over the life of the annuity.

pv	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	Future value or cash balance you want after you've made the final payment.  The future value of a loan, for instance, is $0.  As another example, if you will need $50,000 in 18 years to pay for your child's education, then $50,000 is the future value.

due	Number indicating when payments are due. Use 0 if payments are due at the end of the payment period, and use 1 if payments are due at the beginning of the period.

guess	Value you guess will be returned by Rate.  In most cases, guess is 0.1 (10 percent).

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, after 20 tries, it can't find a result, Rate fails.  If your guess is 10 percent and Rate fails, try a different value for guess.

Distribution Note   When you create and distribute applications that use any of the financial functions, you should install the file MSAFINX.DLL in the customer's Microsoft Windows \SYSTEM directory.  The Visual Basic Setup Kit provides tools to help you write setup programs that install your applications.


Rate Function See Also
See Also

Financial Functions

FV Function

IPmt Function

NPer Function

Pmt Function

PPmt Function

PV Function


Rate Function Example

This example calculates 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).

Const ENDPERIOD = 0, BEGINPERIOD = 1	' When payments are made.
Const MB_YESNO = 4	' Define Yes/No buttons.
Const ID_NO = 7	' Define No as a response.
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?", MB_YESNO)
If PayType = ID_NO 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."


SLN Function

See Also	Example

Description

Returns the straight-line depreciation of an asset for a single period.

Syntax

SLN(cost, salvage, life)

Remarks

The SLN function uses the following numeric arguments:

Argument	Description

cost	Initial cost of the asset.

salvage	Value of the asset at the end of its useful life.

life	Length of the useful life of the asset.

The period for which the depreciation is returned is expressed in the same unit of time as the useful life of the asset.  All arguments must be positive numbers.

Distribution Note   When you create and distribute applications that use any of the financial functions, you should install the file MSAFINX.DLL in the customer's Microsoft Windows \SYSTEM directory.  The Visual Basic Setup Kit provides tools to help you write setup programs that install your applications.


SLN Function See Also
See Also

Financial Functions

DDB Function

SYD Function


SLN Function Example

This example returns 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).

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."


SYD Function

See Also	Example

Description

Returns the sum-of-years' digits depreciation of an asset for a specified period.

Syntax

SYD(cost, salvage, life, period)

Remarks

The SYD function uses the following numeric arguments:

Argument	Description

cost	Initial cost of the asset.

salvage	Value of the asset at the end of its useful life.

life	Length of the useful life of the asset.

period	Period for which asset depreciation is calculated.

The arguments life and period 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.

Distribution Note   When you create and distribute applications that use any of the financial functions, you should install the file MSAFINX.DLL in the customer's Microsoft Windows \SYSTEM directory.  The Visual Basic Setup Kit provides tools to help you write setup programs that install your applications.


SYD Function See Also
See Also

Financial Functions

DDB Function

SLN Function


SYD Function Example

Using the sum-of-years' digits method, this example returns 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), the total life of the asset in years (LifeTime), and the period for which the depreciation is calculated (PDepr), also in years.

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) & "."


Choose Function

See Also	Example

Description

Selects and returns a value from a list of arguments.

Syntax

Choose( indexnum, varexpr [,varexpr ] . . .)

Remarks

The Choose function uses the following parts:

Part	Description

indexnum	Numeric expression or field that results in a value between 1 and the number of varexpr expressions following indexnum.

varexpr	Variant expression.  You can include a maximum of 13 expressions.

You can use Choose to look up one value in a list of possibilities.  For example, if indexnum evaluates to 3 and the varexpr list is "one," "two," "three," then Choose returns "three."  This is particularly useful if indexnum represents the value in an option group.

Choose returns the varexpr determined by the value of indexnum.  If indexnum is 1, Choose returns the first varexpr; if indexnum is 2, it returns the second, and so on.

Choose evaluates every varexpr, even though it returns only one.  For this reason, you should watch for undesirable side effects.  For example, don't have a MsgBox function in each varexpr because they will all be displayed.

The Choose function returns a Null value if indexnum is less than 1 or greater than the number of expressions in the varexpr list.

Following the rules for the Fix function, indexnum is rounded to the nearest whole number.


vbfctChooseSee
See Also

Fix Function

IIf Function


vbfctChooseEx
Choose Function Example

The example displays a name in response to choosing an option button.  To try this example, draw a label and an option button on a blank form.  Set the Name property of the option button to "Opt" and the Index property to 0.  Paste the code over the Form_Load procedure and then press F5 to run the program.

Sub Form_Load ()
Opt(0).Caption = "Shipper 1"
Load Opt(1)
Opt(1).Caption = "Shipper 2"
Opt(1).Top = Opt(0).Top + Opt(1).Height * 1.5
Opt(1).Visible = True
Load Opt(2)
Opt(2).Caption = "Shipper 3"
Opt(2).Top = Opt(1).Top + Opt(1).Height * 1.5
Opt(2).Visible = True
Opt(0).Value = True
End Sub

Sub Option1_Click (Index As Integer)
Label1.Caption = "Shipper: " & Choose(Index, "Speedy", "United", "Federal")
End Sub


DateAdd Function

See Also	Example

Description

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

Syntax

DateAdd( interval, number, date )

Remarks

The DateAdd function uses the following parts:

Part	Description

interval	String expression that is the interval of time you want to add.

number	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).

date	Date being added to, or the name of a Variant containing a valid date.

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

The following table lists the valid time periods and their interval values.  These intervals are also used by the Format function.

Time period	Interval

Year	yyyy

Quarter	q

Month	m

Day of Year	y

Day	d

Weekday	w

Week	ww

Hour	h

Minute	n

Second	s

If you want to add days to date, you can use Day of Year, Day, or Weekday ("y," "d," or "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 date is 31-Jan-96, it returns 29-Feb-96 because 1996 is a leap year.

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

If number isn't a Long value, DateAdd follows the rules for the Fix function and rounds number to the nearest whole number.

Distribution Note   When you create and distribute applications that use this function in your code, you should install the file MSAFINX.DLL in the customer's Microsoft Windows \SYSTEM directory.  The Visual Basic Setup Kit provides tools to help you write setup programs that install your applications.


vbfctDateAddSee
See Also

DateDiff Function

DatePart Function

Day Function

Fix Function

Format Function

Now Function

Weekday Function

Year Function


vbfctDateAddEx
DateAdd Function Example

The example takes a date and displays a corresponding date a specified number of days in the future.  To try this example, draw two text boxes, a label, and a command button on a new form.  Set the AutoSize property of the Label to True.  Paste this code over the Form_Load procedure and then press F5 to run the program.

Sub Command1_Click ()
Label1.Caption = "New date: " & DateAdd("d", Text2.Text, Text1.Text)
End Sub


DateDiff Function

See Also	Example

Description

Returns a Variant containing the number of time intervals between two specified dates.

Syntax

DateDiff( interval, date1, date2 )

Remarks

The DateDiff function uses the following parts:

Part	Description

interval	String expression that is the interval of time you use to calculate the difference between date1 and date2.

date1, date2	Two dates you want to use in the calculation.

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.

The following table lists the valid time periods and their interval values.  These intervals are also used by the Format function.

Time period	Interval

Year	yyyy

Quarter	q

Month	m

Day of Year	y

Day	d

Weekday	w

Week	ww

Hour	h

Minute	n

Second	s

If you want to know the number of days between date1 and date2, you can use either Day of Year or Day ("y" or "d").

When interval is Weekday ("w"), DateDiff returns the number of weeks between the two dates. If date1 falls on a Monday, DateDiff counts the number of Mondays until date2.  It counts date1 but not date2.  If interval is Week ("ww"), however, the DateDiff function returns the number of calendar weeks between the two dates.  It counts the number of Sundays between date1 and date2.  DateDiff counts date1 if it falls on a Sunday; but it doesn't count date2, 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.

Distribution Note   When you create and distribute applications that use this function in your code, you should install the file MSAFINX.DLL in the customer's Microsoft Windows \SYSTEM directory.  The Visual Basic Setup Kit provides tools to help you write setup programs that install your applications.


vbfctDateDiffSee
See Also

DateAdd Function

DatePart Function

Day Function

Fix Function

Format Function

Now Function

Weekday Function

Year Function


vbfctDateDiffEx
DateDiff Function Example

The example displays the number of days between a given date and today.  To try this example, draw a text box, a label, and a command button on a new form.  Set the AutoSize property of the Label to True.  Paste this code over the Form_Load procedure, and then press F5 to run the program.

Sub Command1_Click ()
Label1.Caption = "Days from today: " & DateDiff("d", Now, Text1.Text)
End Sub


DatePart Function

See Also	Example

Description

Returns a specified part of a given date.

Syntax

DatePart( interval, date )

Remarks

The DatePart function uses the following parts:

Part	Description

interval	String expression that is the interval of time you want to return.

date	Date that you want to inspect.

You can use the DatePart function to inspect 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 following table lists the valid time periods and their interval values.  These intervals are also used by the Format function.

Time period	Interval

Year	yyyy

Quarter	q

Month	m

Day of Year	y

Day	d

Weekday	w

Week	ww

Hour	h

Minute	n

Second	s

For Weekday, Sunday = 1, Monday = 2, and so on.

Distribution Note   When you create and distribute applications that use this function in your code (not necessary if included only in SQL statements for your database), you should install the file MSAFINX.DLL in the customer's Microsoft Windows \SYSTEM directory.  The Visual Basic Setup Kit provides tools to help you write setup programs that install your applications.


vbfctDatePartSee
See Also

DateAdd Function

DateDiff Function

Day Function

Fix Function

Format Function

Now Function

Weekday Function

Year Function


vbfctDatePartEx
DatePart Function Example

The example takes a date and displays which quarter of the year it falls in.  To try this example, draw a text box, a label, and a command button on a new form.  Set the AutoSize property of the Label to True.  Paste this code over the Form_Load procedure, and then press F5 to run the program.

Sub Command1_Click ()
Label1.Caption = "Quarter: " & DatePart("q", Text1.Text)
End Sub


Partition Function

See Also	Example 1	Example 2	Example 3

Description

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

Syntax

Partition( number, start, stop, interval )

Remarks

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

The Partition function uses the following parts:

Part	Description

number	Long number that you want to evaluate against the ranges.

start	Long number that is the start of the overall range of numbers.  It can't be less than 0.

stop	Long number that is the end of the overall range of numbers.  It can't be equal to or less than start.

interval	Long number that is the interval spanned by each range in the series from start to stop.  It can't be less than 1.

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 illustrate the text Partition returns.  The ranges are represented by lowervalue:uppervalue, where the low end (lowervalue) of the range is separated from the high end (uppervalue) 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 this table, 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 the stop part, 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.

Distribution Note   When you create and distribute applications that use this function in your code, you should install the file MSAFINX.DLL in the customer's Microsoft Windows \SYSTEM directory.  The Visual Basic Setup Kit provides tools to help you write setup programs that install your applications.


vbfctPartitionSee
See Also

Data Access


vbfctPartitionEx1
Partition Function Example 1

This example creates a select query that inspects the Order Amount field in an Orders table.  It uses the Partition and the SQL Count functions to evaluate and count the number of orders in each of the ranges.  The ranges are defined by the arguments to Partition:

start = 1, stop = 20000, interval = 1000

You can use the following SQL statement for this example:

SELECT DISTINCTROW Partition([Order Amount], 1, 20000, 1000) AS Range,
Count(Orders.[Order Amount]) AS [Count] FROM Orders
GROUP BY Partition([Order Amount], 1, 20000, 1000)
ORDER BY Partition([Order Amount], 1, 20000, 1000),
Count(Orders.[Order Amount]);

The result of the query could look like the following table.

Range	Count

    1: 1000	588

 1001: 2000	274

 2001: 3000	111

 3001: 4000	38

 4000: 5000	33

 5001: 6000	6

 6001: 7000	8

 7001: 8000	2

 8001: 9000	4

 9001:10000	3

10001:11000	6

11001:12000	2

12001:13000	1

13001:14000	1

16001:17000	1

This table contains no orders for the ranges 14001:15000 and 15001:16000.


vbfctPartitionEx2
Partition Function Example 2

This example creates a select query that inspects the Order Amount field in an Orders table.  For each customer, it calculates the number of orders falling within each of several ranges.  The ranges are defined by the arguments to Partition:

start = 1, stop = 20000, interval = 1000.

You can use the following SQL statement for this example:

SELECT Orders.[Customer ID],
Partition(Int([Order Amount]), 1, 20000, 1000) AS Range,
Count(Orders.[Order ID]) AS [Count]
FROM Orders

GROUP BY Orders.[Customer ID],
Partition(Int([Order Amount]), 1, 20000, 1000);

The result of the select query could look like the following table.

Customer ID	Range	Count

ALWAO	    1: 1000	7

ANDRC	    1: 1000	4

ANTHB	    1: 1000	10

ANTHB	 1001: 2000	2

ANTHB	 2001: 3000	1

AROUT	    1: 1000	9

AROUT	 1001: 2000	3

AROUT	 2001: 3000	1

AROUT	 4001: 5000	1

BABUJ	    1: 1000	10

BABUJ	 1001: 2000	7

BABUJ	 2001: 3000	2

BERGS	    1: 1000	8

:	:	:

In this table, customer AROUT has 14 orders.  Nine are valued between 1 and 1000, three are valued between 1001 and 2000, and so on.


vbfctPartitionEx3
Partition Function Example 3

This example creates a crosstab query that inspects the Order Amount field in an Orders table.  It calculates the number of orders for each customer falling within each of several ranges.  The ranges are defined by the arguments to Partition:

start = 1, stop = 20000, interval = 1000.

You can use the following SQL statement for this example:

TRANSFORM Count(Orders.[Order ID]) AS [CountOfOrder ID]
SELECT Orders.[Customer ID]
FROM Orders
GROUP BY Orders.[Customer ID]
PIVOT Partition(Int([Order Amount]), 1, 20000, 1000);

The result of the crosstab query could look like the following table:

Customer ID	    1: 1000	 1001: 2000	 2001: 3000	 3001: 4000

ALWAO	7

ANDRC	4

ANTHB	10	2	1

AROUT	9	3	1	1

BABUJ	10	7	2

BERGS	8	3

BLUEL	2	5	1

BLUMG	1	1

:


Switch Function

See Also	Example

Description

Evaluates a list of expressions and returns a value or an expression associated with the first expression in the list that is True.

Syntax

Switch( varexpr1, var1 [, varexpr2, var2 . . . [, varexpr7 ,var7 ]] )

Remarks

The Switch function uses the following parts:

Part	Description

varexpr	Expression you want to evaluate.

var	Value or expression that is returned if the corresponding varexpr expression is True.

You can include a maximum of seven varexpr/var pairs.  If the parts aren't properly paired, a run-time error occurs.

The Switch function evaluates the expressions in the varexpr list from left to right and returns the contents of the first var argument whose corresponding varexpr expression evaluates True.  For example, if varexpr1 is True, Switch returns var1. If varexpr1 is False, but varexpr2 is True, Switch returns var2, and so on.

The varexpr part is case-sensitive.  You may want to use UCase on strings before evaluating the expression.

Switch returns a Null value if:

None of the varexpr expressions is True.

The leftmost varexpr that is True has a corresponding var 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 varexpr results in a division by zero error, an error occurs.


vbfctSwitchSee
See Also

Choose Function

IIf Function

Select Case Statement

UCase Function


vbfctSwitchEx
Switch Function Example

The example returns the name of a language that matches the name of a city.  To try this example, draw a text box and a label on a new form.  Set the AutoSize property of the label to True.  Copy the code into the Declarations section of the form, and press F5 to run the program.

Enter the name of a city in the text box and click the form.

Sub Form_Click ()
Label1.Caption = "Language: " & Switch(Text1.Text = "London", "English", Text1.Text = "Rome", "Italian", Text1.Text = "Paris", "French")
End Sub


Argument mismatch

Error

If the object cannot process the specified member, we return this code.  Argument mismatch


Can't open file

Error

Can't open file (either file doesn't exist, or it's in use--any error on opening file).


Internal object errors

Error

If the object internally generates an error (for example, I pass parameters that cause a divide by zero), we

return this error code.


Member not found

Error

The following errors will occur when accessing a member of an object

Member not found

If the object cannot process the specified member, we return this code.


No server available

Error

No server available (file can't be opened)


Property type mismatch

Error

If the member returns a type that cannot be mapped to the type expected, we generate this error code.

Property type mismatch


Return type mismatch

Error

If the arguments specified for a member do not match what the object expected, we return this code.

Return type mismatch


Server isn't responding

Error

If we attempt to set a member property with a value that violates what the object expects, we generate this

error code.

Server isn't responding


The control you selected cannot operate in VB unless you have installed data access. Make sure you have installed data access

Error

CDK.  Attempts to load custom bound controls to versions that do not support data access will generate an error.


Cannot remove last non-fixed row

A grid must contain at least one row.


Cannot use AddItem on a fixed row

You cannot insert a fixed row in a grid. Use the FixedRows property to set the number of fixed rows in a grid.


Cannot use RemoveItem on a fixed row

You cannot delete a fixed row from a grid.  The number of fixed rows in a grid is determined by the FixedRows property.


Cols must be one more than FixedCols value

There must be at least one non-fixed row and one non-fixed column.  FixedCols or FixedRows cannot be equal or greater than Cols or Rows, respectively.


FixedCols must be one less than Cols value

The number of columns assigned as Fixed in a grid must be one less than the number of columns.


FixedRows must be one less than Rows value

The number of Rows assigned as fixed in a grid must be one less than the number of rows.


Grid does not contain that row

You have tried to access a row that does not exist. The first row in a grid is zero. Therefore, the last row in a grid is the number of rows minus one. Use the Rows property to set or return the number of rows in a grid.


Invalid alignment value

The valid values for the ColAlignment and FixedAlignment properties are 0 [image] Left Justify, 1 [image] Right Justify, and 2 [image] center. FixedAlignment has an additional setting: 3 [image] Use ColAlignment Value.


Invalid column number for alignment

You cannot align a fixed column with ColAlignment; use the FixedAlignment property. Set the index argument of the ColAlignment property to a column that is not a fixed column. The FixedCols property returns the number of fixed columns in a grid.


Invalid column value

You have attempted to access a column that does not exist. The first column in a grid is zero. Therefore, the last column in a grid is the number of columns minus one. Use the Cols property to set or return the number of columns in a grid.


Invalid column width value

ColWidth must be greater than or equal to one.


Invalid row height value

RowHeight must be greater than or equal to one.


Invalid row value

You have attempted to access a row that does not exist. The first row in a grid is zero. Therefore, the last row in a grid is the number of rows minus one. Use the Rows property to set or return the number of rows in a grid.


Not a valid picture type

You cannot display a Windows metafile (.WMF) in a grid cell. The Picture property supports only bitmaps (.BMP) and icons (.ICO).


Rows must be one more than FixedRows value

The number of Rows assigned in a grid must be one more than the number of fixed rows.


Unable to allocate memory for grid

You are getting low on memory.  Close some unused applications or documents.


Unable to register the memory manager

There was insufficient memory to store the requested information in the grid.


'|' Dynaset method illegal - no scrollable cursor support
<method>: Dynaset method illegal - no scrollable cursor support

A Move method (other than MoveNext) was attempted.  ODBC Level 1 database drivers do not support these methods.  In order to move to a prior position in a Dynaset (e.g., MovePrevious), close the Dynaset and reopen it.  Then issue MoveNext methods until the record is found.


Access attempted on unopened database

An attempt was made to perform an operation on a database object which is not open.  Issue an OpenDatabase call prior to performing any operations.


Access attempted on unopened Dynaset

An operation was requested on a closed Dynaset object. Open the Dynaset and retry the operation.


Property value only valid when Field is part of a Dynaset

An attempt  was made to set or get the Value property of a Field object (either directly or via GetChunk/AppendChunk methods) when the Field object is not attached to a Dyanset object.


Attempt to Move past EOF

A MoveNext method was specified on a Dynaset after EOF was encountered.


Cannot set the property of an object which is part of a Database object

An attempt was made to change the value of a property of an object (TableDef, Field, etc.) that is a part of an open Database object.


CommitTrans/Rollback illegal - Transactions not supported

The database or its driver does not support transactions.


Data type of field '|' not supported by target database
Data type of field '<field name>' not supported by target database

The named field's type is not supported by the database to which you have connected.  Substitute a different type for this field if possible.


Delete method requires a name argument

A collection's Delete method requires a name.  Add the name argument and reissue the request.


Dynaset is not updatable or Edit method has not been invoked

The Update method was requested on a Dynaset when either the user had not previously specified the Edit method or the Dynaset was not updatable.  For the latter, check the Dynaset's Updatable property prior to attempting updates.


Field size illegal for specified field type

Field.Size is illegal for the given field type. Reset the property to a legal value.


Field type is illegal

Field.Type specified is illegal.  Reset the property to a legal value.


General ODBC error: '|'
General ODBC error: '<error>'

ODBC or the Database reported an error in the operation.  The specific error information is contained in the variable portion of this message.


Get value not allowed on collections

An attempt was made to get the value of a member of a collection.


GetChunk: Offset/Size argument combination illegal

Either the Size argument was greater than 64K or the Offset is illegal.  GetChunk methods must progress through the field without backtracking or skipping data. Reissue the method with the arguments corrected.


Name not found in this collection

A column was specified that could not be found in the Collection object.  Correct the column name or the collection.


No fields defined - cannot append table

An attempt was made to append a Table object that has no fields defined.  Append one or more fields to the Table object's fields collection and reissue the request.


ODBC - GetDriverFunctions failure

Unable to determine functions for this database driver. This error may occur if the ODBC database driver does not conform to ODBC level 1 requirements.


ODBC - SQLAllocConnect failure

Unable to allocate an ODBC Connection handle.  This error may occur if there is insufficient memory to process the request.


ODBC - SQLAllocStmt failure

Unable to allocate an ODBC Statement handle.  This error may occur if there is insufficient memory to process the request.


ODBC - SQLAllocEnv failure

Unable to allocate an ODBC Environment handle.  This error may occur if there is insufficient memory to process the request.


ODBC - SQLBindCol failure

Unable to bind column information to memory.  This error may occur if the ODBC database driver does not conform to ODBC level 1 requirements.


ODBC - SQLColumns (Fields.Refresh) failure: '|'
ODBC - SQLColumns (Fields.Refresh) failure: '<error>'

Unable to determine the fields in a table.  Specific error information is contained in the variable portion of the message.


ODBC - SQLConfigDataSource error '|'
ODBC - SQLConfigDataSource error '<error>'

RegisterDatabase failed. The exact error text is included in the variable portion of this message.


ODBC - SQLConnect failure '|'
ODBC - SQLConnect failure '<error>'

ODBC Connection to the Database failed.  The specific error information is contained in the variable portion of this message.


ODBC - SQLFetch failure: '|'
ODBC - SQLFetch failure: '<error>'

Unable to request data from the database. Specific error information is contained in the variable portion of this message.


ODBC - SQLFreeConnect error

Unable to free a connection handle.


ODBC - SQLStatistics (Indexes.Refresh) failure: '|'
ODBC - SQLStatistics (Indexes.Refresh) failure: '<error>'

Unable to determine the indexes for a table.  Specific error information is contained in the variable portion of the message.  This could also occur if there are transactions pending in a SQL Server database. Commit or rollback transactions and reissue the request.


ODBC - SQLTables (TableDefs.Refresh) failure: '|'
ODBC - SQLTables (TableDefs.Refresh) failure: '<error>'

Unable to determine the tables in a database.  May occur if the ODBC database driver does not conform to ODBC level 1 requirements.


ODBC driver does not support exclusive access to Dynasets

CreateDynaset methods Exclusive argument is set to TRUE.  Set this to FALSE and reissue the method.


ODBC objects require VBODBCA.DLL

Could not locate the VBODBCA.DLL file. Check setup or the location of the VBODBCA.DLL file.


OpenDatabase - invalid connect string

The connection string supplied in this call was invalid.  Correct the string and reissue the request.


Property is read-only

An attempt was made to set the value of a read-only property.


Property not found

Attempt to access a reserved or unknown property for the object specified.  Correct the property name and retry the request.


Reserved parameter must be FALSE

The Exclusive argument of the OpenDatabase call must be set to FALSE.  Reissue the call with the correct argument.


Row-returning SQL is illegal in ExecuteSQL method

Not allowed to issue row-returning SQL as an argument to this method.  Use the CreateDynaset method for row-returning operations.


Set field value illegal without previous Edit or AddNew method

Attempt to change the Value property of a Field without issuing Edit/AddNew.  Issue the appropriate Edit/AddNew and retry the operation.


Set value not allowed on collections

Attempt to set the value of a property or member of a collection.


Table exists - append not allowed

Append method's argument specified a table which already exists in the database. Change the table's name property and reissue the request.


Unable to build data type table

Failure to determine/create the data type table for the OpenDatabase request.  May occur if the ODBC database driver is not Level 1-compliant or if there is insufficient memory to complete the process.


Update illegal without previous Edit or AddNew method

An Update method was issued with no prior Edit or AddNew method.  Issue the appropriate method and retry the request.


Warning: | (ODBC - SQLSetConnectOption failure)
Warning: <operation> (ODBC - SQLSetConnectOption failure)

The variable portion of this message identifies the operation requested. A failure is most likely due to a non-Level 1-compliant ODBC driver.


Zero rows affected by Update method

An Update method resulted in no rows being affected in the base table to which the Dynaset refers.


| illegal - no current record
'<item>' illegal - no current record

Edit or Delete method attempted when no current record is available.  Most likely cause is being at EOF or attempting access on an empty Dynaset.  Check Dynaset's EOF property prior to requesting Edit or Delete method.


ODBC - SQLNumResultCols (Create Dynaset) failure: '|'
ODBC - SQLNumResultCols (Create Dynaset) failure: '<error>'

Unable to determine the number of columns in a dynaset.


ODBC - SQLDescribeCol (Create Dynaset) failure '|'
ODBC - SQLDescribeCol (Create Dynaset) failure '<error>'

Unable to determine the nature of the columns in a dynaset


Append illegal - field is part of a TableDefs collection

A Field object was specified as an argument to a Fields.Append operation when it already is a member of an existing Fields collection.  Dim a new Field object, specify its values and retry the operation with the new Field object.


Append illegal - Index is part of a TableDefs collection

An Index object was specified as an argument to an Indexes.Append operation when it already is a member of an existing Indexes collection.  Dim a new Index object, specify its values and retry the operation with the new Index object.


Can't copy

You tried to copy an object to the Clipboard (set Action = 4), but the object is corrupted or is no longer valid.


Can't open Clipboard

You tried to copy (Action = 4) or paste (Action = 5) an object, but the Clipboard is currently not available.  Find the application that has the Clipboard open and close it.


Can't paste

The Clipboard does not contain a valid OLE object.

This error also occurs when you copy an OLE object to the Clipboard and then try to paste the object back to the same OLE control.

The PasteOK property returns True when an object can be pasted from the Clipboard.

Note that when you copy an OLE object to the Clipboard (set Action = 4), then delete the object (set Action = 10), the object on the Clipboard is also deleted.


Class is not set

When setting Action = 0 (CreateNew, CreateEmbed), if you do not specify a source document (SourceDoc property), the Class property must be set to the name of a class available on your system.

To display a list of the available class names at design time, click the OLE control with the right mouse button and choose the Insert Object command.


Dialog already in use

Only one OLE dialog (either Insert Object or Paste Special) can be displayed at a time.


Error loading from file

An error occurred while attempting to read the specified file (set Action = 12).  Possible causes:

The FileNumber property is invalid.

The file wasn't opened in Binary mode.

The file was not saved properly (set Action = 11).

The file is corrupted.

The file position is not located at the beginning of a valid OLE object.


Error saving to file

Unable to write the object to the specified file (set Action = 11, or 18).  Possible causes:

The FileNumber property is invalid.

The specified file wasn't opened in Binary mode.

Unable to write file due to lack of disk space.


Invalid Action

The Action property has been set to an invalid value.

The following values are reserved for future use and are not valid with this version of the OLE control:

2

3

8

13

16


Incorrect Clipboard format

The OleTypeAllowed property does not match the type of object on the Clipboard.


Invalid format

You have attempted to set or get data with the Data or DataText property using an invalid data format, or a format the object does not support.

To determine the set of valid formats for an OLE object, use the ObjectAcceptFormats, ObjectAcceptFormatsCount, ObjectGetFormats, and ObjectGetFormatsCount properties.


Invalid or unknown class

The specified class is not valid and a source document is not specified.

To display a list of the available class names on your system, at design time click the OLE control with the right mouse button and choose the Insert Object command.

Use extra care when setting the Class property at run time as some class names may be case-sensitive.


Invalid property value

You have attempted to assign an invalid value to a property.

This error also occurs when you are performing an action that requires several properties to be set and one of the properties is set to an invalid value.


Invalid source for link

You have attempted to create a linked object (set Action = 1), and the file specified by the SourceDoc property could not be found.


Invalid Verb index

You tried to activate an object (set Action = 7), and the Verb property was set to an invalid value.

Use the ObjectVerbs and ObjectVerbsCount properties to determine the list of verbs an object supports.


Source name is too long

The combined number of characters in the SourceDoc and SourceItem strings cannot exceed 256.


No object

You tried to perform an action on an object that does not exist.


Object not running

You cannot perform the following actions on an object unless the application that created the object is currently running:

Copy an object to the Clipboard (set Action = 4).

Set or read the Data property.

Set or read the DataText property.

Read the ObjectAcceptFormats property.

Read the ObjectAcceptFormatsCount property.

Read the ObjectGetFormats property.

Read the ObjectGetFormatsCount property.

Use the AppIsRunning property to determine if the application that created an object is running.

If the object exists, you activate it (and therefore invoke the application that created it) by setting Action = 7 (Activate).  To activate an object without displaying the application that created it, first set the Verb property to [image] 3.


Out of memory

Could not allocate or access enough memory or disk space for the specified operation.


Source Document is not set

When creating a linked object, or creating an object from a file (set Action = 1), the SourceDoc property must be set to a valid file name.

At design time, select the SourceDoc property in the Properties window and click the three dots in the Settings box to browse your disk for a valid file name.


This control requires Visual Basic version 3.0 or later

The OLE control is not compatible with Visual Basic versions 1.0 and 2.0.


Unable to access source document

You have attempted to create an embedded object, but the file specified by the SourceDoc property is not a valid file.


Unable to activate object

The object's source document cannot be loaded, or the application that created the object is not available.

This error occurs when you try to activate a linked object (set Action = 7) and the file specified in the SourceDoc property has been deleted or no longer exists.

This error also occurs when you activate an object (set Action = 7), and the action specified by the Verb property is not valid.  Some applications that provide objects may support different verbs, depending on the state of the application.  All the verbs supported by an application are listed in the ObjectVerbs array.  However, some verbs may not be valid for the application's current state.


Unable to close object

The object cannot be closed (set Action = 10) in its current state.


Unable to create embedded object

The application that is creating the object cannot create the object as specified in the SourceDoc property.

For example, this error occurs if you try to embed a spreadsheet object and the SourceDoc property specifies a spreadsheet that is too large to be loaded by the spreadsheet application.


Unable to create link

The application that is creating the object cannot create the linked object as specified in the SourceDoc and SourceItem properties.

For example, this error occurs if you try to link a spreadsheet object and the SourceDoc property specifies a spreadsheet that is too large to be loaded by the spreadsheet application.


Unable to fetch link source name

The OLE control cannot determine the name of the source document for the object you want to create.

For example, when you attempt to paste a linked object from the Clipboard (set Action = 5), the OLE control must determine the name of the source document based on the information provided by the Clipboard.  If the OLE control cannot determine the name of the document to link to, this error occurs.


Unable to initialize OLE

OLE 2.0 cannot be initialized.  Make sure all the current OLE 2.0 files are in the \SYSTEM directory of your main Windows directory and that no other copies of these files exist elsewhere on your system.  Note that OLE 2.0 requires Microsoft Windows version 3.1 or later.


Access to OLE Automation object denied

Error 434

You do not have access rights to the object specified in the GetObject function.

Make sure you have access to the specified file. Check the documentation for the application which generated the file to see how to obtain access rights to the object.


Can't empty Clipboard

Error 520

The clipboard was opened but could not be emptied.


Can't open Clipboard

Error 521

The clipboard has already been opened by another application.


Can't create index on Memo field or Long Binary field.

Error 3287

You can't create an index on a Memo or Long Binary field.  Select a different field to index.


Cannot set the property of an object which is part of a Database object.

Error 3268

Those properties can only be set before the object has been appended to a Database object collection.


Class does not support OLE Automation

Error 430

The object specified in the GetObject or CreateObject function was found or created but does not support OLE Automation. Check the documentation of the application that created the object for any limitations on the use of OLE Automation with this class of object.


Can't delete a field that is part of an index.

Error 3280

You attempted to delete a field that is part of an index.  If you want to delete the field, first remove the index.


Couldn't lock table 'Item1'; currently in use by user 'Item3' on machine 'Item2'.

Error 3212

The table can't be locked because it is currently in use.  Wait for the other user's transaction to complete, then try the operation agqain.


Couldn't update; currently locked by user 'Item2' on machine 'Item1'.

Error 3260

The table can't be updated because it is currently locked by another user.  Wait for the lock to be removed, then try the operation again.


Syntax error in ALTER TABLE statement.

Error 3294

You entered an SQL statement that has an invalid ALTER TABLE Statement.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in column definition.

Error 3293

You entered an SQL statement that has an invalid column definition.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error.

Error 3290

You entered an invalid SQL statement.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in CREATE INDEX statement.

Error 3292

You entered an SQL statement that has an invalid CREATE INDEX Statement.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in CREATE TABLE statement.

Error 3291

You entered an SQL statement that has an invalid CREATE TABLE Statement.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Syntax error in DROP INDEX statement.

Error 3295

You entered an SQL statement that has an invalid DROP INDEX Statement.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Error loading DISP200.DLL

Error 441

The code in your application requires OLE Automation, which requires the file VBOA300.DLL. An error occurred when Visual Basic attempted to load this file.

OLE Automation is required when you use the GetObject or CreateObject functions, or refer to the Object property of the OLE control.


External table isn't in the expected format.

Error 3274

The format of the table has changed since it was attached.  Attach the table again, then retry the operation.


Line Item1: Item2 has a quoted string where the property name should be.

Error 19030

A quoted string appeared in the ASCII form file where the property name was expected.  Property names are not placed inside quotation marks.


Line Item1: All controls must precede menus; cannot load control Item2.

Error 19049

A control appeared in an incorrect location in the ASCII form file.  All controls must be loaded before menus.


Line Item1: Cannot load control Item2; containing control not a valid container.

Error 19050

You attempted to load a control into a control which is not a valid container.


Line Item1: Cannot load control Item2; name already in use.

Error 19051

The control named in the ASCII text file could not be loaded because its name is already in use elsewhere in the application.


Line Item1: Cannot set checked property in menu Item2. Parent menu cannot be checked.

Error 19043

A top-level menu control appeared in the ASCII form file with its Checked property set to TRUE.  Top level menus cannot be checked.  The menu will be loaded, but its Checked property will not be set.


Line Item1: Cannot set shortcut property in menu Item2. Parent menu cannot have a shortcut key.

Error 19044

A top-level menu control appeared in the ASCII form file with a shortcut key defined.  Top level menus cannot have a shortcut key.  The menu will be loaded, but its Shortcut property will not be set.


Line Item1: Class Item2 of control Item3 was not a loaded control class.

Error 19037

The ASCII file contains a control class that Visual Basic does not recognize.  Add the custom control with this class to your project.


Line Item1: Class name too long; truncated to Item2.

Error 19040

The ASCII file contains a class name longer than 40 characters.  The class will be loaded with the name truncated to 40 characters.


Line Item1: Control name too long; truncated to Item2.

Error 19039

The ASCII file contains a control name longer than 40 characters.  The control will be loaded with the name truncated to 40 characters.


Line Item1: Did not find an index property and control Item2 already exists.

Error 19038

The control cannot be loaded because there is no index, and it has the same name as a previously loaded control.


Line Item1: Maximum nesting level for controls exceeded with Item2.

Error 19048

The ASCII file contains controls nested more than 7 levels deep.


Line Item1: Missing or invalid control class in file Item2

Error 19052

The ASCII file contains an unknown control class in the form description, or the class name is not a valid string in Visual Basic.


Line Item1: Missing or invalid control name in file Item2.

Error 19053

The ASCII file contains an unknown control name in the form description, or the control name is not a valid string in Visual Basic.


Line Item1: Parent menu Item2 cannot be loaded as a separator.

Error 19042

The ASCII file contains a menu control whose parent menu is defined as a menu separator.  Top-level menu controls cannot be menu separators.  The separator property will not be set.


Line Item1: Property Item2 in Item3 could not be loaded.

Error 19032

The ASCII file contains an unknown property.  The property will be skipped when loading the form.


Line Item1: Property Item2 in Item3 could not be set.

Error 19036

Visual Basic cannot set the property of the specified control as indicated by the form description in the ASCII file.


Line Item1: Property Item2 in Item3 had an invalid file reference.

Error 19035

The ASCII file contains a reference to a file that Visual Basic could not find in the specified directory.


Line Item1: Property Item2 in Item3 had an invalid value.

Error 19034

The ASCII file contains a property with a value that is not correct for this control.  The property is set with its default value.


Line Item1: Property Item2 in Item3 must be a quoted string

Error 19033

The ASCII file contains a property that should appear inside quotation marks, but the quotation marks are missing.  This line in the form description is ignored.


Line Item1: Property Item2 in control Item3 had an invalid property index.

Error 19031

The ASCII file contains a property name with a property index greater than 255.


Line Item1: Syntax error: property Item2 in Item3 was missing an '='.

Error 19041

The ASCII file contains a property name and value without an equal sign between them.  The property is not loaded.


Line Item1: The control name Item2 is invalid.

Error 19028

The ASCII file contains a control name that is not a valid string in Visual basic.  The control is not loaded.


Line Item1: The Form or MDIForm name Item2 is already in use; cannot load this form.

Error 19046

The ASCII file contains a form with a name that is already being used elsewhere in the application.  The form is not loaded.


Line Item1: The Form or MDIForm name Item2 is not valid; cannot load this form.

Error 19027

The ASCII file contains a form name that is not a valid string in Visual basic.  The form is not loaded.


Line Item1: The name Item2 is already in use as a Item3 name.

Error 19045

The ASCII file contains a name that is already in use elsewhere in the application.


Line Item1: The property name Item2 in Item3 is invalid.

Error 19029

The ASCII file contains a property name that is not a valid property for that control.


Not In Context

Error 156

The procedure for this watch is not currently in the call stack.


Unable To Evaluate

Error 158

The watch cannot currently be evaluated.


Several tables exist with that name; please specify owner, as in 'owner.table'.

Error 3299

More than one table with that name exists in the remote ODBC database.  To resolve the ambiguity you must specify the owner of the table you wish to access, using the "owner.table" syntax.


Syntax error in DROP statement.

Error 3296

You entered an SQL statement that has an invalid DROP Statement.

Possible causes:

A reserved word or argument name is misspelled or missing.

Punctuation is incorrect.


Append Method (Professional Edition Only)

See Also	Example

Description

Adds a new object to a collection.

Syntax

collection.Append newobject

Remarks

The Append method has the following parts:

Part	Description

collection	A TableDefs, Indexes, or Fields collection.

newobject	An object variable identifying a TableDef, Field, or Index object being appended.  Must be of the same type as the members of the collection.

Use the Append method to add a new table, add a field to an existing table, or to add an index to a table.  To create a new object variable, use the New keyword with the Dim or Set statement.

You must set the property values of newobject before you append the object to collection.  Once an object is appended to a collection, the object's property values become read-only, except for the Value property of a Field object.

The addition of a new object occurs immediately, but you should use the Refresh method on any recordsets and any data control that may be affected by changes to the database structure.

Appending an object to a collection does not return an error except when appending a new TableDef to the TableDefs collection, when all objects and collections are validated.  The validate operation verifies that the minimum object properties are complete and valid.  If an object with the same name already exists in a collection, an error occurs.  If any of the field names in the Fields property of an Index object are not valid, an error occurs.


See Also

Help:

Delete Method

Dim Statement

Fields Collection

Indexes Collection

New

Refresh Method

Set Statement

TableDefs Collection

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


Append Method Example

The example defines a new field and appends it to a Fields collection.

Dim MyDB As Database, Fd As New Field
Const DB_TEXT = 10	' Set field type constant.
Set MyDB = OpenDatabase("BIBLIO.MDB")	' Open a database.
Fd.Name = "Phone"	' Set field properties.
Fd.Type = DB_TEXT
Fd.Size = 15
MyDB.TableDefs("Authors").Fields.Append Fd	' Add field to collection.


BeginTrans, CommitTrans, Rollback Statements

See Also

Description

BeginTrans [image] begins a new transaction.

CommitTrans [image] ends the current transaction.

Rollback [image] ends the current transaction and restores the database to the state it was in just before the current transaction began.

Syntax

BeginTrans

CommitTrans

Rollback

Remarks

A transaction is a series of changes you make to a database that you want to treat as one complete unit.  A transaction begins when you use the BeginTrans statement.  Use Rollback to undo changes made during the current transaction, and CommitTrans to accept changes and end the current transaction.  Both Rollback and CommitTrans end a transaction.  Once you use CommitTrans, you can't undo changes made during that transaction.  You can have up to five levels of transactions open at once by using multiple BeginTrans statements.

Typically, you use transactions to maintain the integrity of your data when records in two or more tables must be updated.  For example, if you transfer money from one account to another, you might subtract a sum from one and add the sum to another.  If either update fails, the accounts no longer balance.  Use BeginTrans before updating the first record, and then if any subsequent update fails, you can use Rollback to undo all of the updates.  Use CommitTrans after the last record has been successfully updated.

Note   Some databases, such as Paradox, may not support transactions, in which case the Transactions property of the Database object is False.  Test the value of the Transactions property before using BeginTrans to make sure that the Database supports transactions.  If transactions are not supported, these statements are ignored and no error occurs.

If you use CommitTrans or Rollback statements without first using BeginTrans, an error occurs.

If you use Rollback, you should use Refresh on any data control that refers to data that may have changed since the transaction began.

Caution   Whether you use one of these statements or their corresponding methods, the effect is the same.  Transactions are always global and never limited to only one database or recordset.  If you include operations on more than one database or recordset within a transaction, Rollback restores all operations on all databases.


vbstmBeginTransSee
See Also

Help:

BeginTrans, CommitTrans, Rollback Methods

DataChanged Property

Edit Method

Refresh Method

Reposition Event

Update Method

UpdateControls Method

UpdateRecord Method

Validate Event

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data

Programmer's Guide

Chapter 20, "Accessing Databases with the Data Control"


CompactDatabase Statement

See Also	Example

Description

Compacts and encrypts or decrypts a Microsoft Access database.

Syntax

CompactDatabase sourcename, destinationname [, locale [, options ] ]

Remarks

The CompactDatabase statement uses the following parts:

Part	Description

sourcename	A string expression that is the name of an existing database.  It can be a fully qualified path, such as C:\MYDB.MDB.  The file-name extension, if applicable, is required.  If your network supports it, you can also specify a fully qualified network path, such as:
\\MYSERVER\MYSHARE\MYDIR\MYDB

destinationname	A string expression that is the fully qualified path name of the new database to be created.  You can also specify a fully qualified network path, as with sourcename.  Cannot be the same name as sourcename.

locale	A string expression specifying localization information for creating the destination database.  If you omit this part, the locale of destinationname is the same as sourcename.  See table below for locale constants.

options	A Long numeric value indicating one or more options.  You can combine values by adding them together.  See the table below.

You can supply one of the following values (you must use the symbolic constants in DATACONS.TXT) in the locale part:

Constant	Description

DB_LANG_GENERAL	English, German, French.

DB_LANG_SPANISH	Spanish, Italian.

DB_LANG_DUTCH	Dutch.

DB_LANG_SWEDFIN	Sweden, Finland.

DB_LANG_NORWDAN	Norway, Denmark.

DB_LANG_ICELANDIC	Iceland.

DB_LANG_NORDIC	Nordic countries.

You can supply one or more of the following values or symbolic constants (from DATACONS.TXT) in the options part:

Constant	Value	Definition

DB_VERSION10	1	Create a Microsoft Access 1.0 database.

DB_ENCRYPT	2	Encrypt the database.

DB_DECRYPT	4	Remove encryption coding from the database.

If you omit the options part, newdatabase will have the same encryption state as curdatabase.  If both DB_ENCRYPT and DB_DECRYPT are set, newdatabase will have the same encryption state as curdatabase.

As you change data in a database, the file can become fragmented and use more disk space than necessary.  Periodically, you should compact your database in order to defragment the file.  The compacted database will usually be smaller.

The CompactDatabase statement essentially copies all the data and security permissions settings from one database into another.  In the process, the data in the resulting database is organized contiguously to recover disk-space.  It also gives you the option of changing the encryption or language locale during the compaction operation.

You must close a database before you compact it.  In a multiuser environment, you must make sure all other users have closed the database as well.  To make sure, you can open the database for exclusive use and then close it.

Since this statement creates a duplicate copy of the database, you must have enough disk space for both copies.  The compact operation fails if there isn't enough space available.  The compacted copy can be on a different disk.

After a database has been successfully compacted, you can delete the original database file and rename the compacted file to the original name.


vbstmCompactDatabaseSee
See Also

Help:

Kill Statement

Name Statement

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


vbstmCompactDatabaseEx
CompactDatabase Statement Example

The following code compacts a database called C:\PUBS.MDB and keeps a backup copy of the original database.  The new database has the same locale as the source database, but is encrypted.

CompactDatabase "C:\PUBS.MDB","C:\PUBSNEW.MDB",,DB_ENCRYPT
...
Kill "C:\PUBS.BAK"
Name "C:\PUBS.MDB" As "C:\PUBS.BAK"
Name "C:\PUBSNEW.MDB" As "C:\PUBS.MDB"


CreateDatabase Function (Professional Edition Only)

See Also	Example

Description

Creates a Microsoft Access database, and returns a Database object that is open for exclusive read/write access.

Syntax

Set dbobject = CreateDatabase( dbname [, locale [, options ]] )

Remarks

The CreateDatabase function has these parts:

Part	Description

dbobject	A Database object variable.

dbname	A string expression for the name of your new database.  It can be a fully qualified path, such as C:\MYDB.MDB.  The file-name extension, if applicable, is required.  If your network supports it, you can also specify a fully qualified network path, such as:
\\MYSERVER\MYSHARE\MYDIR\MYDB

locale	A string expression specifying the language information for creating the database.  Although not required, an incorrect information in this part will cause a run time error.  See the table below for locale settings.

options	A Long numeric value indicating one or more options.  See the table, below.

You can supply one of the following symbolic constants (from DATACONS.TXT) in the locale part:

Constant	Description

DB_LANG_GENERAL	English, German, French.

DB_LANG_SPANISH	Spanish, Italian.

DB_LANG_DUTCH	Dutch.

DB_LANG_SWEDFIN	Sweden.

DB_LANG_NORWDAN	Norway.

DB_LANG_ICELANDIC	Iceland.

DB_LANG_NORDIC	Nordic countries (Microsoft Access 1.0 only).

You can supply one or more of the following values or symbolic constants (from DATACONS.TXT) in the options part:

Constant	Value	Definition

DB_ENCRYPT	2	Encrypt the database.  To decrypt a database, use the CompactDatabase statement.

DB_VERSION10	1	Create a Microsoft Access 1.0 database.

You can indicate more than one option by adding values together.

The CreateDatabase function opens the new database for exclusive access.  To open it for multiuser access you can use the Close method on the database, then open it again with the OpenDatabase function.

If the database file already exists, an error occurs.


See Also

Help:

And Operator

Close Method

CompactDatabase Statement

Exclusive Property

OpenDatabase Function

Refresh Method

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


CreateDatabase Function Example

The example creates a new database named MYDB.MDB.

Dim CurDB As Database
' Use general locale setting from DATACONS.TXT.
Set CurDB = CreateDatabase("C:\MYDB.MDB", DB_LANG_GENERAL, DB_VERSION10)
...


CreateDynaset Method (Professional Edition Only)

See Also	Example

Description

Creates a Dynaset object from a specified Table object, QueryDef object, or SQL statement.

Syntax

Set dynasetobject = database.CreateDynaset( source [, options ] )

Set dynasetobject = { recordset | querydef }.CreateDynaset( [ options ] )

Remarks

The CreateDynaset method uses these parts:

Part	Description

dynasetobject	Object variable of type Dynaset.

database	Object variable identifying an open database or the Database property of a data control.

recordset	Object variable identifying an existing recordset object or the Recordset property of a data control.

querydef	Object variable identifying an existing QueryDef object.

source	String expression that is the name of an existing recordset, QueryDef or SQL statement.

options	A numeric expression indicating one or more option settings.  Values can be combined by adding them together.  See table below for option values.

You can supply one or a combination of the following symbolic constants and values (from DATACONS.TXT) in the options part:

Constant	Value	Description

DB_DENYWRITE	1	In a multiuser or multitasking environment, others cannot make changes to any records in any table in your Dynaset while you have it open.  Use for administrative purposes only.

DB_READONLY	4	You cannot make changes to records in your Dynaset.  This can increase speed of some operations.

DB_APPENDONLY	8	You can only add new records to the Dynaset.  You cannot read or update existing records.

DB_INCONSISTENT	16	Updates can apply to all fields of the Dynaset, even if they also affect other rows of the Dynaset.

DB_CONSISTENT	32	(Default) Updates apply only to those fields that will not affect other rows of the Dynaset.

DB_SQLPASSTHROUGH	64	For Dynasets created with an SQL statement, this value causes the SQL statement to be passed to an ODBC database for processing, as when creating a Dynaset on tables in a SQL Server or Oracle database.  Ignored except for ODBC remote databases.  The Dynaset is not updatable.

If both DB_INCONSISTENT and DB_CONSISTENT are included, or if neither are included, the result is the default.

When applied to a Dynaset or Snapshot, CreateDynaset returns a new Dynaset containing records filtered and sorted according to the Dynaset's or Snapshot's Filter and Sort properties.  It doesn't affect the contents of the first Dynaset or Snapshot.

To create a Dynaset from a QueryDef that has parameters, open the QueryDef, set the parameters, and then use CreateDynaset.  You set the parameters of a QueryDef using the following syntax:

querydef ! parameter = parametervalue

When you only want to read data and not change data, a Snapshot object is faster than a read-only Dynaset object.  However, a read-only Dynaset will reflect changes made by others while you are using it.  A Snapshot will not.

Note   If your program requires two identical Dynasets, it is more efficient to create a single Dynaset and then use the Clone method to create a second reference.


lanCreateDynasetSee
See Also

Help:

Clone Method

CreateSnapshot Method

Filter Property

OpenTable Method

Options Property

Or Operator

Sort Property

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


lanCreateDynasetEx
CreateDynaset Method Example

This example uses an SQL statement to create a read-only Dynaset of Publishers from New York.

Dim MyDB As Database, MySet As Dynaset
Dim MyTable As Table, SQLStmt As String
Const DB_READONLY = 4	' Set constant.
Set MyDB = OpenDatabase("BIBLIO.MDB")	' Open database.
' Set text for the SQL statement.
SQLStmt = "SELECT * FROM Publishers WHERE State = 'NY'"
' Create the new Dynaset.
Set MySet = MyDB.CreateDynaset(SQLStmt, DB_READONLY)


CreateSnapshot Method (Professional Edition Only)

See Also	Example

Description

Creates a Snapshot object from a specified table, QueryDef, or SQL statement.

Syntax

Set snapshot = database.CreateSnapshot( source [, options ] )

Set snapshot = recordset.CreateSnapshot( [ options ] )

Remarks

The CreateSnapshot method uses these parts:

Part	Description

snapshot	An object variable of type Snapshot.

database	Object variable identifying an open database or the Database property of a data control.

recordset	Object variable identifying an existing recordset object or the Recordset property of a data control.

querydef	Object variable identifying an existing QueryDef object.

source	String expression that is the name of an existing recordset, QueryDef or SQL statement.

options	A numeric expression indicating one or more option settings.  Values can be combined by adding them together.  See table below for option values.

You can use one or a combination of the following symbolic constants and values (from DATACONS.TXT) in the options part:

Constant	Value	Description

DB_DENYWRITE	1	In a multiuser environment, others cannot make changes to records in any table in your Snapshot while you have it open.  Use for administrative purposes only.

DB_SQLPASSTHROUGH	64	For Snapshots created with an SQL statement, this value causes the SQL statement to be passed to an ODBC database for processing, as when creating a Snapshot on tables in a SQL Server or Oracle database.  Ignored except for ODBC remote databases.

Unlike the data in a Dynaset, the data in a Snapshot isn't linked to its underlying tables.  The data in a Snapshot doesn't change even if the data in its underlying tables changes.  Further, you cannot change the data in a Snapshot.

When applied to a Dynaset or Snapshot, CreateSnapshot returns a Snapshot containing records filtered and sorted according to the Dynaset or Snapshot object's Filter and Sort properties.  The contents of the original Dynaset or Snapshot aren't affected.

When applied to a QueryDef, CreateSnapshot executes the QueryDef and returns a Snapshot that is a copy of the data defined by the QueryDef.  If you use CreateSnapshot on an action QueryDef an error occurs (use the Execute method for action QueryDef objects).

To use CreateSnapshot on a QueryDef that has parameters, first open the QueryDef and set the parameters.  You set the parameters of a QueryDef using the following syntax:

querydef ! parameter = parametervalue

When you only want to read data and not change data, a Snapshot object is faster than a read-only Dynaset object.  However, a read-only Dynaset will reflect changes made by others while you are using it.  A Snapshot will not.


lanCreateSnapshotSee
See Also

Help:

CreateDynaset Method

Dynaset Object

Execute Method

Fields Collection

QueryDef Object

Snapshot Object

Sort Property

Table Object

TableDefs Collection

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


lanCreateSnapshotEx
CreateSnapshot Method Example

The first part of the example creates a Snapshot of publishers located in California, sorted by ZIP code.  The second part of the example recreates the Snapshot with a new sort order.

Dim MyDB As Database, MySet As Snapshot, MySQL As String
Set MyDB = OpenDatabase("BIBLIO.MDB")
MySQL = "SELECT * FROM Publishers WHERE State = 'CA' ORDER BY ZIP;"
Set MySet = MyDB.CreateSnapshot(MySQL)
...
MySet.Sort = "Publisher's Name"
Set MySet = MySet.CreateSnapshot()


SetDefaultWorkspace Statement

See Also

Description

Establishes the user ID and password for protected (security-enabled) Microsoft Access databases.  If you are not using a protected database, this statement is ignored.

Syntax

SetDefaultWorkspace username, password

Remarks

The SetDefaultWorkspace statement has these parts:

Part	Description

username	A string expression identifying a user recognized by the system database.

password	A string expression that is a valid password for username.

If you use protected databases, this statement must be the first data access statement used when running your program (except for SetDataAccessOption with the DB_INITPATH option setting).  Initializing a data control or the use of any other data access function or statement will establish a default username of "Admin" and a default password of an empty string ("").  Subsequent attempts to set or change the username or password are ignored.

You can access several databases while your application is running, but all protected databases must recognize the same username and password, since they can't be changed once established.  The only way to change these settings is to exit your application and run it again with different settings.

If you use a protected database, you must include a copy of the system database with the appropriate settings when you distribute your application.  Using this statement without a system database will produce an error.  The system database must be in the current directory or in the directory specified in your application's initialization file (.INI).  If you use a data control and must use the SetDefaultWorkspace statement, you must use it in the Sub Main procedure, or in the first Form_Load event procedure.

Note   Only Microsoft Access can create a system database.


vbstmLoginSee
See Also

Help:

Load Event

Refresh Method

SetDataAccessOption Statement

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


Execute Method

See Also	Example

Description

Invokes an action query in a specified database.

Syntax

dbobject.Execute { queryname | sqlstatement }[, options ]

querydef.Execute [ options ]

Remarks

The Execute method uses these parts:

Part	Description

dbobject	The Database property of a data control.  In the Professional Edition, can also be an object variable identifying an open Database.

queryname	A string expression that is the name of an existing query in dbobject that performs an action, such as update, delete, or insert.

sqlstatement	A string expression that is a valid (for the specified database) SQL statement that performs an action.

querydef	In the Professional Edition, an object variable identifying an open QueryDef that performs an action.

options	A numeric expression indicating one or more option settings.  Multiple options values can be combined by adding them together.  See table below.

You can use the following symbolic constants and values (from DATACONS.TXT) for the options part:

Constant	Value	Description

DB_DENYWRITE	1	In a multiuser environment, others cannot make changes to records in any table in the target recordset while the statement is running.

DB_INCONSISTENT	16	(Default) Updates can apply to all fields of the target recordset, even if they also affect other rows of the target recordset.

DB_CONSISTENT	32	Updates apply only to those fields that will not affect other rows of the target recordset.

DB_SQLPASSTHROUGH	64	This value causes the SQL statement to be passed to an ODBC database for processing; for example, to execute a query in an Oracle or SQL Server database.  Ignored except for ODBC remote databases.

If both DB_INCONSISTENT and DB_CONSISTENT are included, or if neither are included, the result is the default.

Using Execute on a query that selects records produces an error.

Like ExecuteSQL, Execute doesn't return a recordset.

The Execute and ExecuteSQL methods are different in the following ways:

ExecuteSQL returns the number of rows affected by the SQL statement, while Execute does not return a value.

ExecuteSQL operates only on a remote ODBC database such as SQL Server or Oracle.

Execute allows setting of options that affect how the SQL statement is executed.


lanExecuteSee
See Also

Help:

CreateQueryDef Method

ExecuteSQL Method

OpenQueryDef Method

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


lanExecuteX
Execute Method Example

This example uses a data control to execute an existing action query named City Change.

Data1.Database.Execute "City Change"


ExecuteSQL Method

See Also	Example

Description

Executes an action query SQL statement in a specified database.

Syntax

rows = database.ExecuteSQL( sqlstatement )

Remarks

The ExecuteSQL method has the following parts:

Part	Description

rows	The number of rows affected by the action query.  Long data type.

database	The Database property of a data control.  In the Professional Edition, can also be an object variable identifying an open Database object.

sqlstatement	A string expression that is a valid SQL statement that does not return a recordset.

The ExecuteSQL method is valid only for SQL statements that do not return records.  For example, an SQL statement that uses "SELECT..." returns records, while an SQL statement that uses "DELETE..." does not.

Like Execute, ExecuteSQL doesn't return a recordset.

Using ExecuteSQL on a query that selects records produces an error.

The Execute and ExecuteSQL methods are different in the following ways:

ExecuteSQL returns the number of rows affected by the SQL statement, and Execute does not return a value.

ExecuteSQL operates only on a remote ODBC database such as SQL Server or Oracle.

Execute allows setting of options that affect how the SQL statement is executed.


vbmthExecuteSQLSee
See Also

Help:

CreateQueryDef Method

Execute Method

OpenQueryDef Method

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


vbmthExecuteSQLEx
ExecuteSQL Method Example

The example executes an action query that changes the City from "New York" to "NY" in the Publishers table.

MySQL = "UPDATE Publishers SET City = 'NY' WHERE City = 'New York'"
RecsChanged = MyOracleDB.ExecuteSQL MySQL


ListTables Method (Professional Edition Only)

See Also	Example

Description

Creates a Snapshot with one record for each Table or QueryDef in a specified database.

Note   It is much easier and more efficient to use the TableDefs collection instead of this method, which is provided for compatibility with Microsoft Access.  However, it is useful for getting the names of QueryDef objects which are not otherwise available.

Syntax

Set snapshot = database.ListTables( )

Remarks

The ListTables method uses these parts:

Part	Description

snapshot	An object variable of type Snapshot.

database	An object variable identifying an open Database containing the tables and QueryDefs you want to list.  It can also be the Database property of a data control.

The following table lists the names of the Snapshot fields.

Field	Data Type	Description

Name	String	Name of the Table or QueryDef.

DateCreated	Variant	Date on which the Table or QueryDef was created.

LastUpdated	Variant	Date on which the Table or QueryDef definition was last changed.

TableType	Long	Number identifying the kind of Table or QueryDef.  See the table below for possible values.

RecordCount	Long	Number of records in the Table. If TableType is DB_QUERYDEF, RecordCount is Null.

Attributes	Long	Number identifying one or more characteristics of each Table or QueryDef.  If the Attribute is equal to DB_SYSTEMOBJECT (&H80000002) it is a system table.

The possible values for the TableType field are:

Constant	Value	Description

DB_TABLE	&H00000001	A table.

DB_QUERYDEF	&H00000005	A QueryDef.

When you use the ListTables method to create a Snapshot, you can evaluate the contents of the Attributes field in the Snapshot by referring to the TableDef property settings table in the Attributes property topic.

If the specified database contains no user-defined tables, and no QueryDefs, the Snapshot will include only the records of the system tables.

Other Attributes may apply to tables, but are not returned by ListTables.  To examine these values, use the Attributes property of a TableDef object in the TableDefs collection of a Database.

Note   The Fields collection is not available in Snapshots created by the ListTables, ListFields, ListIndexes, and ListParameters methods; therefore, you can't access the field values using an index into the Fields collection.  To access the field values you must explicitly use the name of each field.

You also can't use the Find methods, such as FindFirst, on a Snapshot created with this method.


lanListTablesSee
See Also

Help:

Attributes Property

Fields Collection

Indexes Collection

QueryDef Object

TableDef Object

TableDefs Collection

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


lanListTablesX
ListTables Method Example

This example creates a Snapshot listing all the tables in a database, then prints the data in the Snapshot on the active form.

Dim MyDB As Database, ListSet As Snapshot
Set MyDB = OpenDatabase("BIBLIO.MDB")
Set ListSet = MyDB.ListTables()	' Copy Table info to ListSet.
Do While Not ListSet.EOF
Print ListSet("Name"),	' Print data from each field.
Print ListSet("TableType"),
Print ListSet("RecordCount"),
Print Hex$(ListSet("Attributes"))
ListSet.MoveNext	' Move to next record.
Loop

The printout might look like the following table:

Name	TableType	RecordCount	Attributes

Authors	1	46	0

Book Types	1	0	0

By State	5	#NULL#	0

Get State	5	#NULL#	0

MSysACEs	1	105	&H80000002

MSysColumns	1	108	&H80000002

MSysIndexes	1	15	&H80000002

MSysObjects	1	28	&H80000002

MSysQueries	1	80	&H80000002

Publisher Comments	1	8	0

Publishers	1	30	0

Title Author Publisher	5	#NULL#	0

Titles	1	50	0


OpenDatabase Function (Professional Edition Only)

See Also	Example

Description

Opens an existing database and returns a Database object.

Syntax

OpenDatabase( dbname [, exclusive [, readonly [, connect ]]] )

Remarks

The OpenDatabase function has these parts:

Part	Description

dbname	A string expression that is the name of an existing database.  It can be a fully qualified path, such as C:\MYDB.MDB.  The file extension, if applicable, is required.  If your network supports it, you can also specify a fully qualified network path, such as:
\\MYSERVER\MYSHARE\MYDIR\MYDB

exclusive	A Boolean expression.  If True, the database opens for exclusive (single-user) access and if False, the database opens for multiuser access.  The default is False.

readonly	A Boolean expression.  If True, the database opens for read-only access and if False, the database opens for read/write access.  The default is False.

connect	A string expression used for opening the database.

If dbname refers to a database that is already open for exclusive access by another user, or dbname doesn't exist, an error occurs.  If you specify exclusive use and another user already has the database open, an error occurs.

If dbname is an empty string and connect is "ODBC;" then a dialog box listing all registered ODBC data source names appears, allowing the user to select a database.

For more information about ODBC drivers such as SQL Server or Oracle, see the Help file provided with the driver.

Possible settings for the supported database formats are:

Database format	DatabaseName	Connect
Microsoft Access	drive:\path\filename	(none)
dBASE III	drive:\path	dBASE III;
dBASE IV	drive:\path	dBASE IV;
Paradox	drive:\path	Paradox;
Btrieve	drive:\path\file.DDF	Btrieve;
FoxPro 2.0	drive:\path	FoxPro 2.0;
FoxPro 2.5	drive:\path	FoxPro 2.5;
ODBC	data source name or an empty string ("")	ODBC; DSN=server; DATABASE=defaultdatabase; UID=user; PWD=password; LoginTimeout=seconds


lanOpenDatabaseSee
See Also

Help:

Close Method

RegisterDatabase Statement

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


lanOpenDatabaseX
OpenDatabase Function Example

This example opens the BIBLIO.MDB database for exclusive use.

Dim MyDB As Database
Set MyDB = OpenDatabase("C:\VB\BIBLIO.MDB", True, False)

This example opens an ODBC database and supplies additional login information.

Dim MyDB As Database
Set MyDB = OpenDatabase("", False, False, "ODBC; DSN=MyServer; UID=sa")


OpenTable Method (Professional Edition Only)

See Also	Example

Description

Opens an existing table and returns a Table object.

Syntax

Set tableobject = dbobject.OpenTable(tablename [, options] )

Remarks

The OpenTable method uses these parts:

Part	Description

tableobject	An object variable of type Table.

dbobject	An object variable identifying an open Database.

tablename	String expression that is the name of an existing table in dbobject.

options	A numeric expression indicating one or more option settings.  Values can be combined by adding them together.  See the table below.

You can use the following symbolic constants and values (from DATACONS.TXT):

Constant	Value	Description

DB_DENYWRITE	1	In a multiuser or multitasking environment, others cannot make changes to any records in the Table while you have it open.  Use for administrative purposes only.

DB_DENYREAD	2	In a multiuser or multitasking environment, others cannot read any records in the Table while you have it open.  Use for administrative purposes only.

DB_READONLY	4	You cannot make changes to records in the Table.  This can increase the speed of some operations.

If you want just part of a table, you should use the CreateDynaset method to create a subset of the data.  Although records in tableobject can be ordered only according to its indexes, you can sort a Dynaset on any field.  A Dynaset can also contain fewer records than its underlying Table.  The Seek method on a Table is faster than Find methods on a Dynaset.


lanOpenTableSee
See Also

Help:

Close Method

CreateDynaset Method

Fields Collection

Indexes Collection

OpenDatabase Function

TableDefs Collection


lanOpenTableX
OpenTable Method Example

This example opens the Publishers table in the BIBLIO.MDB database.

Dim MyDB As Database, MyTable As Table
Set MyDB = OpenDatabase("BIBLIO.MDB")	' Open Database.
Set MyTable = MyDB.OpenTable("Publishers")	' Open Table.
...
MyTable.Close	' Close Table.


Refresh Method

See Also	Example 1	Example 2

Description

Forces an immediate repaint or update of a form, control, or object.

Syntax

[formname. | controlname. | objectname. ]Refresh

Remarks

Use this method to force a complete repaint of a form or control.  This is useful when you want a form to display completely while another form is loading, or when you want to update the contents of a system list box, such as a file list box, or the data structures of a data control.

Refresh cannot be used on MDI forms, but can be used on MDI child forms.  You cannot use Refresh on menu or timer controls.

Generally, painting a form or control is handled automatically while no events are occurring.  However, there may be situations where you want the form or control updated immediately.  For example, if you use a file list box, a directory list box, or a drive list box to show the current status of the file system, you can use Refresh to update the list whenever a change is made to the directory structure.

You can use the Refresh method on a data control to open or reopen the database (if the DatabaseName, ReadOnly, Exclusive, or Connect properties have changed) and rebuild the Dynaset in the control's Recordset property.


lanRefreshSee
See Also

Help:

Database Property

DoEvents Function

Fields Collection

Indexes Collection

MDI Form

MDIChild Property

Options Property

Paint Event

Recordset Property

RecordSource Property

TableDef Object

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"

Programmer's Guide:

Chapter 20, "Accessing Databases with the Data Control"


lanRefreshEx1
Refresh Method Example 1

The example uses the Refresh method to update a file list box as test files are being created.  To try this example, paste the code into the Declarations section of a form with a file list box named File1.  Then press F5 and click the form.

Sub Form_Click ()
Dim FName, I, Msg	' Declare variables.
File1.Pattern = "TestFile.*"	' Set file pattern.
For I = 1 To 8	' Do 8 times.
FName = "TESTFILE." & I
Open FName For Output As FreeFile	' Create empty file.
File1.Refresh	' Refresh file list box.
Close	' Close file.
Next I
Msg = "Choose OK to remove the created test files."
MsgBox Msg	' Display message.
Kill "TESTFILE.*"	' Remove test files.
File1.Refresh	' Update file list box.
End Sub


lanRefreshEx2
Refresh Method Example 2 (Data Access)

The example uses the Refresh method and the Exclusive property to change an open database from multiuser to single-user access.

Data1.Exclusive = True
Data1.Refresh


IIf Function

See Also	Example

Description

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

Syntax

IIf( expr, truepart, falsepart )

Remarks

The IIf function has the following parts:

Argument	Description

expr	Expression you want to evaluate.

truepart	Value or expression returned if expr is True.

falsepart	Value or expression returned if expr is False.

You might use IIf (meaning "Immediate If") to evaluate an expression and return either of two other values.  For example, you could use the IIf function to inspect a field on a form and determine whether it is Null.  If it is, you might have the function return an empty string; otherwise, it would return the field's contents.  The following example checks a field in the copy buffer:

IIf(IsNull(Data1.Recordset("State")), "",Data1.Recordset("State"))

IIf is most useful in the Validate event.  The If...Then...Else statement often offers more versatility.  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.


vbfctIIfSee
See Also

Help:

Choose Function

If...Then...Else Statement


vbfctIIfEx
IIf Function Example

This example evaluates the value of the contents of a text box and sets the accompanying caption to display the word "Large" if the amount is greater than 1000; otherwise, it displays the word "Small".

Label1.Caption = IIf(Text1.Text > 1000, "Large", "Small")


BeginTrans, CommitTrans, Rollback Methods

See Also

Description

BeginTrans [image] begins a new transaction.

CommitTrans [image] ends the current transaction.

Rollback [image] ends the current transaction and restores the database to the state it was in when the current transaction began.

Syntax

database.BeginTrans

database.CommitTrans

database.Rollback

Remarks

These methods are included only for compatibility with an earlier version of Visual Basic and are not recommended.  The corresponding statements have exactly the same effect, are compatible with Microsoft Access Basic, and make your code easier to understand.

Caution   Whether you use one of these methods or their corresponding statements, the effect is the same.  Transactions are always global and never limited to only one database or recordset.  If you include operations on more than one database or recordset within a transaction, Rollback restores all operations on all databases.


vbmthBeginTransSee
See Also

Help:

BeginTrans, CommitTrans, Rollback Statements


FreeLocks Statement

See Also

Description

Suspends data processing, allowing the database to release locks on record pages and make all data in your local Dynaset objects current in a multiuser environment.

Syntax

FreeLocks

Remarks

Use the FreeLocks statement in multiuser, multitasking environments where there is not enough time for background processing to keep all records current in your recordset.  Normally, read locks are removed and data in local Dynaset objects is updated only when no other actions (including mouse moves) are occurring.  If data processing is so intense that normal background management of locks is unable to keep up, then you should periodically use FreeLocks to allow the processing that would ordinarily occur in the background.

This function is not needed in single-user environments unless you are running multiple instances of your application.


vbstmFreeLocksSee
See Also

Help:

LockEdits Property

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


RegisterDatabase Statement

See Also	Example

Description

Makes connect information for an ODBC data source name available for use by the OpenDatabase function.

Syntax

RegisterDatabase dsn, driver, silent, attributes

Remarks

The RegisterDatabase statement has the following parts:

Part	Description

dsn	A string expression that is a name used in the OpenDatabase function and refers to a block of descriptive information about the data source.  For example, if the data source is an ODBC remote database, it would be the name of the server.

driver	A string expression that is the name of the ODBC driver.  This is not the name of the ODBC driver DLL file.  For example, "SQL Server" or "Oracle" are driver names, but "SQLSRVR.DLL" is the name of a DLL file.  You must have ODBC and the appropriate driver already installed.

silent	A numeric expression that is True if you do not want to display the ODBC driver dialogs that prompt for driver-specific information, or False if you do want to display the ODBC driver dialogs.  If silent is True, then attributes must contain all the necessary driver-specific information or the dialog will appear anyway.

attributes	String expression that is a list of keywords to be added to the ODBC.INI file.  The keywords are in a carriage-return-delimited string.

If the database is already registered in the ODBC.INI file, the entry is updated.

If RegisterDatabase fails for any reason, no changes are made to the ODBC.INI file, and an error occurs.

For more information about ODBC drivers such as SQL Server or Oracle, see the Help file provided with the driver.


lanRegisterDatabaseSee
See Also

Help:

OpenDatabase Function (Professional Edition Only)


lanRegisterDatabaseEx
RegisterDatabase Example

This example registers a SQL server named "Clinton" and then opens the Pubs database (the default database) on that server.

Dim Att As String, MyDb As Database
Att = "Description = SQL Server on server Clinton" & Chr$(13)
Att = Att & "OemToAnsi=No" & Chr$(13)	' Build keywords string.
Att = Att & "Network=DBNMP3" & Chr$(13)
Att = Att & "Address=\\CLINTON\PIPE\SQL\QUERY" & Chr$(13)
Att = Att & "Database=Pubs"
' Update ODBC.INI.
RegisterDatabase "Clinton", "SQL Server", True, Att
...
Set MyDb = OpenDatabase("Clinton", False, False, "ODBC;")
...


RepairDatabase Statement

See Also

Description

Attempts to repair a corrupted Microsoft Access database.

Syntax

RepairDatabase ( dbname )

Remarks

The RepairDatabase statement has this part:

Part	Description

dbname	A string expression that is the path and file name for an existing Microsoft Access database file.  If you omit the path, only the current directory is searched.  You can also specify a fully qualified network path, such as \\MYSERVER\MYSHARE\MYDIR\MYDB.  If dbname refers to a database that has already been opened by another user, or if dbname doesn't exist, an error occurs.

This statement repairs a Microsoft Access database that was left invalid by an incomplete write operation.  This can occur if Visual Basic or your application quits unexpectedly because of a power outage or computer hardware problems.  The database will not be left invalid if you use the Close method or if Visual Basic and your program exit normally.

RepairDatabase also attempts to validate all system tables and all indexes.  Any data that cannot be salvaged is discarded.

When you attempt to open or compact a corrupted database, a trappable error occurs.  In some situations, a corrupted database may not be detected and no error occurs.  It's a good idea to provide your users with a way to execute the RepairDatabase statement in your application if their database behaves unpredictably.

It's also a good idea after repairing a database to compact it with CompactDatabase.


vbstmRepairDatabaseSee
See Also

Help:

CompactDatabase Statement

Close Method

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


UpdateControls Method

See Also	Example

Description

Gets the current record from a data control's recordset and displays the appropriate data in controls bound to a data control.

Syntax

datactrl.UpdateControls

Remarks

Use this method to restore the contents of bound controls to their original values, such as when a user makes changes to data and then decides to cancel the changes.

This method creates the same effect as making the current record current again, except that no events occur.


vbmthUpdateControlsSee
See Also

Help:

Edit Method

Update Method

UpdateRecord Method

Programmer's Guide:

Chapter 20, "Accessing Databases with the Data Control"


vbmthUpdateControlsEx
UpdateControls Method Example

This example cancels any changes made to data in bound controls and restores the data to the original values.  The KeyPreview property of the Form must be True.

Sub Form_KeyDown (KeyCode As Integer, Shift As Integer)
Const KEY_ESCAPE = &H1B
If KeyCode = KEY_ESCAPE Then
Data1.UpdateControls
End If
End Sub


UpdateRecord Method

See Also

Description

Saves the current values of bound controls.

Syntax

datactrl.UpdateRecord

Remarks

Use this method to save the current contents of bound controls to the database during the Validate event without triggering the Validate event again.  This will avoid a cascading event.

This method has the same effect as executing the Edit method, and then changing a field and executing the Update method, except that no events occur.


vbmthUpdateRecordSee
See Also

Help:

UpdateControls Method

Programmer's Guide:

Chapter 20, "Accessing Databases with the Data Control"


PopupMenu Method

See Also	Example

Description

Displays a pop-up menu on a form at the current mouse location, or at specified coordinates.

Syntax

[form.]PopupMenu menuname [, flags [, x [, y] ] ]

Remarks

The PopupMenu method has these parts:

Part	Description

menuname	The name of the pop-up menu to be displayed.  The specified menu must have at least one submenu.

flags	Defines the location and behavior of a pop-up menu.

x	Specifies the x coordinate where the pop-up menu is to be displayed.

y	Specifies the y coordinate where the pop-up menu is to be displayed.

You specify the x, y coordinates using the scale mode of the specified form.  The x, y coordinates define where the pop-up is displayed relative to the specified form.  For example, the following code displays a pop-up menu in the upper-left corner of Form2 when the user clicks Form1:

' User clicks Form1
Sub Form_Click ()
' Display pop-up menu in upper-left corner of Form2.
Form2.PopupMenu mnuAction, POPUPMENU_LEFTALIGN, 0, 0
End Sub

If the x, y coordinates are not included, the pop-up menu is displayed at the current location of the mouse pointer.

The following tables describe the possible values for flags:

Location constant	Value	Description

POPUPMENU_LEFTALIGN	0	(Default) The left side of the pop-up menu is at x.

POPUPMENU_CENTERALIGN	4	The pop-up menu is centered at x.

POPUPMENU_RIGHTALIGN	8	The right side of the pop-up menu is at x.

Behavior constant	Value	Description

POPUPMENU_LEFTBUTTON	0 	(Default) The pop-up menu recognizes when the user clicks a menu item with the left mouse button only.

POPUPMENU_RIGHTBUTTON	2	The pop-up menu recognizes when the user clicks a menu item with either the right or left mouse button.

Note   The flags parameter has no effect on applications running under Microsoft Windows version 3.0.

To specify flags, you can combine one constant from each group using the Or operator.  For example:

PopupMenu mnuEdit, POPUPMENU_RIGHTALIGN Or POPUPMENU_RIGHTBUTTON, xloc, yloc

When you display a pop-up menu, the code following the call to the PopupMenu method does not run until the user either selects an item in the menu (in which case the code for that menu's Click event is executed before control returns to the code following the PopupMenu statement), or cancels the menu.  In addition, only one pop-up menu can be displayed at a time.  Therefore, calls to this method are ignored if a pop-up menu is already displayed or if a pull-down menu is currently active.

A pop-up menu that is not visible in the menu bar because its Visible property is False in the Menu Design window can still be displayed, because the Visible property of the specified menu is ignored when Visual Basic displays a pop-up menu.

To display a pop-up menu when the user clicks the right mouse button, use the MouseDown event.

Note   Symbolic constants for the PopupMenu method parts can be found in the Visual Basic file CONSTANT.TXT.  When placed in any module in a project, the symbolic names can be used in all your form and code modules.


vbmthPopupMenuSee
See Also

Help:

Creating a Menu Bar

Menu Design Window

MouseDown Event

Or Operator

ScaleMode Property

Visible Property


vbmthPopupMenuEx
PopupMenu Method Example

The example displays a pop-up menu at the cursor location when the user clicks the right mouse button over a form.  To try this example, create a form with a menu named "mnuFile" ("mnuFile" must have at least one submenu).  Copy the code into the Declarations section of the form and press F5.

Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)
If Button = 2 Then
PopupMenu mnuFile
End If
End Sub


ANSI Character Set <definition>
ANSI Character Set

American National Standards Institute (ANSI) 8-bit character set used by Microsoft Windows that allows you 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.


application <definition>
application

A collection of code and visual elements that work together as a single program.  Developers can build and run applications within the development environment, while users usually run applications as executable files outside the development environment.


argument <definition>
argument

A constant, variable, or expression passed to a procedure.


array <definition>
array

A set of sequentially indexed elements having the same type.  Each element of an array has a unique index number that identifies it.  Changes made to an element of an array do not affect the other elements.


ASCII Character Set <definition>
ASCII Character Set

American Standard Code for Information Interchange (ASCII) 7-bit character set widely used to represent letters and symbols found on a standard US keyboard.  The ASCII character set is the same as the first 128 characters (0-127) in the ANSI character set.


automatic formatting <definition>
automatic formatting

A Code window feature that automatically formats code as you enter it by capitalizing the first letter for keywords, regularizing spacing, adding punctuation, updating references to variables and procedure names, and setting the foreground colors.


bit-wise <definition>
bit-wise

A bit-by-bit comparison of identically positioned bits in two numeric expressions.


block If <definition>
block If

Any If...Then statement of more than one line; requires End If as the last line of the statement block.


Boolean expression <definition>
Boolean expression

An expression that evaluates to one of two states, such as on or off.  The off state is always zero and is represented by the intrinsic constant False.  The on state has two definitions:  one bit-wise, the other logical.  The bit-wise definition is represented by the intrinsic constant True and always equals -1.  The logical definition is used in testing for conditional expressions in statements such as If condition Then... or While condition...Wend where any expression that evaluates to nonzero (including -1) fulfills the condition.


break mode <definition>
break mode

Temporary suspension of program execution while in the development environment.  In break mode, you can examine, edit, debug, restart, or continue program execution.


breakpoint <definition>
breakpoint

In the development environment, a selected program line at which execution automatically stops, putting the application in break mode.


cascading event <definition>
cascading event

A sequence of events caused by an event procedure directly or indirectly calling itself; also referred to as an event cascade or recursion.  Avoid this situation whenever possible as cascading event procedures often result in a run-time error.


Clipboard <definition>
Clipboard

A temporary storage location used to transfer text, graphics, and code.


collection <definition>
collection

An ordered set of similarly typed objects.  Collection elements are ordered numerically from zero to Count -1.  An object's position in the collection may change whenever a change occurs in the collection.  This makes the position of any specific object in the collection unpredictable.  This characteristic distinguishes a collection from an array, which is similar to a collection, but whose member objects maintain their position in the array unless they are explicitly changed.


command line <definition>
command line

The path, file name, and argument information provided by the user to run a program.


comment <definition>
comment

Text added to code by a programmer that explains how the code works. Each comment line starts with an apostrophe ( ' ) or the keyword Rem followed by a space.


comparison operator <definition>
comparison operator

A character or symbol indicating a relationship between two or more values or expressions:

Symbol	Description

<	Less than

<=	Less than or equal to

> 	Greater than

>=	Greater than or equal to

<> 	Not equal

=	Equal

Additional comparison operators include Is and Like.  Note, however, that Is and Like cannot be used as comparison operators in a Select Case statement.


date separators <definition>
date separators

Characters used to separate the day, month, and year when date values are formatted.  The characters are determined by system settings.


Empty <definition>
Empty

A value that indicates that a variable has not been initialized.  It is equal to 0 (in a numeric context) or zero-length (in a string context).  Empty is not the same as Null which indicates that a variable contains no valid data.


event <definition>
event

An action recognized by an object, such as clicking the mouse or pressing a key, and for which you can write code to respond.  Events can occur as a result of user action or program code, or they can be triggered by the system.


event procedure <definition>
event procedure

A procedure automatically invoked in response to an event initiated by the user, program code, or triggered by the system.


expression <definition>
expression

A combination of functions, operators, variables, and constants that yield a string or numeric result.  An expression can perform a calculation, manipulate characters, or test data.


insertion point <definition>
insertion point

The place where text is inserted when you type; usually indicated by a text cursor.


line label <definition>
line label

A line label is used to identify a single line of code.  It can be any combination of 40 or less characters that start with a letter and end with a colon.  Each line label must be unique within the module where it is used.  Line labels are not case-sensitive and may begin in any column as long as they are the first nonblank characters on the line.


line number <definition>
line number

A line number is used to identify a single line of code. It can be any combination of 40 or less digits that are unique within the module where used.  Line numbers may begin in any column as long as they are the first nonblank characters.

Note	Line numbers greater than 65,529 are treated as line labels and can't be returned by the Erl function.


logic error <definition>
logic error

A programming error that can cause code to produce wrong results or halt execution.  Can be caused by incorrect variable names, wrong variable types, endless loops, flaws in logical comparisons, or array problems.


method <definition>
method

A Sub or Function that operates on an object.


module <definition>
module

The procedures and declarations stored together in a single file and recognized throughout an application.


module level <definition>
module level

The declarations section of a module.


module variable <definition>
module variable

A variable declared outside of a procedure (using the Dim statement) and visible in all procedures in the module.


Null <definition>
Null

A value that indicates that a variable contains no valid data; is the result of:

an explicit assignment of a variable to Null, or

any operation between expressions that contain Null.

Null is not the same as Empty which indicates that a variable has not been initialized.


numeric expression <definition>
numeric expression

A sequence of characters that can be interpreted as a number.  Also, any combination of variables, constants, functions, and operators that an application can evaluate to a number.


procedure <definition>
procedure

A sequence of code statements executed as a unit.  The term procedure refers to both Sub and Function procedures.


procedure level <definition>
procedure level

The location of statements within a Sub or Function procedure.


property <definition>
property

A named attribute of an object.  Properties define object characteristics (such as size, color, screen location) or object behaviors (whether it is enabled, and so on).


run time <definition>
run time

The time when code is running.  During run time, you can interact with the application as a user would.  In contrast, during development time you build the application.


run-time error <definition>
run-time error

An error that occurs when code is running.  A run-time error results when a statement attempts an invalid operation.


seed <definition>
seed

An initial value used to generate pseudo-random numbers.  For example, the Randomize statement accepts a seed number used by the Rnd function to create unique pseudo-random number sequences.


sort order <definition>
sort order

A sequencing principle used to order data; for example, alphabetic, numeric, ascending, descending, and so on.


split bar <definition>
split bar

The thin bar below the title bar of the Code window used to divide the window into two panes.  Each pane can be scrolled separately (both vertically and horizontally).


statement <definition>
statement

A syntactically complete unit that expresses one kind of action, declaration, or definition.  Normally a statement is a single line, although you can use a colon (:) to put more than one statement on a line.


string comparison <definition>
string comparison

A comparison of two sequences of characters.  Comparisons can be either binary or text.  In English, binary comparisons are case-sensitive; text comparisons are not.


string expression <definition>
string expression

Any expression that evaluates to a sequence of contiguous characters.  Elements of the expression may include a function that returns a string, a string literal, a string constant, or a string variable.


syntax checking <definition>
syntax checking

A feature that checks your code for correct syntax.


syntax error <definition>
syntax error

An error that occurs when syntax rules have been broken.


title bar <definition>
title bar

An area at the top of a window that displays the window's caption or name.


twip <definition>
twip

A unit of screen measurement equal to 1/20 of a printers point.  There are approximately 1440 twips to a logical inch or 567 twips to a logical centimeter [image] the length of a screen item measuring one inch or one centimeter when printed.  A twip is a screen-independent unit used to ensure that placement and proportion of screen elements in your screen application are the same on all display systems.  Contrast with pixel, a screen-dependent unit of measurement.


two's complement <definition>
two's complement

A type of base-2 notation used to represent positive and negative in which negative values are formed by complementing all bits and adding 1 to the result.  Complementing is done by changing all 1s to 0, and all 0s to 1.


type-declaration character <definition>
type-declaration character

A character appended to a variable name indicating the variable's data type.  By default, variables are of type Variant unless a corresponding Deftype statement is present in the module.

Character	Data Type

%	Integer

&	Long

!	Single

#	Double

@	Currency

$	String


variable <definition>
variable

A named storage location capable of containing a certain type of data that can be modified during program execution.  Each variable has a unique name that identifies it within its level of scope.  Variable names must be limited to 40 characters, must begin with an alpha character, cannot contain an embedded period, and cannot have the same scope as a procedure name.


watch expression <definition>
watch expression

An expression you define that allows you to observe the behavior of a variable or expression throughout a procedure; used in debugging applications.  Watch expressions appear in the Watch panel of the Debug window when an application enters break mode.  Depending on the type of watch expression, you can choose to break program execution when the expression changes or evaluates to True.


Data Access

See Also	Objects	Properties	Events	Language

Description

The ability to access and manipulate data in databases, and to manage databases and their objects.

Remarks

Using a data control is the easiest way to create applications that allow users access to data in a database.  You can perform most data access operations without writing any code at all.  Controls bound to a data control automatically display data from a specific field for the current record.  If the data control changes to a different record, all bound controls automatically change to display data from the current record.  If a user changes data or enters new information, the changes are automatically saved in the database when the data control moves to a new record.  You can use the Validate event and the DataChanged property to fine-tune your application.

Visual Basic uses the Microsoft Access database engine for its local data access functionality, and Open Database Connectivity (ODBC) for remote data access functionality.

A Database object has a number of other data access objects, such as TableDef objects, Field objects, and so on.  Each object has a set of properties and methods, and some objects have properties that are collections of other objects.  In the same way that a form has a Controls collection, a Database has a TableDefs collection of TableDef objects, and a TableDef has a Fields collection of Field objects.  For example, to set the value of the "PubID" Field in the current record of a data control's Recordset property, you could use this code:

Data1.Database.TableDefs("Publishers").Fields("PubID").Value = 99

In addition, like other controls, data access objects have a default collection and a default property.  For example, the default collection of a recordset is the Fields collection, and the default property of a Field is the Value property.  You can simplify your code by taking advantage of these defaults.  For example, the following code also sets the value of the "PubID" Field in the current record:

Data1.RecordSource = "Publishers"
Data1.Refresh
Data1.Recordset("PubID") = 99

You can include most Visual Basic functions in SQL statements when querying a database, except when using the DB_SQLPASSTHROUGH option with CreateDynaset or CreateSnapshot.  For example, you could use a SQL statement like this:

SELECT PubID, UCase(Left([Company Name], 10) As [Co Name]
FROM Publishers

You must be running SHARE.EXE (from your AUTOEXEC.BAT file) in order to use Visual Basic's data access functionality.

Professional Edition

With the Professional Edition, you can create object variables of any of the object types using the Dim and Set statements.  For example, the following code creates object variables for a Database, a Dynaset, and a Field:

Dim MyDb As Database, MyDn As Dynaset, MyFd As Field
Set MyDb = OpenDatabase("BIBLIO.MDB")
Set MyDn = MyDb.CreateDynaset("SELECT * FROM Authors")
Set MyFd = MyDn.Fields("Au_ID")

You can use object variables and other Data Definition Language (DDL) features to modify the structure of your database.  For example, you can add a new Field to an existing table with the following code:

Dim MyDb As Database, MyFd As New Field
Const DB_TEXT = 10, DB_UPDATABLEFIELD = 32	' Set constants.
Set MyDb = OpenDatabase("BIBLIO.MDB")	' Open database.
MyFd.Name = "Address"	' Set Field properties.
MyFd.Type = DB_TEXT
MyFd.Attributes = DB_UPDATABLEFIELD
MyDb.TableDefs("Authors").Append MyFd	' Append to TableDef.

This code creates a New object variable for a Field, sets the appropriate properties, then adds it to a TableDef with the Append method.  Since a TableDef contains the definition of a Table, the Table now has a Field named "Address" ready for entering data.  In much the same way, you can create new tables and new indexes.

You can use the Delete method to remove objects from the structure of the Database; however, you cannot delete a Field from the Fields collection of a TableDef.


idxDataAccessSee
See Also

Help:

Dim Statement

Left, Left$ Function

New

Set Statement

UCase, UCase$ Function

Data Access Guide

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


idxDataAccessObj
Objects

The controls you can use with data access are:

Check box

Data control

Image

Label

Picture box

Text box

The objects you can use with data access are:

Dynaset Object

Field Object

Fields Collection

Index Object

Indexes Collection

QueryDef Object

Snapshot Object

Table Object

TableDef Object

TableDefs Collection


idxDataAccessProp
Properties

The properties you can use with data access are:

Attributes

BOF

Bookmark

Bookmarkable

CollatingOrder

Connect

DatabaseName

DataChanged

DataField

DataSource

DateCreated

EOF

Filter

LastModified

LastUpdated

LockEdits

NoMatch

OrdinalPosition

Primary

ReadOnly

Recordset

RecordSource

Sort

SourceField

SourceTable

SourceTableName

SQL

Transactions

Updatable


idxDataAccessEvt
Events

The events you can use with data access are:

Error

Reposition

Validate


idxDataAccessMth
Language

The functions and statements you can use with data access are:

BeginTrans Statement

CommitTrans Statement

CompactDatabase Statement

CreateDatabase Function

FreeLocks Statement

OpenDatabase Function

Partition Function

RegisterDatabase Statement

RepairDatabase Statement

Rollback Statement

SetDataAccessOption Statement

SetDefaultWorkspace Statement

The methods you can use with data access objects and controls are:

AddNew Method

Append Method

AppendChunk Method

BeginTrans Method

Close Method

CommitTrans Method

CreateDynaset Method

CreateQueryDef Method

CreateSnapshot Method

Delete Method

DeleteQueryDef Method

Edit Method

Execute Method

FieldSize Method

FindFirst, FindLast, FindNext, FindPrevious Methods

GetChunk Method

ListFields Method

ListIndexes Method

ListParameters Method

ListTables Method

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

OpenQueryDef Method

OpenTable Method

Refresh Method

Rollback Method

Seek Method

Update Method

UpdateControls Method

UpdateRecord Method


Data Control

See Also	Properties	Events	Methods

Description

A data control provides access to data stored in databases, and allows you to move from record to record and display data from each record in bound controls.  Without a data control, you cannot have bound controls on a form.

Remarks

You can perform most data access operations without writing any code at all.  Controls bound to a data control automatically display data from a specific field for the current record.  If the data control moves to a different record, all bound controls automatically change to display the current record.  If a user changes data or enters new information through a control bound to the data control, the changes are automatically saved in the database when the data control moves to a new record.  You can use the Validate event and the DataChanged property to fine-tune your application.

To open a Database with a data control, set the DatabaseName property with the path and name of the data source name, then set the RecordSource property to the name of a Table or QueryDef in the Database.  You can also use an SQL statement in the RecordSource property to specify a recordset.  You can bind controls to a data control only at design time with the DataSource property.

A data control has two properties that are really data access objects: Database and Recordset.  These properties are references to a data control's underlying Database object and Dynaset object.  Database objects and Dynaset objects each have properties and methods of their own, and you can use a data control with these properties and methods to manipulate your data.  For example, the MoveNext method of a Dynaset moves the current record to the next record in the recordset.  To invoke this method, you could use this code:

Data1.Recordset.MoveNext


vbobjQueryControlSee
See Also

Help:

Data Access

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"

Chapter 3, "Creating Programs to Manipulate Data"

Chapter 4, "Using Visual Basic Controls with Data Access Objects"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


vbobjQueryControlProp
Properties

BackColor	FontBold	MousePointer

Caption	FontItalic	Name

Connect	FontName	Options

Database	FontSize	ReadOnly

DatabaseName	FontStrikethru	Recordset

DragIcon	FontUnderline	RecordSource

DragMode	ForeColor	Tag

EditMode	Height	Top

Enabled	Index	Visible

Exclusive	Left	Width


vbobjQueryControlEvt
Events

DragDrop

DragOver

Error

MouseDown

MouseMove

MouseUp

Reposition

Validate


vbobjQueryControlMth
Methods

Drag	Refresh	UpdateRecord

Move	UpdateControls	ZOrder


Dynaset Object

See Also	Properties	Methods

Description

A type of recordset that is the result of a query and that can have updatable records.  Like a Table, a Dynaset has records (rows) and fields (columns).  A Dynaset is a dynamic set of records you can use to add, change, and delete records from the underlying table or tables.  A Dynaset can contain fields from one or more tables in a database.

Remarks

A data control opens a Database and then creates a Dynaset, using the RecordSource property.  The RecordSource property can be the name of a Table or QueryDef in the Database, or it can be an SQL statement.  The Recordset property of a data control is a reference to its underlying Dynaset object.  You can use any property or method of a Dynaset with a data control's Recordset property.

The default collection of a Dynaset is the Fields collection, and the default property of a Field is the Value property.  For example, using the defaults, the following statements are identical:

Data1.Recordset.Fields("PubID").Value = 99
Data1.Recordset("PubID") = 99

In a multiuser environment, various users can open Dynasets referring to the same records.  Because a Dynaset is dynamic, when one user changes a record, other users have immediate access to the changed data.  If a user adds a record, the change is not reflected for any other user until the other user's Dynaset is recreated using the Refresh method.  If a user deletes a record, other users are notified when they try to access that record.  To maintain the integrity of your data, records are locked during Edit and Update operations so that several users can't update the same record at the same time.  There are two kinds of locking: pessimistic and optimistic.

Not all Fields can be updated in all Dynasets.  Use the Updatable property of a Field to discover if it is updatable.

Professional Edition

In the Professional Edition, you can also declare an object variable as a Dynaset type.  To create a Dynaset for an object variable, you would use the CreateDynaset method on a Database or another Dynaset.  You can have more than one object variable that refers to the same set of records.  Also, keep in mind that object variables created with the Dim statement in the Declarations section of a form exist only while the form is open, and are closed when the form unloads.  In the same way, object variables created in a procedure exist only until the procedure has finished.

You can also create a copy of a Dynaset with the Clone method.  This takes less memory than creating a new Dynaset on the same records, and enables you to use the same bookmarks for both.


vbobjDynasetSee
See Also

Help:

Data Access

Field Object

Fields Collection

QueryDef Object

Recordset Property

Snapshot Object

Table Object

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"

Chapter 4, "Using Visual Basic Controls with Data Access Objects


vbobjDynasetProp
Properties

BOF	Fields Collection	NoMatch

Bookmark	LastModified	Transactions

Bookmarkable	LastUpdated	Updatable

DateCreated	LockEdits

EOF	Name

Professional Edition Only

Filter	Sort


vbobjDynasetMth
Methods

AddNew	FindLast	MoveNext

Clone	FindNext	MovePrevious

Delete	FindPrevious	Update

Edit	MoveFirst

FindFirst	MoveLast

Professional Edition Only

CreateDynaset	ListFields

CreateSnapshot


Fields Collection

See Also	Properties	Methods

Description

A collection of Field objects.  A Fields collection can be found in all recordset objects (Table, Dynaset, Snapshot), and in a TableDef object.

Remarks

The default collection of a recordset is the Fields collection, and the default property of a Field is the Value property.  You can simplify your code by taking advantage of these defaults.  For example, using the defaults, the following statements are identical:

Data1.Recordset.Fields("PubID").Value = 99
Data1.Recordset("PubID") = 99

Like a Table, a Field has a name that is recognized by the Database.  The Name property of a Field is not the same as the name of an object variable to which it is assigned.  Unlike forms and controls, the Name property of a Field object is available at run time.

You can access the individual members of a collection one of two ways:

By number (ordinal position) as you would with the Forms collection or the Controls collection of a Form object:
Fields(0)

By name, which is unique to data access objects:
Fields("PubID")

The Fields collection is not the same as the Fields property of an Index object.

Professional Edition

In the Professional Edition, you can declare an object variable as type Fields (a collection), or as type Field.


vbobjFieldsCollectionSee
See Also

Help:

Data Access

Data Control

Dynaset Object

Field Object

Fields Property

Recordset Property

Snapshot Object

Table Object

TableDef Object

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


vbobjFieldsCollectionProp
Property

Count


vbobjFieldsCollectionMth
Methods

Append

Delete

Refresh


Indexes Collection

See Also	Properties	Methods

Description

A collection of Index objects.  An Indexes collection can be found in Table and TableDef objects.

Remarks

The default collection of a TableDef is the Fields collection.  The default property of an Index is the Name property.  You can simplify your code by taking advantage of these defaults.  For example, using the defaults, the following statements are identical in that they both print the list of field names in an Index with a data control:

Print Data1.Database.TableDefs("Authors").Indexes(0).Fields
Print Data1.Database("Authors").Indexes(0).Fields

Note that the Fields collection of a recordset is not the same as the Fields property of an Index object.

Index objects are stored with a TableDef in a Database, and like a Table and a Field, an Index has a name that is recognized by the Database.  The Name property of an Index object is not the same as the name of an object variable to which it has been assigned.  Unlike forms and controls, the Name property of an Index object is available at run time.

Professional Edition

In the Professional Edition, you can declare an object variable as type Indexes (a collection) or as type Index.


vbobjIndexesCollectionSee
See Also

Help:

Fields Collection

Fields Property

Index Object

Data Access Guide:

Chapter 1, "Introduction to Data Access with Visual Basic"

Chapter 2, "Database Management Using Visual Basic"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


vbobjIndexesCollectionProp
Property

Count


vbobjIndexesCollectionMth
Methods

Append

Delete

Refresh


Snapshot Object (Professional Edition Only)

See Also	Properties	Methods

Description

A type of recordset that is the result of a query and that does not have updatable records.  Like a Table, a Snapshot has records (rows) and fields (columns).  A Snapshot is a static picture of a set of records you can use to find data or generate reports.  A Snapshot can contain fields from one or more tables in a database.

Remarks

In the Professional Edition, you can declare an object variable as a Snapshot type.  To create a Snapshot for an object variable, use the CreateSnapshot  method on a Database, Dynaset, or another Snapshot.  You can have more than one Snapshot object variable containing the same set of records.

Like all recordsets, when you create a Snapshot, the first record is the current record, and you can use any of the Move methods, such as MoveNext, to move the current record to a different record.  You can also use the Find methods, such as FindFirst, to move to a specific record.  To cycle through all records, you can use the BOF and EOF properties to check for the beginning or end of the Snapshot.


vbobjSnapshotSee
See Also

Help:

CreateDynaset Method

Dynaset Object

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


vbobjSnapshotProp
Properties

BOF	EOF

Bookmark	NoMatch

Bookmarkable

Professional Edition Only

Filter	Sort


vbobjSnapshotMth
Methods

Clone	FindLast	MoveFirst

Close	FindNext	MoveLast

CreateSnapshot	FindPrevious	MoveNext

FindFirst	ListFields	MovePrevious


Table Object (Professional Edition Only)

See Also	Properties	Methods

Description

A table is a type of recordset that is a part of a Database and contains data about a particular subject.  A Table object is a logical representation of a physical table.  Like all recordsets, a table has records (rows) and fields (columns).

Remarks

With a data control, you can open a table only by setting the control's RecordSource property to the name of the table.  When the data control loads, it creates a Dynaset based on the table.  Table objects can be used only in the Professional Edition.  You can, however, access the data in a table through the Dynaset created by a data control and represented by its Recordset property.

The Name property of a Table object is not the same as the name of an object variable to which it is assigned.  Unlike forms and controls, the Name property of a Table object is available at run time.

You can declare an object variable as a Table type.  To open a Table with an object variable, use the OpenTable method on a Database.  You can have more than one object variable that refers to the same table, and you can have one or more Dynasets that refer to some or all fields and some or all records in one or more tables.

The default collection of a Table is the Fields collection, and the default property of a Field is the Value property.  You can simplify your code by taking advantage of these defaults.  For example, the following lines of code both set the value of the "PubID" Field in the current record of a Table object:

MyTable.Fields("PubID").Value = 99
MyTable("PubID") = 99

Information about the structure of a table, such as the name and field data type of each Field, is stored in a TableDef.


vbobjTableSee
See Also

Help:

OpenTable Method

TableDef Object

TableDefs Collection

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"


vbobjTableProp
Properties

BOF	Fields Collection	NoMatch

Bookmark	LastModified	Transactions

Bookmarkable	LastUpdated	Updatable

DateCreated	LockEdits

EOF	Name


vbobjTableMth
Methods

AddNew	FindFirst	MoveFirst

Close	FindLast	MoveLast

CreateDynaset	FindNext	MoveNext

CreateSnapshot	FindPrevious	MovePrevious

Delete	ListFields	Seek

Edit	ListIndexes	Update


TableDefs Collection

See Also	Properties	Methods

Description

A collection of TableDef objects.  A TableDef collection can be found in a Database object.

Remarks

The default collection of a Database is the TableDefs collection, and the default collection of a TableDef is the Fields collection.  The default property of a TableDef is the Name property.  You can simplify your code by taking advantage of these defaults.  For example, the following statements are identical in that they both print the number corresponding to the field data type of a Field in a TableDef using a data control:

Print Data1.Database.TableDefs("Publishers").Fields("PubID").Type
Print Data1.Database("Publishers")("PubID").Type

The Name property of a TableDef object is not the same as the name of an object variable to which it is assigned.  Unlike forms and controls, the Name property of a TableDef object is available at run time.

Professional Edition

In the Professional Edition, you can create an object variable of type TableDefs (a collection) as well as type TableDef.  For example, you could use this code to print the field data type:

Dim MyDb As Database, MyTableDef As TableDef
Set MyDb = OpenDatabase("BIBLIO.MDB")
Set MyTableDef = MyDb("Publishers")
Print MyTableDef("PubID").Type

To make changes in the structure of a table, such as adding a Field

1.	Make sure the Table is closed by all users.

2.	Create a New Field object variable and set its properties.

3.	Add the Field to the Fields collection of the TableDef with the Append method.

In cases where the data is stored in another database, the table is said to be "attached" to the database.  Attached tables are stored in external databases or are tables not in the Microsoft Access format [image] they are linked to the database by way of the SourceTableName and Connect properties of the TableDef object.  Attached tables behave as if their data is stored as part of the database.

To attach a table to a database

1.	Dim a new TableDef object.

2.	Set its Connect and SourceTableName properties (and optionally, its Attributes property).

3.	Add it to the TableDefs collection of a Database with the Append method.

You cannot delete a Field from a TableDefs collection.


vbobjTableDefsCollectionSee
See Also

Help:

Data Access

TableDef Object

Data Access Guide:

Chapter 3, "Creating Programs to Manipulate Data"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


vbobjTableDefsCollectionProp
Property

Count


vbobjTableDefsCollectionMth
Methods

Append (Professional Edition Only)

Delete (Professional Edition Only)


Field Object

See Also	Properties	Methods

Description

A part of a recordset that defines one column of data.  The Value property of a Field object contains data from a single element of that column from the current record.

Remarks

Field objects are stored with a TableDef in a Database, and like a Table, a Field has a name that is recognized by the Database.  The default collection of a recordset is the Fields collection.  You can simplify your code by taking advantage of defaults.  For example, both of the following code lines print the value of the "PubID" Field in the current record of a data control:

Print Data1.Recordset.Fields("PubID").Value
Print Data1.Recordset("PubID")

The Name property of a Field object is not the same as the name of an object variable to which it is assigned.  Unlike forms and controls, the Name property of data access objects is available at run time.

Professional Edition

In the Professional Edition, you can declare an object variable as type Fields (a collection), or as a type Field.  You could use this code to print out the value of the "PubID" Field for each record in a Dynaset:

Dim MyDb As Database, MyDn As Dynaset, MyFd As Field
Set MyDb = OpenDatabase("BIBLIO.MDB")
Set MyDn = MyDb.CreateDynaset("Publishers")
Set MyFd = MyDb("PubID")
Do While Not MyDn.EOF
Print MyFd
MyDn.MoveNext
Loop


vbobjFieldObjectSee
See Also

Help:

BOF Property

Data Access

EOF Property

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


vbobjFieldObjectProp
Properties

Attributes	OrdinalPosition	SourceTable

CollatingOrder	Size	Type

Name	SourceField	Value


vbobjFieldObjectMth
Methods

Append (Professional Edition Only)

AppendChunk

FieldSize

GetChunk


Index Object

See Also	Properties

Description

An object contained in the Indexes collections of Table and TableDef objects.  Indexes are used to order records by one or more key fields within a table.  They speed up the process of finding records, and can enforce unique values in each field named in the Index.  An Index is stored in the database as a retrievable object.  A table can have none, one, or more indexes.

Remarks

The Name property of an Index object is not the same as the name of an object variable to which it is assigned.  Unlike forms and controls, the Name property of an Index object is available at run time.

Professional Edition

In the Professional Edition, you can declare an object variable as an Index type.

A Table usually should have an index uniquely identifying each record, called a "primary key" index.  A primary key index is indicated with the Primary property of an Index object.

Although an Index can help find records quickly, if you are frequently updating a table with several indexes, it can actually slow down the updating process.  Creating a new Index on a table with many existing records can be a very lengthy process.  If there is no Index on a Table, finding records can be a lengthy process also.

To create an index for a Table

1.	Create a New Index object.

2.	Set its properties.

3.	Add it to the Indexes collection of a TableDef with the Append method.

An index can include one or more key fields.  The key fields of an index are defined in the Fields property of an Index object.  The Fields collection of a TableDef or recordset is not the same as the Fields property of an Index object.

The Seek method of a Table uses an index of the Table to find specific records.


vbobjIndexObjectSee
See Also

Help:

Indexes Collection

Seek Method (Professional Edition Only)

TableDef Object

TableDefs Collection

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"

Programmers Guide:

Chapter 20, ""Accessing Databases with the Data Control


vbobjIndexObjectProp
Properties

Fields	Primary

Name	Unique


TableDef Object

See Also	Properties

Description

An object in a database that defines the structure of a table.  In contrast, a Table is the physical container of the data in a Database.

Remarks

With a data control, you can examine the structure of a table using the TableDefs collection of the data control's Database property.  For example, you can read the Count property of the Fields collection to determine how many Field objects are in a Table, and then read the Field names.  For example, the following code prints all Field names in a TableDef:

Dim I
For I = 0 to Data1.Database.TableDefs("Publishers").Fields.Count - 1
Print Data1.Database.TableDefs("Publishers").Fields(I).Name
Next I

A table is stored in a database and has a name that is recognized by the database.  A TableDef has a Name property that is the name of the table defined by the TableDef.  The Name property of a TableDef is not the same as the name of an object variable to which it is assigned.  Unlike forms and controls, the Name property of a TableDef object is available at run time.

The default collection of a Database is the TableDefs collection, and the default collection of a TableDef and all recordsets is the Fields collection.  The default property of a TableDef is the Name property.  You can simplify your code by taking advantage of these defaults.  For example, both of the following code lines print the name of the first table in the TableDefs collection:

Print Data1.Database.TableDefs(0).Name
Print Data1.Database(0)

Professional Edition

In the Professional Edition, you can create an object variable of type TableDefs as well as type TableDef.  You can make changes in the structure of a table, and even create new tables in a database.

To create a Table in a Database ready for new records

1.	Create a New TableDef.

2.	Set its properties.

3.	Create New Field objects, set their properties, and add them to the Fields collection of the TableDef with the Append method.

4.	Use the Append method to add the new TableDef to the TableDefs collection of the Database.


vbobjTableDefSee
See Also

Help:

Append Method

Delete Method

New

Table Object

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


vbobjTableDefProp
Properties

Attributes	Fields Collection	Name

Connect	Indexes Collection	SourceTableName

DateCreated	LastUpdated	Updatable


QueryDef Object

See Also	Properties	Methods

Description

A definition of a query stored in a database.

Remarks

You can use the name of an existing QueryDef in the RecordSource property of a data control just as you would use the name of a Table to define the records in the control's Dynaset.

The default property of a QueryDef object is the Name property.

Professional Edition

In the Professional Edition, you can create an object variable of type QueryDef.  When you create a Dynaset or Snapshot using an SQL query, the query is stored in your code.  Instead of repeatedly creating often-used queries in code, you can use the CreateQueryDef method to create a QueryDef that is saved in the Database.

Like a Table, a QueryDef has a name recognized by the Database.  The name of a QueryDef is not the same as the name of an object variable to which it has been assigned.  Unlike controls and forms, the Name property of a QueryDef object is available at run time.

The TableDefs collection of a Database also lists available QueryDefs.  To discover whether a listed TableDef is really a QueryDef, use the ListTables method.


vbobjQueryDefSee
See Also

Help:

Attributes Property

CreateQueryDef Method (Professional Edition Only)

DeleteQueryDef Method (Professional Edition Only)

TableDefs Collection

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"

Chapter 3, "Creating Programs to Manipulate Data"


vbobjQueryDefProp
Properties

Name

SQL


vbobjQueryDefMth
Methods

Close

Execute

Professional Edition Only

CreateDynaset

CreateSnapshot

ListParameters


Clone Method (Professional Edition Only)

See Also	Example

Description

Returns a duplicate recordset object that refers to the same recordset from which it was created.

Syntax

Set recordset2 = recordset1.Clone( )

Remarks

The Clone method uses the following parts:

Part	Description

recordset1	The Recordset property of a data control or an object variable identifying an open Table, Dynaset or Snapshot.

recordset2	An object variable of the same type as recordset1.

Use the Clone method to create duplicate recordset objects where each has its own current record.  Using Clone doesn't affect the data in the original recordset or in the underlying tables.  However, you can change, add, and delete records with the clone of a Dynaset just as with the original.

You might use Clone when you want to perform an operation on a recordset requiring multiple current records.  This is faster and more efficient than creating a second Dynaset.

Bookmarks are valid between recordsets and their clones, but not between recordsets created with separate CreateDynaset or CreateSnapshot methods.


vbmthCloneSee
See Also

Help:

Bookmark Property

Close Method

CreateDynaset Method

CreateSnapshot Method

OpenTable Method

Recordset Property


vbmthCloneEx
Clone Method Example

The example creates a duplicate Dynaset from the recordset of a data control, and then in the Validate event, searches for a duplicate record in the cloned Dynaset in order to validate the entry when a user is attempting to add a new record.

' Declarations section.
Dim MyDup As Dynaset
...

Sub Form_Load ()
Data1.DatabaseName = "BIBLIO.MDB"	' Set data properties.
Data1.RecordSource = "Authors"
Data1.Refresh	' Open database.
Set MyDup = Data1.Recordset.Clone()	' Clone recordset.
...
Sub Data1_Validate ()
' Make sure a change has taken place.
If Not Text1.DataChanged Then Exit Sub
' In the cloned recordset, find a matching record.
MyDup.Find "Author = " & Text1.Text
If Not MyDup.NoMatch Then	' If a match is found...
...


ListParameters Method (Professional Edition Only)

See Also	Example

Description

Creates a Snapshot with one record for each parameter in a specified QueryDef object.

Syntax

Set snapshot = querydef.ListParameters( )

Remarks

The ListParameters method uses the following parts:

Part	Description

snapshot	An object variable of type Snapshot.

querydef	An object variable identifying an open QueryDef containing the parameters you want to list.

The records in the Snapshot are in the same order as the parameters in the specified QueryDef.  If the QueryDef has no parameters, the Snapshot will have no records.  The fields in the Snapshot are:

Field	Data type	Description

Name	String	Name of the parameter.

Type	Long	A number corresponding to the field data type.  See table below.

The values and symbolic constants (from DATACONS.TXT) for the Type field in the Snapshot are:

Constant	Value	Description

DB_BOOLEAN	1	True/False

DB_BYTE	2	Byte

DB_INTEGER	3	Integer

DB_LONG	4	Long

DB_CURRENCY	5	Currency

DB_SINGLE	6	Single

DB_DOUBLE	7	Double

DB_DATE	8	Date/Time

DB_TEXT	10	Text

DB_LONGBINARY	11	Long Binary

DB_MEMO	12	Memo

You can't use the Find methods, such as FindFirst, on a Snapshot created with ListParameters.  The Fields collection is not available in Snapshots created by the ListTables, ListFields, ListIndexes, and ListParameters methods; therefore, you can't access the field values using an index into the Fields collection.  To access the field values, you must explicitly use the name of each field.


vbmthListParametersSee
See Also

Help:

Fields Collection

ListFields Method

ListIndexes Method

QueryDef Object

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


vbmthListParametersEx
ListParameters Method Example

The example creates a Snapshot with the ListParameters method, then prints the field names and values in the Debug window.  To run the example, paste the code over the Form_Click event procedure code and press F5 to run your program.  Click the form to run the procedure.

Sub Form_Click ()
Dim Db As Database, Qd As QueryDef, Sn As Snapshot, I As Integer
Set Db = OpenDatabase("BIBLIO.MDB")	' Open a database.
Set Qd = Db.OpenQueryDef("Get State")	' Open a QueryDef.
Set Sn = Qd.ListParameters()	' Get parameters of query.
Debug.Print "Name", "Type"	' Print column heads.
Do While Not Sn.EOF	' Print each value.
Debug.Print Sn("Name"),
Debug.Print Sn("Type")
Sn.MoveNext	' Move to next record.
Loop
End Sub


Primary Property

See Also	Example (Professional Edition Only)

Applies To

Index object.

Description

Determines if an Index can be used to uniquely identify each record in a table.  Not available at design time; read-only when the Index is a member of a collection.  Read/write only in the Professional Edition with a new object not yet appended to a collection.

Syntax

index.Primary [ = { True | False }]

Remarks

Many relational database management system (DBMS) products require at least one unique index, called a "primary key," on every table.  Microsoft Access allows tables without a primary key, but if the table grows large, finding records can be slow and you cannot use queries that create joins between it and any other table.

Only one index per table can be a Primary index.

In the Professional Edition, when you create a new table in your database, it's a good idea to create an index on one or more fields that uniquely identifies each record, then set the Primary property of the Index object to True.

Data Type

Integer (Boolean)


vbproPrimarySee
See Also

Help:

Append Method

Data Access

Delete Method

Index Object

Indexes Collection

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


vbproPrimaryEx
Primary Property Example (Professional Edition Only)

The example creates a new Table and primary key Index, then adds it to the TableDefs collection of a Database.

Dim Db As Database, Tb As New TableDef, Idx As New Index
Dim Fd1 As New Field, Fd2 As New Field
Set Db = OpenDatabase("BIBLIO.MDB")	' Open the Database.
Tb.Name = "Book Types"	' Set new Table property.
Fd1.Name = "TypeNum"	' Set Fd1 Field properties.
Fd1.Type = 4
Tb.Fields.Append Fd1	' Add Fd1 Field to TableDef.
Fd2.Name = "Type"	' Set Fd2 Field properties.
Fd2.Type = 10
Fd2.Size = 15
Tb.Fields.Append Fd2	' Add Fd2 Field to TableDef.
Idx.Name = "PrimaryKey"	' Set properties in new Index.
Idx.Unique = True
Idx.Primary = True
Idx.Fields = "TypeNum"
Tb.Indexes.Append Idx	' Add Index to TableDef.
Db.TableDefs.Append Tb	' Add TableDef to Database.


OLE Control

See Also	Properties	Events	Methods

Description

Object linking and embedding (OLE) is a technology that allows a programmer of Windows-based applications to create an application that can display data from many different applications, and allows the user to edit that data from within the application in which it was created.  In some cases, the user can even edit the data from within the Visual Basic application.  The Visual Basic OLE control provides an interface to this technology.

Using the OLE Control

You use the OLE control to display an OLE object on a form.  You either create the object at design time using standard OLE dialogs (Insert Object, Paste Special), or at run time by setting the appropriate properties.

Using the OLE Control's Pop-up Menus

Each time you draw an OLE control on a form, the Insert Object dialog is displayed.  You use this dialog to create a linked or embedded object.  By choosing Cancel, an object is not created.

At design time, you click the OLE control with the right mouse button to display a pop-up menu.  The commands displayed on this pop-up menu depend on the state of the OLE control as displayed in the following table:

Command	Enabled in pop-up when...

Insert Object 	this command is always enabled.

Paste Special	the Clipboard contains a valid OLE object.

Delete Embedded Object	the OLE control contains an embedded object.

Delete Linked Object	the OLE control contains a linked object.

Create Link	the SourceDoc property is set.

Create Embedded Object  	the Class or SourceDoc property is set.

OLE Fundamentals

The following terms and concepts are fundamental to understanding the OLE control.

OLE Object

An OLE object refers to a discrete unit of data supplied by an OLE application.  An application can expose many types of objects.  For example a spreadsheet application can expose a worksheet, macro sheet, chart, cell, or range of cells [image] all as different types of objects.

You use the OLE control to create linked and embedded objects.  When a linked or embedded object is created, it contains the name of the application that supplied the object, its data (or, in the case of a linked object, a reference to the data), and an image of the data.  An OLE control can contain only one object at a time.  There are several ways to create a linked or embedded object:

Use the Insert Object or Paste Special dialogs (run time and design time).

Set the Class property in the Properties window, then click the OLE control with the right mouse button and select the appropriate command (design time only).

Set the Action property of the OLE control (run time only).

OLE Automation

Some applications provide objects that support OLE Automation.  You can use Visual Basic to programmatically manipulate the data in these objects.  Some objects that support OLE Automation also support linking and embedding.  If an object in the OLE control supports OLE Automation, you can access its data using the Object property.

You can create an OLE Automation object without the OLE control using the CreateObject function.

Class

An objects class determines the application that provides the objects data and the type of data the object contains.  The class names of some commonly used Microsoft applications include MSGraph, MSDraw, WordDocument, and ExcelWorksheet.  You can get a list of the class names available to your application by selecting the Class property in the Properties window and clicking on the three dots in the Settings box.

Note   The Insert Object dialog does not display a list of class names.  This dialog displays user-friendly names for each class of object, which are generally longer and more easily understood.

Container Application

An application that receives and displays an objects data is a container application.  For example, a Visual Basic application that uses an OLE control to embed or link data from another application is a container application.

In Visual Basic 2.0, applications that provide access to objects were called server or source applications.  Applications used to contain objects were referred to as client or destination applications.

Linked and Embedded Objects

You use an OLE control to incorporate data into a Visual Basic application by linking or embedding data from another application.  Data associated with a linked object is stored by the application that supplied the object; the OLE control stores only link references that enable display of snapshots of the source data.  Data associated with an embedded object is contained in an OLE control and can be saved by your Visual Basic application.

When an object is linked, the object's data can be accessed from any application containing a link to that data and can be changed from within any of them.  For example, if a text file is linked to a Visual Basic application, it can be modified by any other application linked to it.  The modified version will appear in all the documents linked to this text file.

When you use an OLE control to create an embedded object, all the data associated with the object is contained in the OLE control.  For example, if a spreadsheet were an embedded object, all the data associated with the cells would be contained in the OLE control, including any necessary formulas.  The name of the application that created the object is saved along with the data.  If the user selects the embedded object while working with the Visual Basic application, the spreadsheet application can be started automatically for editing those cells.  When an object is embedded into an application, no other application has access to the data in the embedded object.  Embedding is useful when you want only your application to maintain data that is produced and edited in another application.


Properties

Action	HelpContextID	OleTypeAllowed

AppIsRunning	HostName	OleType

AutoActivate	hWnd	Parent

AutoVerbMenu	Index	PasteOK

BackColor	Left	Picture

BorderStyle	lpOleObject	SizeMode

Class	Name	SourceDoc

Data	ObjectAcceptFormatsCount	SourceItem

DataText	ObjectAcceptFormats	Tag

DisplayType	ObjectGetFormatsCount	Top

DragIcon	ObjectGetFormats	UpdateOptions

DragMode	Object	Verb

FileNumber	ObjectVerbFlags	Visible

Format	ObjectVerbsCount	Width

Height	ObjectVerbs


Events

Click	KeyDown	MouseMove

DblClick	KeyPress	MouseUp

DragDrop	KeyUp	Resize

DragOver	LostFocus	Updated

GotFocus	MouseDown


Methods

Drag

Move

Refresh

SetFocus

ZOrder


See Also

Help:

CreateObject Function

GetObject Function

Open Statement

Using Custom Controls

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"

Chapter 23, "Programming Other Applications' Objects"


Distributing OLE Applications

See Also

When you create and distribute applications that use the OLE control, you should install the following files in the customers Microsoft Windows \SYSTEM directory:

COMPOBJ.DLL

MSOLE2.VBX

MSOLEVBX.DLL

OLE2.REG

OLE2.DLL

OLE2CONV.DLL

OLE2DISP.DLL

OLE2NLS.DLL

OLE2PROX.DLL

STORAGE.DLL

VBOA300.DLL

The OLE control can be used only on systems running Microsoft Windows version 3.1 or later.

You also need to make sure OLE 2.0 is registered on the users machine and that SHARE.EXE is installed in the users AUTOEXEC.BAT file (SHARE.EXE is not required if the user is running Microsoft Windows for Workgroups).  Use the SetupWizard to create distribution disks that do this.  When specifying files to distribute, choose Add OLE Files from the Options menu.

To install OLE 2.0 without using the SetupWizard or the Setup Toolkit

1.	Check to see if OLE 2.0 has already been installed.  If OLE2.DLL is on the users machine, then OLE 2.0 has already been installed.  If the user does not have the most current version of OLE2.DLL, you can install the new version using the following steps.

2.	Copy the above files to the users \WINDOWS\SYSTEM directory.

3.	Register OLE 2.0 using the following command line:
REGEDIT /S OLE2.REG


howOLEAppSee
See Also

Help:

Creating Your Distribution Disks

Files You Are Allowed to Distribute

Files You Need to Distribute

How to Use the Setup Kit

Overview

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


Action Property (OLE)

See Also

Applies To

OLE control.

Description

Determines an action to take.  Not available at design time; write-only at run time.

Usage

[form.]ole.Action = setting

Setting

By setting the Action property at run time, you can perform the following operations:

Setting 	Description

0	OLE_CREATE_EMBED [image] creates an embedded object.

To use this action, you must first set the Class and OleTypeAllowed properties.  Set the OleTypeAllowed property to 1 (Embedded) or 2 (Either).  The Class property determines the type of OLE object to create.  To view a list of valid class names on your system, select the Class property in the Properties window and click the three dots (...) in the Settings box.

When you create a new OLE object, the executable file associated with the class name (for example, EXCEL.EXE) must either be active or on the system's path.

1	OLE_CREATE_LINK [image] creates a linked OLE object from the contents of a file.

To use this action, you must first set the OleTypeAllowed and SourceDoc properties.  Set OleTypeAllowed to 0 (Linked) or 2 (Either).  The SourceDoc property specifies the file from which the OLE object is created.  You can also set the SourceItem property (for example, a row/column range specification if the application creating the object is a Microsoft Excel worksheet).

When an OLE object is created with this action, the OLE control simply displays an image of the file specified by the SourceDoc property.  If the OLE object is saved, only the link references are saved, since the OLE control contains only a metafile image of the data and no source data.

When creating a new OLE object, the executable file associated with the class name (for example, EXCEL.EXE) must either be active or on the system's path.

2 	Reserved for future use.

3 	Reserved for future use.

4	OLE_COPY [image] copies the object to the Clipboard.

When an OLE object is copied to the Clipboard, all the data and link information associated with the object is placed on the Clipboard.  You can copy both linked and embedded objects to the Clipboard.

You can use this action to support an Edit Copy command.

5	OLE_PASTE [image] copies data from the Clipboard to an OLE control.

To use this action, set the OleTypeAllowed property, and then check the value of the PasteOK property.  You cannot paste successfully unless PasteOK returns a value of True.

If the Paste was successful, the OleType property will be set to 0 (Link) or 1 (Embed).  If the Paste was not successful, the OleType property will be set to 3 (None).

You can use this action to support an Edit Paste command.

See the PasteOK property topic for more information and an example.

6	OLE_UPDATE [image] retrieves the current data from the application that supplied the object and displays that data as a picture in the OLE control.

7	OLE_ACTIVATE [image] opens an OLE object for an operation, such as editing.

To use this action, first set the Verb property.  The Verb property specifies the operation to perform when the OLE object is activated.

If you set the AutoActivate property to 2 (Double-Click), the OLE control will automatically activate the current object when the user double-clicks the control.

8	Reserved for future use.

9	OLE_CLOSE [image] closes an OLE object and terminates the connection with the application that provided the object.  This action applies to embedded objects only.  It has no effect on linked objects.

This action is equivalent to the user choosing Close from the object's Control-menu box.

10	OLE_DELETE [image] deletes the specified OLE object and frees the memory associated with it.

This action allows the programmer to explicitly delete an OLE object.  Objects are automatically deleted when a form is closed or when the object is updated to a new object.

11	OLE_SAVE_TO_FILE [image] saves an OLE object to a data file.

To use this action, first set the FileNumber property.  The FileNumber property must correspond to an open, binary file.

If the OLE object is linked (OleType = 0, Linked), then only the link information and an image of the data is saved to the specified file.  The object's data is maintained by the application that created the object.  If the OLE object is embedded (OleType = 1, Embedded), the object's data is maintained by the OLE control and can be saved by your Visual Basic application.

See the FileNumber property topic for an example.

12	OLE_READ_FROM_FILE [image] loads an OLE object from a data file created using the SaveToFile action.

To use this action, first set the FileNumber property.  The FileNumber property must correspond to an open, binary file.

See the FileNumber property topic for an example.

13	Reserved for future use.

14	OLE_INSERT_OBJ_DLG [image] displays the Insert Object dialog.  At run time, you display this dialog to allow the user to create a linked or embedded object.  Using this dialog, the user chooses the type of object (linked or embedded) and the application that is to provide the object.

Use the OleTypeAllowed property to determine the type of object that can be created (linked, embedded, either) using this dialog.

15	OLE_PASTE_SPECIAL_DLG [image] displays the Paste Special dialog.  At run time, you display this dialog to allow the user to paste an object from the Clipboard.  This dialog displays several options to the user, including pasting either a linked or embedded object.

Use the OleTypeAllowed property to determine the type of object that can be created (linked, embedded, either) using this dialog.

16	Reserved for future use.

17	OLE_FETCH_VERBS [image] updates the list of verbs an object supports.

18	OLE_SAVE_TO_OLE1FILE [image] Saves an object to the OLE1 file format.

Note	Constants for Action property settings are defined in the Visual Basic file CONSTANT.TXT.

Data Type

Integer (Enumerated)


See Also

Help:

AppIsRunning Property

AutoActivate Property

Class Property

FileNumber Property

OleType Property

OleTypeAllowed Property

PasteOK Property

SourceDoc Property

SourceItem Property

UpdateOptions Property

Verb Property

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


AppIsRunning Property

See Also

Applies To

OLE control.

Description

Indicates whether the application that created the object in the OLE control is currently activated and running.  Not available at design time; read-only at run time.

Usage

[form.]ole.AppIsRunning

Setting

The AppIsRunning property settings are:

Setting 	Description

True 	The application that produced the object in the OLE control is currently running.

False	The application that produced the object in the OLE control is not currently running.

Data Type

Integer (Boolean)


See Also

Help:

Action Property

OleType Property

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


AutoActivate Property

See Also

Applies To

OLE control.

Description

Allows the user to activate an object by double-clicking the OLE control, or by giving the OLE control the focus.

Usage

[form.]ole.AutoActivate = [setting ]

Setting

The AutoActivate property settings are:

Setting 	Description

0 	Manual.  The OLE object is not automatically activated.  You can activate an object programmatically by setting Action = 7 (OLE_ACTIVATE).

1	Focus.  If the OLE control contains an object, the application that provided the object will be activated when the OLE control gets the focus.

2	(Default) Double-Click.  If the OLE control contains an object, the application that provided the object will be activated when the user double-clicks the OLE control or presses Enter when the control has the focus.

Remarks

You can determine if the OLE control contains an object by querying the OleType property.

Some objects can be activated from within the OLE control.  When such an object is activated, the user can edit the object (or perform some other action) from inside the boundaries of the OLE control.  This feature is called In-Place Activation.  If an object supports In-Place Activation, you can set AutoActivate to 1 (Focus) to activate an object when the OLE control gets the focus.

Note   When AutoActivate is set to 2 (Double-Click), the DblClick event does not occur when the user double-clicks an OLE control.

Data Type

Integer (Enumerated)


See Also

Help:

Action Property

OleType Property

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


AutoVerbMenu Property

See Also

Applies To

OLE control.

Description

Determines if a pop-up menu containing the object's verbs is displayed when the user clicks the OLE control with the right mouse button.

Usage

[form.]ole.AutoVerbMenu[ = boolean ]

Setting

The AutoVerbMenu property settings are:

Setting 	Description

True 	(Default) When the user clicks the OLE control with the right mouse button, a pop-up menu is displayed showing the commands the object supports.

False	No pop-up menu is displayed.

Remarks

When this property is set to True, Click events and MouseDown events do not occur when the OLE control is clicked with the right mouse button.

Data Type

Integer (Boolean)


See Also

Help:

Action Property

ObjectVerbs Property

ObjectVerbsCount Property

Verb Property

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


Class Property

See Also

Applies To

OLE control.

Description

Determines the class name of an embedded OLE object.

Usage

[form.]ole.Class [ = classname ]

Remarks

A class name defines the type of an OLE object.  For example, Microsoft Excel version 4.0 supports three types of OLE objects [image] spreadsheets, charts, and macro sheets.  Their class names are "ExcelWorksheet," "ExcelChart," and "ExcelMacrosheet," respectively.

When you create an object at design time using the Insert Object or Paste Special dialogs, the class of the new object is automatically entered in the Properties window.

To view a list of class names available on your system, select the Class property in the Properties window and click the three dots (...) in the Settings box.

This property is updated when an object is copied from the Clipboard.  For example, if a Microsoft Excel chart is pasted from the Clipboard to an OLE object that previously contained a Microsoft Excel worksheet, the Class property changes from "ExcelChart" to "ExcelWorksheet."  You can paste an object from the Clipboard by setting Action = 5 (Paste), or Action = 15 (Paste Special Dialog).

Note   With the advent of OLE2 and OLE Automation, the syntax for the Class property will change.  Applications that are updated to support OLE2 or OLE Automation will define their objects using the following syntax:

"applicationname.objecttype"

Applicationname specifies the name of the application supplying the object.  Objecttype specifies the object's type (for example, worksheet, chart, macro sheet).

Data Type

String


See Also

Help:

Action Property

PasteOK Property

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


Data Property

See Also

Applies To

OLE control.

Description

Determines a handle to a memory or graphical device interface (GDI) object containing data in a specified format.  Not available at design time.

Usage

[form.]ole.Data [ = data ]

Remarks

Set this property to send data to an application that created an object.  Before using the Data property, set the Format property to determine the type of data contained in the memory or GDI object.

You can get a list of acceptable formats for an OLE object using the ObjectAcceptFormats and ObjectGetFormats properties.

Setting this property to 0 frees the memory associated with the handle.

OLE Automation provides an easier and more reliable solution for sending data and commands to and from an object.  If an object supports OLE Automation, you can access the object through the Object property, or using the CreateObject and GetObject functions.

Data Type

Long


See Also

Help:

CreateObject Function

DataText Property

Format Property

GetObject Function

Object Property

ObjectAcceptFormats Property

ObjectAcceptFormatsCount Property

ObjectGetFormats Property

ObjectGetFormatsCount Property


DataText Property

See Also	Example

Applies To

OLE control.

Description

Sends or retrieves a string from the specified OLE object.  Not available at design time.

Usage

[form.]ole.DataText [ = data ]

Remarks

To send a string to an object, first set the Format property to a format the object supports.  Use the ObjectGetFormats and ObjectAcceptFormats properties to get a list of formats supported by an object.

When getting data from an object, the DataText property returns the string sent from the object, ending at the first null character.

The DataText string must be less than 64K.

OLE Automation provides an easier and more reliable solution for sending data and commands to and from an object.  If an object supports OLE Automation, you can access the object through the Object property, or using the CreateObject and GetObject functions.

Data Type

String


See Also

CreateObject Function

Data Property

Format Property

GetObject Function

Object Property

ObjectAcceptFormats Property

ObjectAcceptFormatsCount Property

ObjectGetFormats Property

ObjectGetFormatsCount Property


DataText Property Example

The example sends data to the Microsoft Graph application, so you must have Graph to run the example. Create a form about half the size of the screen with a command button (command1) in the upper left corner of the form and an OLE control (OLE1) placed below the command button.

When you place the OLE control on the form, the Insert Object dialog is displayed. Choose Cancel and press F5 to run the example.

Sub Command1_Click ()
Dim Msg, NL, TB	' Declare variables.
TB = Chr(9)	' Tab character.
NL = Chr(10)	' Newline character.
' Create data to replace default Graph data.
Msg = TB + "Drew" & TB & "Teresa" & TB & "Bob"
Msg = Msg + NL & "Eric" & TB & "1" & TB & "2" & TB & "3"
Msg = Msg + NL & "Ted" & TB & "11" & TB & "22" & TB & "33"
Msg = Msg + NL & "Arthur" & TB & "21" & TB & "32" & TB & "23"
' Send the data through the DataText property.
' Activate MSGRAPH as hidden.
Ole1.Verb = -3
Ole1.Action = 7
If Ole1.AppIsRunning Then
Ole1.DataText = Msg
' Update the object.
Ole1.Action = 6
Else
MsgBox "MSGRAPH is not active."
End If
End Sub

Sub Form_Load ()
Ole1.Format = "CF_TEXT"	' Set the format to text.
Ole1.SizeMode = 2	' Autosize.
Ole1.Class = "MSGRAPH"	' Embed an MSGRAPH object.
Ole1.Action = 0
End Sub


DisplayType Property

See Also

Applies To

OLE control.

Description

Determines whether an object displays its contents or an icon.

Usage

[form.]ole.DisplayType [ = setting ]

Setting

The DisplayType property settings are:

Setting 	Description

0 	(Default) Content.  When the OLE control contains an object, the object's data is displayed in the control.

1	Icon.  When the OLE control contains an object, the object's icon is displayed in the control.

Remarks

This property determines the default setting of the Icon check box in the Insert Object and Paste Special dialogs.  When you display these dialogs either at run time (set Action to 14 or 15) or design time, the Icon check box is automatically selected if this property is set to 1 (Icon).

When creating an object at run time using the Action property, you use the DisplayType property to determine if the object is to be displayed as an icon (set DisplayType = 1), or if the objects data is to be displayed in the control (set DisplayType = 0).

Once an object is created, you cannot change its display type.

Data Type

Integer


See Also

Help:

Action Property


FileNumber Property

See Also	Example

Applies To

OLE control.

Description

Determines the file number to be used when saving or loading an OLE object, or reflects the last file number used.  Not available at design time.

Usage

[form.]ole.FileNumber [ = filenumber ]

Remarks

The FileNumber must correspond to an open, binary file.

Use this property to specify the number of the file to be opened or saved when setting Action = 11 (Save) or Action = 12 (Read).

Data Type

Integer


See Also

Help:

Action Property

FreeFile Function

Open Statement

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


FileNumber Property Example

The example shows how to save and open the data associated with Ole1 in a file named MYOB.OLE.  To run the example you need Microsoft Excel 4.0 running or on your path.  Create a form with an OLE control named Ole1.  When the Insert Object dialog is displayed, press Cancel.  Place a command button named Command1 on the form.  Place a menu named File on the form with two menu items: mnuOpenObject and mnuSaveObject.

Press F5 and then press the command button to set the Class and Action properties.  Microsoft Excel starts if it is not already running.  Enter data in a spreadsheet, then choose Update from the Microsoft Excel File menu to show the data in the OLE control.  Choose Save from the example form's File menu.  This creates the file in which the OLE object is saved.  You can end the example application, start it again and choose Open Object from its File menu to display the object independently of Microsoft Excel.  Note that when you do so, the command button is disabled.

Sub Command1_Click ()
Ole1.Class = "ExcelWorksheet"	' Set class.
Ole1.Action = 0	' Create OLE object.
Show	' Show form with object,
Command1.Enabled = False	' then disable button.
End Sub

Sub mnuSaveObject_Click ()
Dim FileNum	' Declare variable.
FileNum = FreeFile	' Get a valid file number.
Open "MYOB.OLE" For Binary As FileNum	' Open file to be saved.
Ole1.FileNumber = FileNum	' Set the filenumber.
Ole1.Action = 11	' Save the file.
Close #FileNum	' Close the file.
End Sub

Sub mnuOpenObject_Click ()
Dim FileNum	' Declare variable.
FileNum = FreeFile	' Get a valid file number.
Open "MYOB.OLE" For Binary As FileNum	' Open the file.
Ole1.FileNumber = FileNum	' Set the filenumber.
Ole1.Action = 12	' Get data from file.
Close #FileNum	' Close the binary file.
' Since you've opened the file, disable button that initiates object.
Command1.Enabled = False
End Sub


Format Property

See Also

Applies To

OLE control.

Description

Determines the format when sending data to and getting data from an application that created an object.  Not available at design time.

Usage

[form.]ole.Format [ = format ]

Remarks

This property determines the format used with the Data and DataText properties.

Use the ObjectAcceptFormats, ObjectAcceptFormatsCount, ObjectGetFormats, and ObjectGetFormatsCount properties to get a list of the acceptable data formats for a specific class of OLE object.

Many applications that provide objects support only one or two formats.  For example, Microsoft Draw accepts only the CF_METAFILEPICT format.  Note that although CF_METAFILEPICT resembles the symbolic constant CF_METAFILE (numeric value 3) defined in CONSTANT.TXT, it is actually a string literal and would be assigned as:

Ole1.Format = "CF_METAFILEPICT"

In many cases the list of formats an object can accept (ObjectAcceptFormats) is different from the list of formats an object can provide (ObjectGetFormats).

Data Type

String


See Also

Data Property

DataText Property

Format, Format$ Function

ObjectAcceptFormats Property

ObjectAcceptFormatsCount Property

ObjectGetFormats Property

ObjectGetFormatsCount Property


HostName Property

See Also

Applies To

OLE control.

Description

Determines the user-readable host name of your Visual Basic application.

Usage

[form.]ole.HostName [ = name ]

Remarks

When editing an OLE object, the HostName may be displayed in the object's window title.  Some applications that provide objects do not display the HostName.

Data Type

String


See Also

Help:

OLE Control.

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


lpOleObject Property

See Also

Applies To

OLE control.

Description

Specifies the address of the OLE object.  Not available at design time; read-only at run time.

Usage

[form.]ole.lpOleObject

Remarks

Many function calls in the OLE2 DLLs require the address of an object as an argument.  Pass the value specified in the lpOleObject property when making API calls to the OLE2 DLLs.  The value is 0 if no object is currently displayed.  If a call is made to an API that makes a callback to the OLE control, the result is unpredictable.

The address returned by this property is a far pointer to the lpOleObject interface for the current object.

Data Type

Long


See Also

Help:

hWnd Property

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


Object Property

See Also

Applies To

OLE control.

Description

Represents the object in an OLE control.  Not available at design time; read-only at run time.

Usage

[form.]ole.Object[.property | .method ] [ = setting ]

Remarks

Use this property to specify an OLE object when performing OLE Automation tasks.

You perform OLE Automation tasks on the object using properties and methods the object supports.  For information on which properties and methods an object supports, see the documentation for the application that created the object.

Data Type

Long


See Also

Help:

CreateObject Function

GetObject Function

OLE Automation

Programmer's Guide:

Chapter 23, "Programming Other Applications' Objects"


PasteOK Property

See Also	Example

Applies To

OLE control.

Description

Specifies whether the contents of the Clipboard can be pasted into the OLE control.  Not available at design time; read-only at run time.

Usage

[form.]ole.PasteOK

Remarks

When this property returns True, the contents of the Clipboard can be pasted into the OLE control.

Use the OleTypeAllowed property to specify the type of object (linked or embedded) that can be pasted into the OLE control.  Once an object has been successfully pasted into the OLE control, you can query the OleType property to determine the type of object that was created.

This property can be useful if your application supports the Paste command in the Edit menu.  If PasteOK is False, then the Edit Paste command should be disabled; otherwise it can be enabled.  Enable and disable menu commands by setting their Enabled property to True and False, respectively.

You paste an object into the OLE control by setting Action = 5 (Paste).

To provide more flexibility to the user, display a Paste Special dialog when the user selects the Edit Paste command (set OleTypeAllowed = 2, and Action = 15).  When this dialog is displayed, an object is pasted to the Clipboard based on the user's selections in the dialog.

Data Type

Integer (Boolean)


See Also

Help:

Action Property

Enabled Property

OleType Property

OleTypeAllowed Property

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


PasteOK Property Example

The example code cannot run by itself, but it illustrates how to paste the contents of the Clipboard into the OLE control when the user chooses the appropriate menu item.  To see how this works in an application, load the sample program OLE2DEMO.MAK, and place a breakpoint in the mnuEditClick procedure.  Then press F5 and choose Paste from the Edit menu.

Sub mnuEditPaste_Click ()
' Check value of PasteOK.
If Ole1.PasteOK Then
Ole1.Action = 5	' Do the Paste if OK.
Else	' Otherwise disable Paste
mnuEditPaste.Enabled = False	' menu item and give
MsgBox "Cannot Paste"	' appropriate message.
End If
End Sub


ObjectAcceptFormats Property

See Also	Example

Applies To

OLE control.

Description

Specifies the list of formats an object can accept.  Not available at design time; read-only at run time.

Usage

[form.]ole.ObjectAcceptFormats (index)

Remarks

ObjectAcceptFormats is a zero-based array of strings describing the valid formats that can be used in the Format property when exchanging data with an object using the Data and DataText properties.  ObjectAcceptFormatsCount specifies the number of elements in the ObjectAcceptFormats array.

The list of acceptable formats is obtained from an object.  If the OLE control does not contain an object, an error will occur when you attempt to access this property.

Data Type

String


See Also

Help:

Data Property

DataText Property

Format Property

ObjectAcceptFormatsCount Property

ObjectGetFormats Property

ObjectGetFormatsCount Property

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


Example for ObjectAcceptFormats, ObjectAcceptFormatsCount, ObjectGetFormats, ObjectGetFormatsCount, ObjectVerbs, ObjectVerbsCount Properties

To run this example, place an OLE control and three list boxes on a form.  Paste the example code into the declarations section of the form and press F5 to run.  When the Insert Object dialog is displayed, select an application in the New Object list box and click OK to create an object.

Sub Form_Click ()
Dim I	' Declare variable.
' Display the Insert Object dialog.
Ole1.Action = 14
' Update the list of available verbs
Ole1.Action = 17	' Fetch verbs.
' Clear the list boxes.
List1.Clear
List2.Clear
List3.Clear
' Fill the Verbs list box. Since ObjectVerbs(0) is
' the default verb and is repeated in the ObjectVerbs()
' array, start the count at 1.
For I = 1 To Ole1.ObjectVerbsCount - 1
List1.AddItem Ole1.ObjectVerbs(I)
Next I

'Fill the Accept Formats list box.
For I = 0 To Ole1.ObjectAcceptFormatsCount - 1
List2.AddItem Ole1.ObjectAcceptFormats(I)
Next I

' Fill the Get Formats list box.
For I = 0 To Ole1.ObjectGetFormatsCount - 1
List3.AddItem Ole1.ObjectGetFormats(I)
Next I
End Sub


ObjectAcceptFormatsCount Property

See Also	Example

Applies To

OLE control.

Description

Specifies the number of formats that can be accepted by an object.  Not available at design time; read-only at run time.

Usage

[form.]ole.ObjectAcceptFormatsCount

Remarks

Use this property to get the number of elements in the ObjectAcceptFormats property array.

Data Type

Integer


See Also

Help:

Data Property

DataText Property

Format Property

ObjectAcceptFormats Property

ObjectGetFormats Property

ObjectGetFormatsCount Property

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


ObjectGetFormats Property

See Also	Example

Applies To

OLE control.

Description

Specifies the list of formats an object can return.  Not available at design time; read-only at run time.

Usage

[form.]ole.ObjectGetFormats (index)

Remarks

The list is a zero-based string array.  Elements of the array can be used to set the Format property when getting data from an object using the Data and DataText properties.

Data Type

String


See Also

Help:

Data Property

DataText Property

Format Property

ObjectAcceptFormats Property

ObjectGetFormatsCount Property

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


ObjectGetFormatsCount Property

See Also	Example

Applies To

OLE control.

Description

Specifies the number of formats an object can provide.  Not available at design time; read-only at run time.

Usage

[form.]ole.ObjectGetFormatsCount

Remarks

Use this property to determine the number of elements in the ObjectGetFormats property array.

Data Type

Integer


See Also

Help:

Data Property

DataText Property

Format Property

ObjectAcceptFormats Property

ObjectAcceptFormatsCount Property

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


OleType Property

See Also

Applies To

OLE control.

Description

Specifies the status of the object in an OLE control.

Usage

[form.]ole.OleType

Setting

The OleType property settings are:

Setting	Description

0 	Linked.  The OLE control contains a linked object.  All the object's data is managed by the application that created it.  When the object is saved (set Action = 11), only link information such as SourceDoc, SourceItem, and so on, is saved in the specified file by your Visual Basic application.

1	Embedded.  The OLE control contains an embedded object.  All the OLE object's data is managed with the Visual Basic application.  When the object is saved (set Action = 11), all data associated with the object is saved in the specified file.

3	None.  The OLE control does not contain an object.

Remarks

Use this property to determine if the OLE control contains an object, or to determine the type of object the OLE control contains.

Use the AppIsRunning property to determine if the application that created the object is running.

When creating an object, use the OleTypeAllowed property to determine the type of object that can be created.

Data Type

Integer


See Also

Help:

Action Property

AppIsRunning Property

FileNumber Property

OleTypeAllowed Property

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


OleTypeAllowed Property

See Also

Applies To

OLE control.

Description

Determines the type of object the OLE control can contain.

Usage

[form.]ole.OleTypeAllowed [ = setting ]

Setting

The OleTypeAllowed property settings are:

Setting	Description

0 	Linked.  The OLE control can contain only a linked object.

1	Embedded.  The OLE control can contain only an embedded object.

2	(Default) Either.  The OLE control can contain either a linked or an embedded object.

Remarks

When you allow the user to create an object by displaying the Insert Object dialog (set Action = 14), the Paste Special dialog (set Action = 15), or when pasting an object from the Clipboard (set Action = 5), use this property to determine the type of object the user is allowed to create.

Use the OleType property to determine an object's type (linked, embedded, or none).

Data Type

Integer


See Also

Help:

Action Property

AppIsRunning Property

OleType Property

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


ObjectVerbs Property

See Also	Example

Applies To

OLE control.

Description

Returns the list of verbs an object supports.  Not available at design time; read-only at run time.

Usage

[form.]ole.ObjectVerbs (index)

Remarks

ObjectVerbs is a zero-based string array.  Use this property along with the ObjectVerbsCount property to get the verbs supported by an object.  These verbs are used by the Verb property to determine an action to perform when an OLE object is activated (set Action = 7).

Note   The Verb property provides an index to the ObjectVerbs array.

The first verb in the ObjectVerbs array, ObjectVerbs(0), is the default verb.  If the Verb property has not been set, this is the action performed when the object is activated.

The remaining verbs in the array can be displayed in a menu.  If it is appropriate to display the default verb in a menu (in most cases this is true), then the default verb will have two entries in the ObjectVerbs array.

Applications that display OLE objects typically include an Object command on the Edit menu.  When the user selects Edit Object, a cascading menu displays the object's verbs.  Use the ObjectVerbs, ObjectVerbsCount, and ObjectVerbFlags properties to create such a menu at run time.

The list of verbs an object supports may vary, depending on the state of the object.  To update the list of verbs an object supports, set Action = 17 (Fetch Verbs).  Be sure to update the list of verbs before presenting it to the user.

To automatically display the verbs in the ObjectVerbs array in a pop-up menu when the user clicks an object with the right mouse button, set the AutoVerbMenu property to True.

Note   Each object supports three special verbs which may or may not be listed in the ObjectVerbs property.  These verbs are represented by the values [image] 1, [image] 2, and [image] 3.  They are used by the Verb property to show, open, or hide an object.

Data Type

String


See Also

Help:

Action Property

AutoVerbMenu Property

ObjectVerbFlags Property

ObjectVerbsCount Property

Verb Property

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


ObjectVerbsCount Property

See Also	Example

Applies To

OLE control.

Description

Specifies the number of verbs supported by an object.  Not available at design time; read-only at run time.

Usage

[form.]ole.ObjectVerbsCount

Remarks

Use this property to determine the number of elements in the ObjectVerbs property array.

The list of verbs an object supports may vary, depending on the state of the object.  To update the list of verbs an object supports, set Action = 17 (Fetch Verbs).

Data Type

Integer


See Also

Help:

Action Property

ObjectVerbFlags Property

ObjectVerbs Property

Verb Property

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


ObjectVerbFlags Property

See Also

Applies To

OLE control.

Description

Specifies the menu state for each verb in the ObjectVerbs array.  Not available at design time; read-only at run time.

Usage

[form.]ole.ObjectVerbFlags (index)

Remarks

The first verb in the ObjectVerbs array is the default verb.  The remaining verbs in this array are suitable for displaying on a menu.  The ObjectVerbFlags array contains information about the menu state (such as grayed, checked, and so on) for each verb in the ObjectVerbs array.

When displaying a menu containing an object's verbs, check the value of this property to see how the item should be displayed.

The following table describes the possible ObjectVerbFlags.

Constant	  Value	Description

VF_CHECKED	&H0008	The menu item should be checked.

VF_DISABLED	&H0002	The menu item should be disabled (but not grayed).

VF_ENABLED	&H0000	The menu item should be enabled.

VF_GRAYED	&H0001	The menu item should be grayed.

VF_SEPARATOR	&H0800	The menu item is a separator bar.

Note   These constant settings are defined in the Visual Basic file CONSTANT.TXT.

Data Type

String


See Also

Action Property

AutoVerbMenu Property

ObjectVerbs Property

ObjectVerbsCount Property

Verb Property


SizeMode Property

See Also

Applies To

OLE control.

Description

Determines how the OLE control is sized or how its image is displayed when it contains an object.

Usage

[form.]ole.SizeMode [ = setting ]

Setting

The SizeMode property settings are:

Setting 	Description

0 	(Default) Clip.  The object is displayed in actual size.  If the object is larger than the OLE control, its image is clipped by the control's borders.

1	Stretch.  The object's image is sized to fill the OLE control.

2	Autosize.  The OLE control is resized to display the entire object.

Remarks

When SizeMode is set to 2 (Autosize), the OLE control is automatically resized when the display size of an object changes.  When this occurs, the Resize event is invoked before the OLE control is automatically resized.  The HeightNew and WidthNew parameters indicate the optimal size for displaying the object (this size is determined by the application that created the object).  You can size the control differently by changing the values of the HeightNew and WidthNew parameters in the Resize event.

Data Type

Integer


vbproSizeModeSee
See Also

Help:

Action Property

Resize Event

Updated Event

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


SourceDoc Property

See Also	Example

Applies To

OLE control.

Description

Determines the file name to use when you create an OLE object.

Usage

[form.]ole.SourceDoc [ = filename ]

Remarks

Use the SourceDoc property to specify the file to be linked when creating a linked object (set Action = 1).  Use the SourceItem property to specify data within the file to be linked.

When creating an embedded object (set Action = 0), if the SourceDoc property is set to a valid file name, an embedded object is created using the specified file as a template.

When a linked object is created, the SourceItem property is concatenated to the SourceDoc property.  At run time, the SourceItem property returns an empty string ("") and the SourceDoc property returns the entire path to the linked file, followed by an exclamation point (!) or a backslash (\), followed by the SourceItem.  For example:

"C:\WORK\QTR1\REVENUE.XLS!R1C1:R30C15"

Data Type

String


See Also

Help:

Action Property

Class Property

OleType Property

OleTypeAllowed Property

SourceItem Property

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


SourceDoc, SourceItem Properties Example

The example creates a linked OLE object when the user clicks the command button.  First, use Microsoft Excel to create a spreadsheet named OLETEST.XLS.  Then create a form with an OLE control named Ole1.  When the Insert Object dialog is displayed, choose Cancel.  Place a command button on the form and copy the following code into the form's Declarations section, and then press F5.  The file OLETEST.XLS must exist in the specified path.

Sub Command1_Click
' Set class.
Ole1.Class = "ExcelWorksheet"
' Specify source file.
Ole1.SourceDoc = "C:\EXCEL\OLETEST.XLS"
' Specify the data within the file to be linked.
Ole1.SourceItem = "R1C1:R5C5"
' Create a linked object using OleTest.xls.
Ole1.Action = 1
End Sub


SourceItem Property

See Also	Example

Applies To

OLE control.

Description

Determines the data within the file to be linked when you create a linked object.

Usage

[form.]ole.SourceItem [ = stringexpression ]

Remarks

OleTypeAllowed must be set to 0 (Linked) or 2 (Either) when using this property.  Use the SourceDoc property to specify the file to link.

Each object uses its own syntax to describe units of data.  To set this property, specify a unit of data recognized by the object.  For example, when you link to Microsoft Excel, you specify the SourceItem using a cell or cell-range reference such as "R1C1" or "R3C4:R9C22," or a named range such as "Revenues."

To determine the syntax to describe a unit of data for an object, see the documentation for the application that created the object.

Tip   You may be able to determine this syntax by creating a linked object at design time using the Paste Special command (click the OLE control with the right mouse button).  Once the object is created, select the SourceDoc property in the Properties window and look at the string in the Settings box.  For most objects, this string will contain a path to the linked file, followed by an exclamation point (!), or a backslash (\) and the syntax for the linked data.

When a linked object is created, the SourceItem property is concatenated to the SourceDoc property.  At run time, the SourceItem property returns an empty string ("") and the SourceDoc property returns the entire path to the linked file, followed by an exclamation point (!) or a backslash (\), followed by the SourceItem.  For example:

"C:\WORK\QTR1\REVENUE.XLS!R1C1:R30C15"

Data Type

String


See Also

Help:

Action Property

Class Property

OleType Property

OleTypeAllowed Property

SourceDoc Property

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


UpdateOptions Property

See Also

Applies To

OLE control.

Description

Determines how an object is updated when linked data is modified.  Not available at design time.

Usage

[form.]ole.UpdateOptions [ = option ]

Setting

The UpdateOptions property settings are:

Setting	Description

0 	(Default) Automatic.  The object is updated each time the linked data changes.

1	Frozen.  The object is updated whenever the user saves the linked document from within the application in which it was created.

2	Manual.  The object is updated only when the Action property is set to 6 (Update).

Remarks

This property is useful for linked objects where other users or applications can access and modify the linked data.

When an object's data is changed, the Updated event is invoked.

Data Type

Integer (Enumerated)


See Also

Help:

Action Property

Class Property

OleType Property

OleTypeAllowed Property

Updated Event

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


Verb Property

See Also

Applies To

OLE control.

Description

Specifies an operation to perform when an OLE object is activated (Action = 7).

Usage

[form.]ole.Verb [ = verbnumber ]

Remarks

Each object can support its own set of verbs.  For example, many objects support the verbs "edit" and "play."  Use the ObjectVerbs and ObjectVerbsCount properties to access the list of verbs supported by an object.  Set Verb = 1 to specify the first verb in the list, set Verb = 2 to specify the second verb in the list, and so on.

These standard verbs are supported by every object:

Value	Action

0 	The default action for the object.

1	Activates the object for editing.  If the application that created the object supports in-place editing, the object is activated within the OLE control.

2	Opens the object in a separate application window.  If the application that created the object supports in-place editing, the object is activated in its own window.

3	For embedded objects, this verb hides the application that created the object.

Note   These verbs may not be listed in the ObjectVerbs property array.

Set AutoActivate = 2 (Double-Click) to automatically activate an object when it is double-clicked by the user.

Set AutoVerbMenu = True to display a pop-up menu containing the object's verbs when the user clicks the object with the right mouse button.

Data Type

Integer


See Also

Help:

Action Property

AutoActivate Property

AutoVerbMenu Property

ObjectVerbs Property

ObjectVerbsCount Property

OleType Property

OleTypeAllowed Property

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"


Updated Event

See Also

Applies To

OLE control.

Description

Occurs when an object's data has been modified.

Syntax

Sub OLE_Updated (Code As Integer)

Remarks

Code indicates how the OLE object was updated.  Its possible values are:

Value	Constant	Description

0	OLE_CHANGED	The object's data has changed.

1	OLE_SAVED	The object's data has been saved by the application that created the object.

2	OLE_CLOSED	The file containing the linked object's data has been closed by the application that created the object.

3	OLE_RENAMED	The file containing the linked object's data has been renamed by the application that created the object.

This event is useful for determining if an object's data has been changed since it was last saved.  To do this, set a global variable in the Updated event indicating the object needs to be saved.  When you save the OLE object, reset the variable.  The constants are defined in the Visual Basic file CONSTANT.TXT.


See Also

Action Property

Class Property

OleType Property

OleTypeAllowed Property

UpdateOptions Property


CreateObject Function

See Also

Creates an OLE Automation object.

Syntax

CreateObject (class)

Remarks

The class argument is a string indicating the name of the application used to create the object and the type of object.  To specify an object's class, use the following syntax:

"appname.objecttype"

The class argument has these parts:

Part	Description

appname	The name of the application providing the object.

objecttype	The type, or class, of object to create.

Each application that supports OLE Automation provides at least one type of object.  For example, a word-processing application may provide an application object, a document object, and a toolbar object.

Note   To get a list of OLE Automation objects an application supports, consult that application's documentation.

Use this function to create an OLE Automation object and assign the object to an object variable.  To do this, first dimension a variable of type object.  Then use the Set statement to assign the object returned by CreateObject to the object variable.  For example:

Dim MyObject As Object
Set MyObject = CreateObject("WordProc.Document")

When this code is executed, the application creating the object is started if it is not already running (WordProc.Exe in this example), and an object of the specified type is created.  Unlike creating a linked or embedded object using the OLE control, the object's image is not displayed anywhere in Visual Basic, nor is the object's data maintained by Visual Basic.

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

MyObject.Bold
MyObject.Insert "Hello, world."
MyObject.Print
MyObject.SaveAs "C:\WORDPROC\DOCS\TEST.DOC"


See Also

Help:

GetObject Function

Object Property

OLE Automation

OLE Control

Set Statement

Programmer's Guide:

Chapter 23, "Programming Other Applications' Objects"


GetObject Function

See Also

Retrieves an OLE Automation object from a file.

Syntax

GetObject (filename [, class ])

Remarks

The GetObject function has these parts:

Part	Description

filename	The full path and name of the file containing the object to retrieve.  If filename is an empty string (""), then class is required.

class	A string representing the class of the object to retrieve.

The class argument is optional.  It uses the following syntax:

 "appname.objecttype"

The class argument has these parts:

Part	Description

appname	The name of the application providing the object.

objecttype	The type or class of object to create.

Use the GetObject function to access an OLE Automation object from a file and assign the object to an object variable.  To do this, first dimension a variable of type object.  Then use the Set statement to assign the object returned by GetObject to the object variable.  For example:

Dim MyObject As Object
Set MyObject = GetObject("C:\WORDPROC\DOCS\OLETEST.DOC")

When this code is executed, the application associated with the specified file name is started (WORDPROC.EXE in this example) and the object in the specified file is activated.

If the filename argument is set to an empty string (""), this function returns the currently active object of the specified type.  If there is no object of that type active, an error occurs.

The above example shows how to activate an entire file.  However, some applications allow you to activate part of a file.  To do this, add an exclamation point (!) to the end of the file name followed by 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 many spreadsheet applications you specify the rows and columns of a range of cells using an R1C1 syntax.  You could use the following code to activate a range of cells within a spreadsheet called REVENUE.SPD:

Set Sheet = GetObject("C:\ACCOUNTS\REVENUE.SPD!R1C1:R10C20")

If you do not specify the object's class, the OLE2 DLLs determine the application to invoke 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 spreadsheet might support three different types of objects: an application object, a worksheet 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:

Set Sheet = GetObject("C:\ACCOUNTS\REVENUE.SPD", "SPDSHEET.WORKSHEET")

In the above example, SPDSHEET is the name of a spreadsheet application and WORKSHEET one of the object types it supports.

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

Sheet.Row 	= 4
Sheet.Column	= 2
Sheet.Insert 	= "Hello, world."
Sheet.SaveAs "C:\WORDPROC\DOCS\TEST.DOC"
Sheet.Print


See Also

Help:

CreateObject Function

Object Property

OLE Automation

OLE Control

Set Statement

Programmer's Guide:

Chapter 23, "Programming Other Applications' Objects"


OLE Automation

See Also

What is OLE Automation?

OLE Automation is an industry standard that applications use to expose their OLE objects to development tools, macro languages, and other containers that support OLE Automation.  For example, a spreadsheet application may expose a worksheet, chart, cell, or range of cells [image] all as different types of objects.  A word processor might expose objects such as application, paragraph, sentence, bookmark, or selection.

When an application supports OLE Automation, the objects it exposes can be accessed by Visual Basic.  You use Visual Basic to manipulate these objects by invoking methods on the object, or by getting and setting the objects properties, just as you would with the objects in Visual Basic.  For example, if you created an OLE Automation object named MyObj, you might write code such as this to manipulate the object:

' Enter text in the object.
MyObj.Insert "Hello, world."
' Format the text as bold.
MyObj.Bold
' Save the object to a file.
MyObj.SaveAs  "C:\WORDPROC\DOCUMENTS\TESTOBJ.DOC"

The properties and methods an object supports are defined by the application that created the object.  See that application's documentation for details on the properties and methods it supports.

Accessing an object

The following functions and properties allow you to access an OLE Automation object:

Name	Description

CreateObject Function	Creates a new object of a specified type.

GetObject Function	Retrieves an object from a file.

Object Property	Specifies the object in an OLE control.

Distribution Note

When you create and distribute applications that use OLE Automation, you should install the files COMPOBJ.DLL, OLE2.REG, OLE2.DLL, OLE2CONV.DLL, OLE2DISP.DLL, OLE2NLS.DLL, OLE2PROX.DLL, STORAGE.DLL, and VBOA300.DLL in the customers Microsoft Windows \SYSTEM directory.

You also need to make sure OLE 2.0 is registered on the users machine and that SHARE.EXE is installed in the users AUTOEXEC.BAT file (SHARE.EXE is not required if the user is running Microsoft Windows for Workgroups).  Use the SetupWizard to create distribution disks that do this.

For more information on the SetupWizard and on distributing applications, see Chapter 25, Distributing Your Applications, in the Programmer's Guide or search Help for Setup Kit.  For more information on distributing OLE applications, see Chapter 22, Object Linking and Embedding (OLE), in the Programmer's Guide.


See Also

Help:

CreateObject Function

GetObject Function

Object Property

OLE Control

Set Statement

Programmer's Guide:

Chapter 22, "Object Linking and Embedding (OLE)"

Chapter 23, "Programming Other Applications' Objects"

Chapter 25, "Distributing Your Applications"


MiscFlags Property

See Also

Applies To

OLE control.

Description

Provides access to one or more additional features of the OLE control.

Syntax

[form.]ole.MiscFlags = setting

Settings

The MiscFlags settings are:

Constant	Value	Description

OLE_MISCFLAG_MEMSTORAGE	1	Causes the control to use memory to store the object while it is loaded.

OLE_MISCFLAG_DISABLEINPLACE	2	Overrides the control's default behaviour of allowing in-place activation for objects that support it.

Remarks

The MEMSTORAGE flag setting is faster than the default, which is to store it on disk as a temporary file.  This setting can, however, consume a great deal of memory for objects whose data requires a lot of space, such as a bitmap for a paint program.

If an object supports in-place editing, you can use the DISABLEINPLACE setting to force the object to activate in a separate window.

To combine values, use the Or operator.  For example, to combine both flags, you could use this code:

Ole1.MiscFlags = OLE_MISCFLAG_MEMSTORAGE Or OLE_MISCFLAG_DISABLEINPLACE


vbproMiscFlagsSee
See Also

Or Operator

And Operator


Attributes Property

See Also

Applies To

Field object, TableDef object.

Description

Indicates one or more characteristics of a Field or TableDef.  Not available at design time; read-only when the object is a member of a collection.  Read/write only in the Professional Edition with a new object not yet appended to a collection.

Syntax

{ field | tabledef }.Attributes [ = numericexpression ]

Setting

For a Field object, the Attributes property setting can be any combination of the following:

Constant	Value	Description

DB_FIXEDFIELD	1	(Default for numeric) Value in the Field is fixed-length.

DB_AUTOINCRFIELD	16	Value for new records is automatically incremented by the database.  Valid only on fields of Long data type.

DB_UPDATABLEFIELD	32	Value in the Field can be changed.

For a TableDef object, the Attributes property setting can be any combination of the following:

Constant	Value (Hex)	Description

DB_ATTACHEXCLUSIVE	&H00010000	For Microsoft Access databases, indicates the table is an attached table opened for exclusive use.

DB_ATTACHSAVEPWD	&H00020000	For Microsoft Access databases, indicates the user ID and password for the source table should be saved with the linking information.

DB_SYSTEMOBJECT	&H80000002	Indicates the table is a system table.

DB_ATTACHEDTABLE	&H40000000	Indicates the table is an attached table from a non-ODBC database, such as Microsoft Access or Paradox.

DB_ATTACHEDODBC	&H20000000	Indicates the table is an attached table from an ODBC database, such as SQL Server or Oracle.

Remarks

The field part can be a member of a Fields collection of the Recordset property of a data control, and the tabledef part can be a member of the TableDefs collection of the Database property of a data control.  In the Professional Edition, they can also be object variables identifying Field or TableDef objects, respectively.

When reading this property, use the And operator to test for a specific Attribute.  For example, to determine whether a Field is fixed-length, you could use this code:

If Data1.Recordset.Fields("PubID").Attributes And DB_FIELDFIXED Then...

In the Professional Edition, you can set this property only on a New TableDef object, and you can use only DB_ATTACHEXCLUSIVE and DB_ATTACHSAVEPWD.  To set both values, you can combine them by adding the values together.  Any other values are ignored without error.

Data Type

Long


vbproAttributesSee
See Also

Help:

And Operator

Data Access

Indexes Collection

New

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


CollatingOrder Property

See Also

Applies To

Database object, Field object.

Description

Determines the method for comparing text values.  Not available at design time; read-only at run time.

Syntax

{ database | field }.CollatingOrder

Setting

The CollatingOrder property settings are:

Constant	Value	Description

DB_SORTGENERAL	256	Sort by EFGPI rules (English, French, German, Portuguese, and Italian).

DB_SORTSPANISH	258	Sort by Spanish rules.

DB_SORTDUTCH	259	Sort by Dutch rules.

DB_SORTSWEDFIN	260	Sort by Swedish, Finnish rules.

DB_SORTNORDAN	261	Sort by Norwegian, Danish rules.

DB_SORTICELANDIC	262	Sort by Icelandic rules.

DB_SORTPDXINTL	4096	Sort by Paradox international rules.

DB_SORTPDXSWE	4097	Sort by Paradox Swedish, Finnish rules.

DB_SORTPDXNOR	4098	Sort by Paradox Norwegian, Danish rules.

DB_SORTUNDEFINED	1	Field sort rules are undefined or unknown.

Remarks

The database part can be the Database property of a data control, and the field part can be a member of the Fields collection of a TableDef in the TableDefs collection of the Database property of a data control.  In the Professional Edition, they can also be object variables identifying an open Database or a Field, respectively.

This corresponds to the locale part of the CompactDataBase statement and CreateDataBase function.  You can use the value of this property in the compare part of the StrComp and InStr functions.

Data Type

Integer


vbproCollatingOrderSee
See Also

And Operator

Data Access

Indexes Collection

New

InStr Function

StrComp Function


Exclusive Property

See Also	Example

Applies To

Data control.

Description

Determines whether the underlying database for a data control is opened for single-user or multiuser access.  Read/write at both design time and run time.

Syntax

[form.]datacontrol.Exclusive [ = {True | False}]

Setting

The Exclusive property settings are:

Setting	Description

True	The database is open for single-user access.  No one else can open the database until it is closed.

False	(Default) The database is open for multiuser access.  Others can open the database and have access to the data while it is open.

Remarks

The value of this property, along with the DatabaseName, ReadOnly, and Connect properties, is used to open a database.  In the Professional Edition, this property corresponds to the exclusive argument in the OpenDatabase function.

The Exclusive property is used only when opening the Database.  If you change the value of this property at run time, you must use the Refresh method for the change to take effect.  If someone else already has it open, you cannot open it for exclusive use.

Database operations are faster if the Database is opened for exclusive use.

Once you have opened a Database for exclusive use, your application can have as many instances open as necessary.

Data Type

String


proExclusiveSee
See Also

Help:

Attributes Property

Close Method

Connect Property

Data Access

DatabaseName Property

OpenDatabase Function (Professional Edition Only)

ReadOnly Property

Refresh Method

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


proExclusiveEx
Exclusive Property Example

The example first opens a Database as single-user (exclusive), then changes it to multiuser access (non-exclusive).

Data1.DatabaseName = "BIBLIO.MDB"
Data1.RecordSource = "Publishers"
Data1.Exclusive = True
Data1.Refresh
...
Data1.Exclusive = False
Data1.Refresh


Options Property

See Also

Applies To

Data control.

Description

Determines one or more characteristics of the Dynaset in the control's Recordset property.  Read/write at design time and run time.

Syntax

[form.] datacontrol.Options [ = numericexpression ]

Setting

The Options property settings are:

Constant	Value	Description

DB_DENYWRITE	1	In a multiuser environment, others cannot make changes to records in the Dynaset.

DB_READONLY	4	You cannot make changes to records in the Dynaset.

DB_APPENDONLY	8	You can add new records to the Dynaset, but you cannot read existing records.

DB_INCONSISTENT	16	Updates can apply to all fields of the Dynaset, even if they also affect other records in the Dynaset.

DB_CONSISTENT	32	(Default) Updates apply only to those fields that will not affect other records in the Dynaset.

DB_SQLPASSTHROUGH	64	When using data controls with an SQL statement in the RecordSource property, sends the SQL statement through to an ODBC database, such as a SQL Server or Oracle database for processing.

These values are from the Visual Basic file DATACONS.TXT.

Remarks

If you change this property at run time, you must use the Refresh method for the change to have any effect.

In the Professional Edition, this property corresponds to the options argument in the CreateDynaset method.

To set more than one value for this property, you can combine them by adding values together.  For example, to set both DB_READONLY and DB_INCONSISTENT you could use this code:

Data1.Options = DB_READONLY + DB_INCONSISTENT

To determine if the property contains a specific value, you can use the And operator.  For example, to determine if the recordset is opened for read-only access, you could use this code:

If Data1.Options And DB_READONLY Then...

If both DB_INCONSISTENT and DB_CONSISTENT values are used, the result is consistent updates, which is the default for Dynaset objects.

Data Type

Long


vbproOptionsSee
See Also

Help:

CreateDynaset Method (Professional Edition Only)

Data Access

Recordset Property

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


OrdinalPosition Property

See Also

Applies To

Field object.

Description

Indicates the numeric order of a Field object in the Fields collection of a TableDef.  Not available at design time; read-only at run time.

Syntax

tabledef.Fields( fieldname ).OrdinalPosition

Remarks

Each Field in the Fields collection of a TableDef has a unique value in the OrdinalPosition property.  The first Field appended to the collection is in the first position (0).  The second Field is in OrdinalPosition 1, and so on.

To specify a Field in a collection, you can use either the value of the Name property for the Field, or the value of the OrdinalPosition property.  For example, in the BIBLIO.MDB database, the table named "Publishers" has a field named "PubID" in the ordinal position of 0.  To print the current value of the Field, you can use either the Name of the Field or the OrdinalPosition of the Field in the collection.  For example, these statements print identical results:

Print Data1.Recordset.Fields("PubID")
Print Data1.Recordset.Fields(0)

Data Type

Integer


vbproOrdinalPositionSee
See Also

Help:

Data Access

Fields Collection

Index Property (Control Arrays)

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


ReadOnly Property

See Also

Applies To

Data control, file list box.

Description

Data control [image] determines whether the control's Database is opened for read-only access.

File list box [image] determines whether a file list box contains files with ReadOnly attributes.

Read/write at both design time and run time.

Syntax

[form.] control.ReadOnly [ = {True | False}]

Setting

The ReadOnly property settings are:

Setting	Description

True	Data control [image] the control's Database is opened with read-only access to data.  Changes to data are not allowed.
File list box [image] the control includes read-only files in the list.

False	(Default) Data control [image] the control's Database is opened with read/write access to data.
File list box [image] no read-only files are listed in the control.

Remarks

Use this property with a data control to specify whether data in the underlying Database can be changed.  For example, you might create an application that only displays data.  A read-only Database is also faster.

For a data control, this property is used only the first time a database is opened by your application.  If your application subsequently opens other instances of the database, the property is ignored.  For a change in this property to take effect, you must close all instances of the database and then use the Refresh method.

In the Professional Edition, this property corresponds to the readonly argument in the OpenDatabase function.

Use this property with a file list box to specify which kinds of files to display, based on standard file attributes used in the operating environment.  Setting this property at run time resets the list to display only those files with the corresponding attributes.  For example, in an application with restricted levels of access, you might want to display only read-only files by setting ReadOnly to True.

Data Type

Integer (Boolean)


vbproReadOnlySee
See Also

Help:

Data Access

Database Property

OpenDatabase Function (Professional Edition Only)

Path Property

Pattern Property

Refresh Method

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


Database Object

See Also	Properties	Methods

Description

A database is a collection of data related to a specific topic or purpose.  A database can contain tables, queries, and indexes.  A Database object is a logical representation of a physical database.

Remarks

The Database property of a data control is the only way to get access to a Database object without using the Professional Edition.  The Database property is a Database object representing the source of data appearing in other controls bound to the data control and corresponds to the database specified by the DatabaseName and Connect properties of a data control.

Database objects have properties and methods you can use to manage your data.  You can use any methods of a Database object with the Database property of a data control, such as Close and Execute.  You can also examine the internal structure of the physical database by using the TableDefs collection of a Database object, and in turn, the Fields and Indexes collections of individual TableDef objects.

Professional Edition

With the Professional Edition, you can create object variables of type Database using the Dim and Set statements.  For example, the following code creates and opens a Database object:

Dim MyDb As Database
Set MyDb = OpenDatabase("C:\VB\BIBLIO.MDB")


vbobjDatabaseSee
See Also

Help:

Connect Property

CreateDatabase Function

Data Access

Database Property

DatabaseName Property

Dim Statement

OpenDatabase Function

Set Statement

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"

Chapter 3, "Creating Programs to Manipulate Data"

Programmer's Guide

Chapter 20, "Accessing Databases with the Data Control"


vbobjDatabaseProp
Properties

CollatingOrder

Connect

Exclusive

Name

QueryTimeout

TableDefs Collection

Transactions

Updatable


vbobjDatabaseMth
Methods

BeginTrans	CreateSnapshot	ListTables

Close	DeleteQueryDef	OpenQueryDef

CommitTrans	Execute	OpenTable

CreateDynaset	ExecuteSQL	Rollback

CreateQueryDef	ListFields


Error Event

See Also	Example

Applies To

Data control.

Description

Occurs only as the result of a data access error that occurs when no Visual Basic code is being executed.

Syntax

Sub datacontrol_Error ([Index As Integer,] DataErr As Integer, Response As Integer)

Remarks

The Error event uses these parts:

Part	Description

Index	Uniquely identifies a control if it is in a control array.

DataErr	The error number.

Response	A number corresponding to the response you want to take.

Constants and values for the Response part are:

Constant	Value	Description

DATA_ERRCONTINUE	0	Continue

DATA_ERRDISPLAY	1	(Default) Display the message

These values are from the Visual Basic file CONSTANT.TXT.

You ordinarily provide error-handling functionality for run-time errors in your code.  However, run-time errors can occur when none of your code is running, such as when:

A user clicks a data control button.

The data control automatically opens a database and loads a recordset after the Form_Load event.

A custom control performs an operation such as the MoveNext method, the AddNew method, or the Delete method.

If an error results from one of these actions, the Error event occurs.


vbevtErrorSee
See Also

Help:

AddNew Method

Data Access

Delete Method

MoveFirst, MovePrevious, MoveNext, MoveLast Methods

Trappable Data Access Errors

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


vbevtErrorEx
Error Event Example

The example displays an Open dialog if the database specified in the data control's DatabaseName property is not found.

Sub Data1_Error (DataError As Integer, Response As Integer)
Select Case DataError
Case 3024	' If database file not found.
CMDialog1.Action = 1	' Display an Open dialog.
...
End Select
End Sub


Reposition Event

See Also	Example

Applies To

Data control.

Description

Occurs after a record becomes the current record.

Syntax

Sub datacontrol.Reposition ([Index As Integer])

Remarks

The Index part uniquely identifies a control if it is in a control array.

When a data control loads, it makes the first record in the recordset the current record, causing the Reposition event.  Whenever a user clicks any button on the data control, moving from record to record, or if you use any of the Move methods, such as MoveNext, or the Find methods, such as FindFirst, the Reposition event occurs after each record becomes current.

In contrast, the Validate event occurs before moving to a different record.

You can use this event to perform calculations based on data in the current record, or to change the form in response to data in the current record.


vbevtRepositionSee
See Also

Help:

Data Access

DataChanged Property

Error Event

FindFirst, FindLast, FindNext, FindPrevious Methods

MoveFirst, MoveLast, MoveNext, MovePrevious Methods

Validate Event


vbevtRepositionEx
Reposition Event Example

The example changes the selection of a list box based on data in the current record.

' In the Declarations section.
Dim Loading As Integer

Sub Form_Load ()
Data1.DatabaseName = "C:\VB\BIBLIO.MDB"
Data1.RecordSource = "SELECT DISTINCT State FROM Publishers"
Loading = True	' Set the global variable.
Data1.Refresh	' Open database & recordset.
Do While Not Data1.Recordset.EOF
If Not IsNull(Data1.Recordset(0)) Then  ' If not empty, then
List1.AddItem Data1.Recordset(0)	' Add to the list
End If
Data1.Recordset.MoveNext	' Move to next record.
Loop
Data1.RecordSource = "Publishers"	' Change the RecordSource.
Data1.Refresh	' Rebuild the recordset.
Text1.DataField = "State"	' Set field for text box.
Loading = False	' Turn off global variable.
End Sub

Sub Data1_Reposition ()
Dim I As Integer
If Loading Then Exit Sub	' If global variable is set.
For I = 0 To List1.ListCount - 1	' Check items in list box.
If List1.List(I) = Data1.Recordset("State") Then
List1.ListIndex = I	' Select matching item.
Exit For	' Stop looking through list.
End If
Next I
End Sub


SetDataAccessOption Statement

See Also

Description

Sets a global option for data access functionality.

Syntax

SetDataAccessOption option, value

Setting

The SetDataAccessOption statement has the following parts:

Part	Description

option	A numeric expression corresponding to a valid option.

value	A Variant containing a value that is valid for the kind of option.

The option part can be the following:

Constant	Value	Description

DB_OPTIONINIPATH	1	Sets the name and path of your application's initialization file (.INI).  Takes effect only when SetDataAccessOption is used before the data access functionality is loaded and initialized.  Once data access has been initialized, this setting cannot be changed without first exiting the application.  The value is a string expression.

Remarks

For the DB_OPTIONINIPATH option, the value argument contains a string expression providing the path and name of your application's initialization (.INI) file.  Initialization files are usually stored in a user's WINDOWS directory, and have the same name as the executable file but with the .INI extension.  Use this statement only if your application's initialization file has a different name or is in a directory other than the WINDOWS directory.  Your application must use an initialization file in order to use databases in any format other than Microsoft Access, such as FoxPro, Paradox, Btrieve, dBASE, or an ODBC database such as SQL Server or Oracle.


vbstmSetDataAccessOptionSee
See Also

Help:

BeginTrans, CommitTrans, Rollback Statements

CreateDefaultWorkspace Statement

Data Access


EditMode Property

See Also

Applies To

Data control.

Description

Indicates the current state of editing for the current record.  Not available at design time; read-only at run time.

Syntax

[form.] datacontrol.EditMode

Setting

The EditMode property settings are:

Constant	Value	Description

DATA_EDITNONE	0	There is no editing operation in progress.

DATA_EDITMODE	1	Edit method has been invoked and the current record is in the copy buffer.

DATA_EDITADD	2	AddNew method has been invoked and the current record in the copy buffer is a new record that hasn't been saved in the database.

These values are from the Visual Basic file CONSTANT.TXT.

Remarks

This property is most useful when you want to depart from the default functionality of a data control, or if you are not using a data control with the Professional Edition.  In the Validate event, you might check the value of this property and the value of the Action parameter to the procedure to determine whether you should invoke the UpdateRecord method.

You might also check to see if LockEdits is True and EditMode is DATA_EDITMODE to determine whether the current data page is locked.

Data Type

Integer


vbproEditModeSee
See Also

Help:

AddNew Method

Data Access

DataChanged Property

Edit Method

Update Method

UpdateControls Method

UpdateRecord Method

Validate Event


QueryTimeout Property (Professional Edition Only)

See Also

Applies To

Database object.

Description

Determines the number of seconds Visual Basic waits before a timeout error occurs when executing a query on an ODBC database.  The default is 60 seconds.  Not available at design time; read/write at run time.

Syntax

database.QueryTimeout [ = seconds ]

Remarks

The database is an object variable identifying an open Database object.

When using an ODBC database, such as SQL Server or Oracle, there may be delays due to network traffic or heavy use of the ODBC server.  Rather than waiting indefinitely, you can specify how long to wait before the database produces an error.

When set to zero, no timeout occurs.

Note	Does not apply to the CreateDynaset method.

Data Type

Integer


vbproQueryTimeoutSee
See Also

Help:

Data Access

Error Event

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


Database Property

See Also	Example

Applies To

Data control.

Description

A reference to a data control's underlying Database object.  Not available at design time; read-only at run time.

Syntax

[form.] datacontrol.Database.method [argumentlist ]

[form.] datacontrol.Database.property [ = setting ]

Remarks

To provide access to data, a data control finds the specified database and then using the Exclusive, ReadOnly, and Connect properties, opens it as a Database object.  The Database property is a direct reference to that object.

Database objects have properties and methods you can use to manage your data.  You can use any methods of a Database object with the Database property of a data control, such as Close and Execute.  You can also examine the internal structure of the Database by using its TableDefs collection, and in turn, the Fields and Indexes collections of individual TableDef objects.

Data Type

Database object


vbproDatabaseSee
See Also

Help:

Connect Property

Data Access

Database Object

DatabaseName Property

Exclusive Property

Fields Collection

Indexes Collection

Name Property

ReadOnly Property

Recordset Property

TableDefs Collection

Data Access Guide:

Chapter 4, "Using Visual Basic Controls with Data Access Objects"

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


vbproDatabaseEx
Database, DatabaseName Properties Example

The example examines the Database property of a data control and prints the name of each Table in the Debug window.

Sub PrintTableNames ()
Dim I
Data1.DatabaseName = "BIBLIO.MDB"	' Set Database file.
Data1.Refresh	' Open the Database.
' Read and print the name of each table in the Database.
For I = 0 To Data1.Database.TableDefs.Count - 1
Debug.Print Data1.Database.TableDefs(I).Name
Next I
End Sub


DatabaseName Property

See Also	Example

Applies To

Data control.

Description

Determines the name and location of the source of data for a data control.  Read/write at both design time and run time.

Syntax

[form.]datacontrol.DatabaseName [ = pathname ]

Remarks

For Microsoft Access and Btrieve databases, the DatabaseName setting is the path and name of the database file (.MDB or .DDF).  For dBASE III, dBASE IV, Paradox, and FoxPro databases, the DatabaseName property setting is the path to the directory of the database file (.DBF, .PDX).  If your network system supports it, the DatabaseName setting can be a fully qualified network path name such as \\MYSERVER\MYSHARE\DATABASE.MDB.

For ODBC databases, such as SQL Server and Oracle, this property can be left blank if the control's Connect property identifies a data source name (DSN) registered in the ODBC.INI file.

If you change this property after the control's Database is open, you must use the Refresh method to open the new database.

Data Type

String


vbproDatabaseNameSee
See Also

Help:

Connect Property

OpenDatabase Function (Professional Edition Only)

Refresh Method

RegisterDatabase Statement

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


DataChanged Property

See Also	Example

Applies To

Check box, image, label, picture box, text box, and other bound controls that may become available.

Description

Indicates that the data in the control has been changed by some process other than getting data from the current record.  Not available at design time; read/write at run time.

Syntax

[form.] control.DataChanged [ = {True | False}]

Setting

The DataChanged property settings are:

Setting	Description

True	The data currently in the control is not the same as in the current record.

False	(Default) The data currently in the control, if any, is the same as the data in the current record.

Remarks

When a data control moves from record to record, each bound control automatically displays data from a specific field in the current record and DataChanged is set to False.  If the data in the control changes in any way other than moving to a different record, DataChanged becomes True.

When the data control starts to move to a different record, the Validate event occurs.  Then if DataChanged is True for any bound control, the data control invokes the Edit and UpdateRecord methods.  Finally, data from any control where the DataChanged property is True is saved to the database.

In the code for the Validate event, you can set this property to False for any bound control where you do not want to save the data in the database.

Inspect the value of the DataChanged property in your code for a control's Change event to avoid a cascading event.  This applies to both bound and unbound controls.

Data Type

Integer (Boolean)


vbproDataChangedSee
See Also

Help:

Change Event

Data Access

Data Control

Edit Method

Update Method

UpdateRecord Method

Validate Event


DataSource Property

See Also

Applies To

Check box, image, label, picture box, text box, and other bound controls that may become available.

Description

Determines the data control through which the current control is bound to a database.  Read/write at design time; not available at run time.

Remarks

To bind a control to a field in a database at run time, you must specify a data control in this property at design time.  To complete the connection with a database, you must also provide the name of a Field object in the DataField property.  Unlike the DataSource property, the DataField property setting can be provided at run time.


vbproDataSourceSee
See Also

Help:

Data Access

RecordSource Property


GridLineWidth Property

See Also	Example

Applies To

Grid.

Description

Determines the width in pixels of the gridlines for a grid control.

Syntax

[form.] grid.GridLineWidth[ = numericexpression ]

Remarks

The minimum setting is 1; the maximum setting is 10.  The default is 1.

Data Type

Integer


vbproGridLineWidthSee
See Also

Help:

GridLines Property


vbproGridLineWidthEx
GridLineWidth Property Example

The example increments the width of gridlines in a grid with each click of the mouse.  To try this example, draw a grid on a form, paste this code into the Declarations section of the form, and then press F5 to run the program.

Sub Grid1_Click ()
If Grid1.GridLineWidth < 10 Then
' Increment width.
Grid1.GridLineWidth = Grid1.GridLineWidth + 1
Else
Grid1.GridLineWidth = 1	' Set width back to 1.
End If
End Sub


LastModified Property

See Also	Example

Applies To

Dynaset object, Table object.

Description

Contains the bookmark of the most recently added or changed record.  Not available at design time; read-only at run time.

Syntax

recordset.Bookmark = recordset.LastModified

Remarks

The recordset can be the Recordset property of a data control.  In the Professional Edition, it can also be an object variable identifying an open Dynaset object or Table object.

Use this property to make the most recently modified record the current record.

Data Type

Variant or String


vbproLastModifiedSee
See Also

Help:

Bookmark Property

Data Access

LastUpdated Property


vbproLastModifiedEx
LastModified Property Example

The example might be used with a menu in a program to allow users to return to the last record that was modified.

Data1.Recordset.Bookmark = Data1.Recordset.LastModified


SourceField, SourceTable Properties

See Also	Example

Applies To

Field object.

Description

Indicates the name of the field or table that is the original source of the data in the Field object.  Not available at design time; read-only at run time.

Syntax

{recordset | tabledef }.field.SourceField

{recordset | tabledef }.field.SourceTable

Remarks

You can use these properties to discover the original source of your data.  The Recordset property of a data control is a Dynaset object that can be the result of a query on several tables.  Depending on how the query is constructed, any field may or may not have the same name as in the original table.

Data Type

String


vbproSourceFieldNameSee
See Also

Help:

Data Access

Fields Collection

SourceTableName Property

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


vbproSourceFieldNameEx
SourceFieldName, SourceTableName Properties Example

The example creates a Dynaset object in a data control using an SQL statement that creates aliases for fields in two different tables.  The example then prints the name of the field, the name of the SourceTable, and the name of the SourceField in the Debug window.

Sub PrintSourceInfo ()
Dim MYSQL, I
Data1.DatabaseName = "BIBLIO.MDB"
' Construct the SQL statement.
MYSQL = "SELECT PubID As PID, Au_ID As AID"
MYSQL = MYSQL & " FROM Publishers, Authors"	' Set the RecordSource property.
Data1.RecordSource = MYSQL
Data1.Refresh
For I = 0 To Data1.Recordset.Fields.Count - 1
' Print field name.
Debug.Print Data1.Recordset.Fields(I).Name
' Print source table.
Debug.Print, Data1.Recordset.Fields(I).SourceTableName,
' Print source field.
Debug.Print Data1.Recordset.Fields(I).SourceFieldName
Next I
End Sub


Validate Event

See Also	Example

Applies To

Data control.

Description

The Validate event occurs before a different record becomes the current record; before the Update method (except when data is saved with the UpdateRecord method); and before a Delete, Unload or Close operation.

Syntax

Sub datacontrol_Validate ([ Index As Integer,] Action As Integer, Save As Integer)

Remarks

The Index part uniquely identifies a control if it is in a control array.

The Action part indicates the operation that is causing this event to occur.  The possible constants and values of Action are:

Constant	Value	Description

DATA_ACTIONCANCEL	0	Cancel the operation when the Sub exits.

DATA_ACTIONMOVEFIRST	1	MoveFirst method.

DATA_ACTIONMOVEPREVIOUS	2	MovePrevious method.

DATA_ACTIONMOVENEXT	3	MoveNext method.

DATA_ACTIONMOVELAST	4	MoveLast method.

DATA_ACTIONADDNEW	5	AddNew method.

DATA_ACTIONUPDATE	6	Update operation (not UpdateRecord).

DATA_ACTIONDELETE	7	Delete method.

DATA_ACTIONFIND	8	Find method.

DATA_ACTIONBOOKMARK	9	The Bookmark property has been set.

DATA_ACTIONCLOSE	10	The Close method.

DATA_ACTIONUNLOAD	11	The form is being unloaded.

These constants and values are in the Visual Basic file CONSTANT.TXT.

You can change the Action part to convert one action into another.  You can change the various Move methods and AddNew, which can be freely exchanged (any Move into AddNew, any Move into any other Move, or AddNew into any Move).  When in AddNew mode, you can use MoveNext and then execute another AddNew to examine the EditMode property to determine if an Edit or AddNew operation is in progress.  Attempting to change AddNew or one of the Moves into any of the other actions is either ignored or produces a trappable error.  Any action can be stopped by setting Action to 0.

The Save argument initially indicates whether bound data has changed (True/False).  Save can still be False if data in the copy buffer is changed.  If Save is True when this event exits, the Edit and UpdateRecord methods are invoked.  Only data from bound controls or from the copy buffer where the DataChanged property is True are saved by the UpdateRecord method.

This event occurs even if no changes have been made to data in bound controls, and even if there are no bound controls.  You can use this event to change values and update data as necessary.  You can also choose to save data or not, and choose to stop whatever action is causing the event to occur and substitute a different action.

In your code for this event, you can check the data in each bound control where DataChanged is True.  You can then set DataChanged to False to avoid saving that data in the database.

You cannot use any methods (such as MoveNext) on the underlying Dynaset object during this event.


vbevtValidateSee
See Also

Help:

AddNew Method

Bookmark Property

Close Method

Delete Method

Edit Method

EditMode Property

FindFirst, FindPrevious, FindNext, FindLast Methods

MoveFirst, MovePrevious, MoveNext, MoveLast Methods

Update Method

UpdateRecord Method

Programmers Guide:

Chapter 20, "Accessing Databases with the Data Control"


vbevtValidateEx
DataChanged Property and Validate Event Example

The example illustrates simple data validation.  In the Authors table in the BIBLIO.MDB database, there are two fields: Au_ID and Author.  Since the value in Au_ID is used to uniquely identify the author, this value should not change.  The example does not allow changes to the Au_ID field, which is bound to Text1.

Sub Data1_Validate (Action As Integer, Save As Integer)
If Text1.DataChanged Then	' Check for change in data.
MsgBox "You can't change the ID number."
Text1.DataChanged = False	' Do not save changed data.
End If
...
End Sub


SelCount Property

See Also

Applies to

List box

Description

Indicates the number of selected items in a list box; not available at design time and read-only at run time.

Syntax

[form.] [listbox].SelCount

Remarks

The SelCount property returns 0 if no items are selected. Otherwise, it returns the number of list items currently selected. This property is particularly useful when users can make multiple, disjoint selections.  You can quickly determine when all selected list items have been read without reading the entire list.

Data Type

Integer


vbproSelCountSee
See Also

Help:

AddItem Method

List Property

ListIndex Property

NewIndex Property

RemoveItem Method

Selected Property

TopIndex Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


SourceTableName Property

See Also

Applies To

TableDef object.

Description

For attached tables, indicates the name of the table as it exists in the original data source.  Not available at design time; read-only at run time.

Syntax

tabledef .SourceTableName

Remarks

You can use this property to discover the original source of your data.


vbproSourceTableNameSee
See Also

Help:

Data Access

Fields Collection

SourceField Property

SourceTable Property

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


Paste Link Command (Edit Menu)

See Also

Inserts Clipboard contents copied from another Windows-based application.  It also creates a link with that application to update the copied data automatically.

This command is unavailable unless the Clipboard contents are from an application that can transfer data to Visual Basic and the destination control of the link is capable of having a DDE link.


See Also

Help:

Creating a DDE Source or Destination Link

Programmer's Guide:

Chapter 17, "Interacting with the Environment"


Resize Event

See Also	Example

Applies To

Form, MDI form, OLE control, picture box.

Description

Occurs when a form first appears or the size of an object changes.

Syntax

Sub {Form|MDIForm|picturebox}_Resize ( )

Sub OLEControl_Resize (heightnew As Single, widthnew As Single)

Remarks

Use a Resize procedure to move or resize controls when the parent form is resized.  You can also use a Resize procedure to recalculate variables or properties (such as ScaleHeight and ScaleWidth) that may depend on the size of the form.  To invoke the Paint event every time a form is resized, use the Refresh method in a Resize procedure if you want graphics to maintain sizes proportional to the form when the form is resized.

Whenever the AutoRedraw property is set to False and the form is resized, Visual Basic also calls the related events in the order Resize, Paint.  When you attach procedures for these related events, be sure their actions don't conflict.

When an OLE control's SizeMode property is set to 2 (autosize), the control is automatically sized according to the display size of the object in the control.  If the display size of the object changes, the control is automatically resized to fit the object.  When this occurs, the Resize event is invoked before the OLE control is resized.  The heightnew and widthnew parts indicate the optimal size for displaying the object (this size is determined by the application that created the object).  You can size the control differently by changing the values of the heightnew and widthnew parts in the Resize event.


See Also

Help:

AutoRedraw Property

Load Statement

Paint Event

Refresh Method

Show Method

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Resize Event Example

The example automatically resizes a text box to fill the form whenever the form is resized.  To try this example, paste the code into the Declarations section of a form that contains a text box.  Set the text box MultiLine property to True, the ScrollBars property to 3, and the BorderStyle to 0.  Then press F5 and resize the form.

Sub Form_Load ()
Text1.Text = ""	' Clear text.
End Sub

Sub Form_Resize ()
Text1.Move 0,0, ScaleWidth, ScaleHeight
End Sub


BorderStyle Property

See Also

Applies To

Form, grid, image, label, line, OLE control, picture box, shape, text box.

Description

Determines the border style for an object.  For forms and text boxes, read-only at run time.

Usage

[form.][control.]BorderStyle

Setting

The BorderStyle property settings for a form are:

Setting	Description

0	None (no border or related border elements).

1	Fixed Single.  Can include Control-menu box, title bar, Maximize button, and Minimize button.  Resizable only using Maximize and Minimize buttons.

2	(Default) Sizable.  Resizable using any of the optional border elements listed for setting 1.

3	Fixed Double.  Can include Control-menu box and title bar; cannot include Maximize or Minimize buttons.  Not resizable.

The BorderStyle property settings for a grid, image, label, picture box, and text box are:

Setting	Description

0	(Default for image and label) None.

1	(Default for picture box and text box) Fixed Single.

The BorderStyle property settings for a line and a shape are:

Setting	Description

0	Transparent.

1	(Default) Solid.  The border is centered on the edge of the shape.

2	Dash.

3	Dot.

4	Dash-Dot.

5	Dash-Dot-Dot.

6	Inside Solid.  The outer edge of the border is the outer edge of the shape.

The BorderStyle property settings for an OLE control are:

Setting	Description

0	None.

1	Fixed Single.

Remarks

For a form, the BorderStyle property determines key characteristics that visually identify a form as either a general-purpose window or a dialog box.  Setting 3 (Fixed Double) is useful for standard dialog boxes.

MDI child forms set to 2 (Sizable) will appear within the MDI form in a default size defined by the Windows environment at run time.  For any other setting, the form will appear in the size specified at design time.

Note   If a form with a menu is set to 3 (Fixed Double), it will appear with a setting 1 (Fixed Single) border instead.

At run time, a form is either modal or modeless.  Use the Show method to specify whether a form is modal or modeless.

Data Type

Integer (Enumerated)


See Also

Help:

Caption Property

ControlBox Property

DrawStyle Property

MaxButton Property

MinButton Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Cancel Property

See Also

Applies To

Command button.

Description

Determines whether a command button is the Cancel button on a form.

Usage

[form.]commandbutton.Cancel[ = boolean ]

Setting

The Cancel property settings are:

Setting	Description

True	The command button is the Cancel button.

False	(Default) The command button isn't the Cancel button.

Remarks

Use the Cancel property to give a user the option of canceling uncommitted changes and returning the form to its previous state.

Only one command button on a form can be the Cancel button.  When the Cancel property is set to True for one command button, it is automatically set to False for all other command buttons on the form.  When a command button's Cancel property is True and the form is the active form, the user can choose the command button by clicking it, pressing the Esc key, or pressing Enter when the button has the focus.

Tip   For a form that supports irreversible operations, such as deletions, it's a good idea to make the Cancel button the default button.  To do this, set both the Cancel property and the Default property to True.

Data Type

Integer (Boolean)


See Also

Help:

CancelError Property

Default Property

KeyDown, KeyUp Events

KeyPress Event

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


FontBold, FontItalic, FontStrikethru, FontTransparent, FontUnderline Properties

See Also	Example

Apply To

Form, check box, combo box, command button, common dialog, data control, directory list box, drive list box, file list box, frame, grid, label, list box, option button, picture box, Printer object, text box.

Description

Determine font styles in the following formats:  FontBold, FontItalic, FontStrikethru, and FontUnderline.  FontTransparent determines whether background text or graphics are included with the characters in a particular font; FontTransparent applies only to forms, picture boxes, and the Printer object.

Usage

{[form.][control.]|Printer.}FontBold[ = boolean ]

{[form.][control.]|Printer.}FontItalic[ = boolean ]

{[form.][control.]|Printer.}FontStrikethru[ = boolean ]

{[form.][picturebox.]|Printer.}FontTransparent[ = boolean ]

{[form.][control.]|Printer.}FontUnderline[ = boolean ]

Setting

The settings for the FontBold, FontItalic, FontStrikethru, FontTransparent, and FontUnderline properties are:

Setting	Description

True	(Default for FontBold (except with the common dialog control) and FontTransparent) Turns on the formatting in that style.  Setting FontTransparent to True permits background graphics or text to show through the characters in a font.

False	(Default for FontItalic, FontStrikethru, and FontUnderline; and FontBold with the common dialog control) Turns off the formatting in that style.  Setting FontTransparent to False masks out existing background graphics or text.

Remarks

Use these font properties to format text, either at design time using the Properties window or at run time using code.  For forms, picture boxes, and the Printer object, setting these properties does not affect graphics or print output already drawn to a form, picture box, or Printer object.  For all other controls, font changes take effect on the screen immediately.

To use these properties with the common dialog control, the CF_EFFECTS flag must be set.

Note   Fonts available in Visual Basic vary according to your system configuration, display devices, and printing devices.  Font-related properties can be set only to values for which actual fonts exist.

In general, you should change the FontName property before you set size and style attributes with the FontSize, FontBold, FontItalic, FontStrikethru, FontTransparent, and FontUnderline properties.  However, when you set TrueType fonts to smaller than 8 points, you should set the point size with the FontSize property, then set the FontName property, and then set the size again with the FontSize property.  The Windows environment uses a different font for TrueType fonts that are smaller than 8 points.

Data Type

Integer (Boolean)


See Also

Help:

TextHeight Method

TextWidth Method

Programmer's Guide:

Chapter 16, "Displaying and Printing Information"


FontBold, FontItalic, FontStrikethru, FontTransparent, FontUnderline Properties Example

The example puts text on a form in one of two combinations of styles with each mouse click.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()
FontStrikethru = Not FontStrikethru	' Toggle strikethru.
FontItalic = Not FontStrikethru	' Toggle font style.
Print "Now is the time!"	' Print some text.
End Sub


Caption Property

See Also	Example

Applies To

Form, MDI form, check box, command button, data control, frame, label, menu, option button.

Description

Form [image] determines the text displayed in the form's title bar.  When the form is minimized, this text is displayed below the form's icon.

Controls [image] determines the text displayed in or next to a control.

Usage

[form.][control.]Caption[ = stringexpression ]

Remarks

When you create a new object, its default caption is the same as the default Name for both forms and controls.  This default caption includes the object name and an integer, such as Command1 or Form1.  For a more descriptive label, set the Caption property.

You can use the Caption property to assign an access key to a control.  In the caption, include an ampersand (&) immediately preceding the character you want for an access key.  The character will be underlined.  Press Alt plus the underlined character to move the focus to that control.  To include an ampersand in a caption without creating an access key, type a double ampersand (&&).  A single ampersand will appear in the caption and no characters will be underlined.

For labels, the caption is limited to 2048 characters.  For forms and all other controls that have captions, the limit is 255 characters.

To display a form caption, set the BorderStyle property to either 1, 2, or 3.  A caption too long for the form's title bar will be clipped.

When an MDI child form is maximized within an MDI form, the child form's caption is included with the parent form's caption.

Note   For a label, set the AutoSize property to True to automatically resize the control to fit its caption.

Data Type

String


See Also

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Caption Property Example

The example changes the caption on a command button each time the user clicks the button.  To try this example, paste the code into the Declarations section of a form containing a command button named Command1.  Then press F5 and click the button.

Sub Command1_Click ()
' Check caption, then change it.
If Command1.Caption = "Clicked" Then
Command1.Caption = "OK"
Else
Command1.Caption = "Clicked"
End If
End Sub


AutoSize Property

 See Also

Applies To

Label, picture box.

Description

Determines whether a control is automatically resized to fit its contents.

Usage

[form.]control.AutoSize[ = {True|False}]

Remarks

The AutoSize property settings are:

Setting	Description

True 	Automatically resizes the control to fit its contents.

False 	(Default) Keeps the size of the control constant.  Contents are clipped when they exceed the area of the control.

Data Type

Integer (Boolean)


See Also

Help:

Alignment Property

Resize Event

SizeMode Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


FontName Property

See Also	Example

Applies To

Form, check box, combo box, command button, common dialog, data control, directory list box, drive list box, file list box, frame, grid, label, list box, option button, picture box, Printer object, text box.

Description

Determines the font used to display text in a control or in a run-time drawing or printing operation.

Usage

{[form.][control.]|Printer.}FontName[ = font ]

Remarks

The default for this property is determined by the system.  Fonts available with Visual Basic vary according to your system configuration, display devices, and printing devices.  Font-related properties can be set only to values for which fonts exist.

In general, you should change FontName before setting size and style attributes with the FontSize, FontBold, FontItalic, FontStrikethru, FontTransparent, and FontUnderline properties.

On systems running Windows 3.0, the fonts "Helv" or "Tms Rmn" are called "MS Sans Serif" and "MS Serif", respectively.  In code, if you set FontName to "Helv," then test whether the FontName is set to "Helv," the result will be False, since it will be changed internally to "MS Sans Serif."

Note   At run time, you can get information on fonts available to the system through the FontCount and Fonts properties.

Data Type

String


See Also

Help:

FontBold, FontItalic, FontStrikethru, FontTransparent, FontUnderline Properties

FontSize Property

Print Method

TextHeight Method

TextWidth Method

Programmer's Guide:

Chapter 16, "Displaying and Printing Information"


FontName Property Example

The example prints the name of each font using the particular font.  To try this example, paste the code into the Declarations section of a form.  Press F5 to run the program and then click the form.  Each time you click the form, the font name is printed.

Sub Form_Click ()
Static I	' Declare variables.
Dim OldFont
OldFont = FontName	' Preserve original font.
FontName = Screen.Fonts(I)	' Change to new font.
Print Screen.Fonts(I)	' Print name of font.
I = I + 1	' Increment counter.
If I = FontCount Then I = 0	' Start over.
FontName = OldFont	' Restore original font.
End Sub


FontSize Property

See Also	Example

Applies To

Form, check box, combo box, command button, common dialog, data control, directory list box, drive list box, file list box, frame, grid, label, list box, option button, picture box, Printer object, text box.

Description

Determines the size of the font to be used for text displayed in a control or in a run-time drawing or printing operation.

Usage

{[form.][control.]|Printer.}FontSize[ = points ]

Remarks

Use this property to format text in the font size you want.  The default is determined by the system.  To change the default, specify the size of the font in points.

The maximum value for FontSize is 2048 points.

Note   Fonts available with Visual Basic vary according to your system configuration, display devices, and printing devices.  Font-related properties can be set only to values for which fonts exist.

In general, you should change the FontName property before you set size and style attributes with the FontSize, FontBold, FontItalic, FontStrikethru, FontTransparent, and FontUnderline properties.  However, when you set TrueType fonts to smaller than 8 points, you should set the point size with the FontSize property, then set the FontName property, and then set the size again with the FontSize property.  The Windows environment uses a different font for TrueType fonts that are smaller than 8 points.

Data Type

Single


See Also

Help:

FontBold, FontItalic, FontStrikethru, FontTransparent, FontUnderline Properties

FontCount Property

Fonts Property

Programmer's Guide:

Chapter 16, "Displaying and Printing Information"


FontSize Property Example

The example prints text on your form in two different point sizes with each click of the mouse.  To try this example, paste the code into the Declarations section of a form.  Press F5 to run the program and then click the form.

Sub Form_Click ()
FontSize = 24	' Set FontSize.
Print "This is 24 point type."	' Print large type.
FontSize = 8	' Set FontSize.
Print "This is 8 point type."	' Print small type.
End Sub


Height, Width Properties

See Also	Example

Apply To

Form, MDI form, check box, combo box, command button, data control, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, list box, OLE control, option button, picture box, Printer object, Screen object, shape, text box, vertical scroll bar.

Description

Determine the dimensions of an object.

Usage

{[form.][control.]|Printer.|Screen.}Height[ = numericexpression ]

{[form.][control.]|Printer.|Screen.}Width[ = numericexpression ]

Remarks

Measurements are calculated as follows:

Form [image] the external height and width of the form, including the borders and title bar.

Control [image] measured from the center of the control's border so that controls with different border widths align correctly.  These properties use the scale units of a control's container.

Printer object [image] the physical dimensions of the paper set up for the printing device; not available at design time and read-only at run time.

Screen object [image] the height and width of the screen; not available at design time and read-only at run time.

For a form, Printer object, and Screen object, these properties are always measured in twips.  For a form or control, the values for these properties change as the object is sized by the user or by code.  Maximum limits of these properties for all objects are system-dependent.

Use the Height, Width, Left, and Top properties for operations or calculations based on an object's total area, such as sizing or moving the object.  Use the ScaleLeft, ScaleTop, ScaleHeight, and ScaleWidth properties for operations or calculations based on an object's internal area, such as drawing or moving objects within another object.

Note   The Height property can't be changed for drive list boxes or for combo boxes whose Style property is 0 (Dropdown Combo) or 2 (Dropdown List).

Data Type

Single


See Also

Help:

Left, Top Properties

Move Method

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

Width # Statement


Height, Width Properties Example

The example sets the size of a form to 75% of screen size, and centers the form when it is loaded.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Load ()
Width = Screen.Width * .75	' Set width of form.
Height = Screen.Height * .75	' Set height of form.
Left = (Screen.Width - Width) / 2	' Center form horizontally.
Top = (Screen.Height - Height) / 2	' Center form vertically.
End Sub


Option Base Statement

See Also	Example

Declares the default lower bound for array subscripts.

Syntax

Option Base number

Remarks

The Option Base statement is never required.  If used, it can appear only once in a form or module, can occur only in the Declarations section, and must be used before you declare the dimensions of any arrays.

The value of number must be either 0 or 1.  The default base is 0.

The Option Base statement has no effect on arrays within user-defined types.  However, use caution, as this will not be true in future versions of Visual Basic.  The lower bound for all such arrays is always 0.

Tip   The To clause in the Dim, Global, ReDim, and Static statements provides a more flexible way to control the range of an array's subscripts.  However, if you don't explicitly set the lower bound with a To clause, you can use Option Base to change the default lower bound to 1.


See Also

Dim Statement

Global Statement

LBound Function

ReDim Statement

Static Statement


Option Base Statement Example

The example uses the Option Base statement to override the default base array subscript value of 0.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Option Base 1	' Module level statement.
Sub Form_Click ()
Dim A(), Msg, NL	' Declare variables.
NL = Chr(10)	' Define newline.
ReDim A(20)	' Create an array.
Msg = "The lower bound of the A array is " & LBound(A) & "."
Msg = Msg & NL & "The upper bound is " & UBound(A) & "."
MsgBox Msg	' Display message.
End Sub


Controls

See Also	Controls List

Description

A control is an object that you draw on a form to enable or enhance user interaction with an application.  You add menu controls to a form using the Menu Design window; all other controls appear in the Toolbox and are placed on a form by double-clicking them or by clicking and then dragging them onto a form.

Remarks

Controls accept user input or display output.  Controls have properties that define aspects of their appearance, such as position, size, and color, and aspects of their behavior, such as how they respond to user input.

Controls can respond to events initiated by the user or triggered by the system.  For example, you could write code in a command button's Click event procedure that would load a file or perform a calculation and then display the result.

In addition to properties and events, you can use methods to manipulate controls from code.  For example, you can use the Move method with some controls to change their location and size.

Each control has its own set of properties, events and methods.

Note that the Control keyword is an object type and you can use it to declare a variable of type Control before setting it to a specific control type.  You can also declare a procedure parameter to have type Control.

Graphical controls include the image, label, line, and shape controls.  A graphical control uses fewer system resources and has different drawing and display characteristics than other controls.


Controls List

Control	Description

Check box	Gives the user a True/False or Yes/No option.

Combo box	Enables the user to make a selection by typing text into a text box or by selecting an item from a list.

Command button	Chosen by the user to begin or end a process.

Common dialog	Provides a standard set of dialog boxes for operations such as opening, saving, and printing files or selecting colors and fonts.

Data control	Enables the developer to create applications that view and manipulate databases.

Directory list box	Enables the user to select directories and paths at run time.

Drive list box	Enables the user to select valid disk drives at run time.

File list box	Enables the user to select files at run time.

Frame	Provides a functional grouping and container for other controls.

Grid	Provides a matrix of spreadsheet-type cells whose contents can be manipulated in code.  Grid is a custom control supplied with Visual Basic.

Horizontal scroll bar	Allows navigation through lists or forms; also can indicate position in a range.

Image	Displays a bitmap, icon, or metafile as a graphic.

Label	Displays text the user can't change.

Line	Displays itself as a horizontal, vertical, or diagonal line.

List box	Displays a list from which the user can select one or more items.

Menu	Displays a menu on a form.

OLE control	Allows a programmer to create applications that can display and allow editing of data from many different applications [image] for example, objects created by draw, graphics, and spreadsheet applications.  Data from another application can be edited within the application in which it was created

Option button	As part of a group of option buttons, displays multiple choices from which the user can select only one.

Picture box	Displays graphics that are drawn with Circle, Line, and Print methods, or that are loaded from a bitmap, icon, or metafile.  Can also act as a container for other controls.

Shape	Displays itself as a variety of shapes including boxes, circles, and so on.

Text box	Displays text the user can edit.

Timer	Enables you to run code at a specified time interval.

Vertical scroll bar	Allows navigation through lists or forms; also can indicate position in a range.


See Also

Help:

ActiveControl Property

ActiveForm Property

Controls Collection

Creating a Menu Bar

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


EOF Function

See Also	Example

Returns a value during file input that indicates whether the end of a file has been reached.

Syntax

EOF(filenumber)

Remarks

The argument filenumber is the number used in the Open statement to open the file.  You can use any numeric expression that evaluates to the number of an open file.

The EOF function returns True if the end of a file has been reached, and False if it has not.  Use the EOF function with sequential files to test for the end of a file.  This helps you avoid the error that occurs when you attempt to get input past the end of a file.

When used with Random or Binary files, EOF returns True if the last executed Get statement was unable to read an entire record; otherwise, it returns False.


See Also

Loc Function

LOF Function

Open Statement


EOF Function Example

The example uses the EOF function to detect the end of a sequential file.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()
Dim NL, TestVar, Msg	' Declare variables.
NL = Chr(10)	' Define newline.
MakeDataFile	' Create sample data file.
Open "TESTFILE" For Input As #1	' Open file for input.
Do While Not EOF(1)	' Check for end of file.
Input #1, TestVar	' Read data.
Loop
Close #1	' Close file.
Msg = "The last value read from the data file was "
Msg = Msg & TestVar & "." & NL
Msg = Msg & NL & "Choose OK to remove the created test file."
MsgBox Msg	' Display results.
Kill "TESTFILE"	' Delete file from disk.
End Sub

Sub MakeDataFile ()
Dim I	' Declare variable.
Open "TESTFILE" For Output As #1	' Open file.
For I = 0 To 200	' Generate random values
Print #1, Int((100) * Rnd)	' from 0 to 99.
Next I
Close #1	' Close file.
End Sub


InStr Function

See Also	Example

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

Syntax 1

InStr( [start,] strexpr1, strexpr2 )

Syntax 2

 InStr(start, strexpr1, strexpr2 [, compare] )

Remarks

The InStr function has these parts:

Part	Description

start	Numeric expression that sets the starting position for each search; start must be between 1 and approximately 65,535.  If start is omitted, the search of strexpr1 begins at the first character position.  The start argument is not optional if the compare argument is specified.

strexpr1	String expression being searched.

strexpr2	String expression being sought.

compare	Specifies the string-comparison method.  The argument compare can be omitted; it can be 0 or 1; or it can be the value of the CollatingOrder property of a Field object.  If compare is omitted, the module default string-comparison method is used.  Unless you use Option Compare Text to change the default comparison method, the default is Option Compare Binary.

If compare is 0, string comparison is case-sensitive; so, for example, "M" doesn't match "m".  If compare is 1, string comparison is not case-sensitive; so, for example, "M" matches "m".

If you want to sort or compare values from a Database, Snapshot or Dynaset in the same way the Database would, you must provide the CollatingOrder property of the Field object.

If strexpr2 is found within strexpr1, InStr returns the position at which the match was found.  If strexpr2 is zero-length, start is returned.  If start is greater than strexpr2, strexpr1 is zero-length, or strexpr2 can't be found, InStr returns 0.

If either string expression is Null, the function returns a Null.  If start or compare is Null, an error occurs.


See Also

Option Compare Statement

StrComp Function


InStr Function Example

The example uses InStr to return the position of a character within a string.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()
Dim Alphabet, LetterNum, Msg, UsrInput	' Declare variables.
Alphabet ="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Msg = "Please enter a single letter of the alphabet."
UsrInput = UCase(InputBox(Msg))	' Get user input.
If Len(UsrInput) Then
LetterNum = InStr(Alphabet, UsrInput)	' Get position.
If LetterNum <> 0 Then
Msg = "Your letter is number " & LetterNum
Msg = Msg  & " of " & Len(Alphabet) & "."
Else
Msg = "You didn't enter a letter of the alphabet!"
End If
Else
Msg = "You didn't enter anything."
End If
MsgBox Msg	' Display message.
End Sub


StrComp Function

See Also	Example

Returns a Variant that indicates the result of the comparison of two string arguments.

Syntax

StrComp(stringexpr1, stringexpr2 [, compare] )

Remarks

The StrComp function has these parts:

Part	Description

stringexpr1	Any string expression.

stringexpr2	Any string expression.

compare	Specifies the string-comparison method.  The argument compare can be omitted; it can be 0 or 1; or it can be the value of the CollatingOrder property of a Field object.  If compare is omitted, the module default string-comparison method is used.  Unless you use Option Compare Text to change the default comparison method, the default is Option Compare Binary.

If compare is 0, string comparison is case-sensitive; so, for example, "M" is less than "m".  If compare is not 0, string comparison is not case-sensitive; so, for example, "M" matches "m".

If you want to sort or compare values from a Database, Snapshot or Dynaset in the same way the Database would, you must provide the CollatingOrder property of the Field object.

The StrComp function returns a Variant that indicates the relationship between the string expressions.  Regardless of underlying data type (Variant or String), each string expression argument is converted to a Variant and then both arguments are compared.  The following table illustrates the possible StrComp return values:

Return value	Condition

1	stringexpr1 < stringexpr2

0	stringexpr1 = stringexpr2

1	stringexpr1 > stringexpr2

Null	stringexpr1 = Null or stringexpr2 = Null


See Also

Instr Function

Option Compare Statement


StrComp Function Example

The example uses StrComp to compare two variables.  If the default comparison method is in effect (Option Compare Binary), this code will indicate that Var1 is less than Var2.  However, if Option Compare Text is in effect, the comparison will indicate that the variables are equal.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()
Dim Cmp, Msg, Var1, Var2	' Declare variables.
Var1 = "ABCD": Var2 = "abcd"	' Define variables.
Cmp = StrComp(Var1, Var2)	' Compare variables.
Select Case Cmp
Case -1
Msg = "Var1 is less than Var2."
Case 0
Msg = "Var1 is equal to Var2."
Case 1
Msg = "Var1 is greater than Var2."
End Select
MsgBox Msg	' Display message.
End Sub


Count Property

See Also

Applies To

Forms collection, Controls collection, Fields collection, Indexes collection, TableDefs collection.

Description

Forms collection [image] specifies the number of loaded forms.

Controls collection [image] specifies the number of controls on a form, including menus and menu items.

Fields, Indexes, TableDefs collections [image] specifies the number of objects in the collection.

Not available at design time; read-only at run time.

Usage

Forms.Count

[form.]Controls.Count

database.TableDefs.Count

{tabledef | recordset}.Fields.Count

{table | tabledef}.Indexes.Count

Remarks

You can use this property in a For...Next loop to specify the number of forms or controls in a collection.  For example, the following code would move all controls on a form one-half inch to the right (ScaleMode = 0):

For I = 0 To Form1.Count - 1
Form1.Controls(I).Left = Form1.Controls(I).Left + 720
Next I

You can also use this kind of structure to quickly enable or disable all controls on a form.

When used with the If TypeOf statement, you can cycle through all controls and change, for example, the values of only the text boxes, or the BackColor setting of all the option buttons.

Data Type

Integer


See Also

Help:

Count Function (SQL Only)

RecordCount Property

Programmer's Guide:

Chapter 8, "Objects and Instances"


Value Property

See Also	Example

Applies To

Check box, command button, Field object, horizontal scroll bar, option button, vertical scroll bar.

Description

Check box, option button [image] determines the state of the control.

Command button [image] determines whether the button is chosen; not available at design time.

Field object [image] determines the content of a field.

Horizontal and vertical scroll bars [image] determines the current position of the scroll bar, whose return value is always between the values for the Max and Min properties, inclusive.

Usage

{[form.]control | field}.Value[ = setting ]

Setting

The Value property settings are:

Check box [image] 0 is Unchecked (default), 1 is Checked, and 2 is Grayed (dimmed).

Command button [image] True indicates the button is chosen; False (the default), indicates the button is not chosen.  Setting the Value property to True in code invokes the button's Click event.

Field object [image] restricted only by the Field data types.

Horizontal and vertical scroll bars [image] set values between [image] 32,768 and 32,767 to position the scroll box.

Option button [image] True indicates the button is selected; False, the default, indicates the button is not selected.

Remarks

A default property of an object is assumed, and does not need to be specified in code.  For example, Field is the default property of any Recordset, and Value is the default property of a Field object.  This makes the two statements below equivalent:

Dn.Fields("PubID").Value = X
Dn.("PubID") = X

The first statement specifies the default properties; the second statement assumes them.

Data Type

Check box [image] Integer (Enumerated)

Command button, option button [image] Integer (Boolean)

Field objects [image] any one of the Field data types

Horizontal and vertical scroll bars [image] Integer


See Also

Help:

Max, Min Properties

Data Access

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Value Property Example

The example displays a horizontal scroll bar's numeric value in a text box.  To try this example, paste the code into the Declarations section of a form that has a text box and horizontal scroll bar.  Press F5 to run the program and then click the scroll bar.

Sub Form_Load ()
HScroll1.Min = 0	' Initialize scroll bar.
HScroll1.Max = 1000
HScroll1.LargeChange = 100
HScroll1.SmallChange = 1
End Sub

Sub HScroll1_Change ()
Text1.Text = Format (HScroll1.Value)
End Sub


Name Property

See Also

Applies To

All forms and controls, Database object, Dynaset object, Field object, Index object, QueryDef object, Snapshot object, Table object, TableDef object.

Description

Specifies the name used in code to identify a form, control, or data access object.  Not available at run time.

Remarks

The default name for new objects is the kind of object plus a unique integer.  For example, the first new form is "Form1," a new MDI form is "MDIForm1," and the third text box you create on a form is "Text3."

An object's Name property must start with a letter and can be a maximum of 40 characters.  It can include numbers and underscore characters but can't include punctuation or spaces.  Forms can't have the same name as another global object such as Clipboard, Screen, or App.  However, unlike Visual Basic 1.0, a name can be the same as a reserved word, property name, or the name of another object, but this can create conflicts in your code.  For information on handling naming conflicts, see Chapter 6, "Programming Fundamentals," in the Programmer's Guide.

You can use a form's Name property with the Dim statement in code to create other instances of the form.

You can't have two forms at design time with the same name.  You can create an array of controls of the same type by setting the Name property to the same value.  For example, when you set the name of all option buttons in a group to "MyOpt," Visual Basic assigns unique values to the Index property of each control to distinguish it from others in the array.  Two controls of different types can't share the same name.

Note   Although Visual Basic often uses the Name property as the default value for the Caption, LinkTopic, and Text properties, changing one does not affect the others.

For many of the Database objects, the Name property reflects the name as known to the Database, as in the name of a Table, Field, or QueryDef.  There is no direct link between the name of the Database object and the object variable used to reference it.  The name of the Dynaset or Snapshot is either the Name property of a Table or QueryDef used to create it, or the SQL statement used to create it.

Data Type

String


See Also

Help:

ActiveForm Property

Caption Property

Data Access

Dim Statement

Index Property (Control Arrays)

Index Property (Data Access)

LinkTopic Property

Me Reserved Word

Text Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 6, "Programming Fundamentals"

Chapter 20, "Accessing Databases with the Data Control"

Data Access Guide

Chapter 2, "Database Management Using Visual Basic"


Show Method

See Also	Example

Displays a form.

Syntax

[form.]Show [style]

Remarks

The Show method has these parts:

Part	Description

form	Form or MDI form to display. If not specified, the form associated with the current form module is displayed.

style	Integer value that determines if the form is modal or modeless.  If style is 0, the form is modeless; if style is 1, the form is modal.

If the specified form is not loaded when the Show method is invoked, Visual Basic automatically loads it.

When a modeless form is displayed, Visual Basic code that occurs after the Show method is executed as it is encountered.  When a modal form is displayed, no Visual Basic code after the Show method is executed until the form is hidden or unloaded.

When displaying a modal form, no user input (keyboard or mouse) can occur in any other form until the modal form is hidden or unloaded.  The program must hide or unload a modal form (usually in response to some user action) before further user input can occur.  MDI forms cannot be shown modally.

Although other forms in your application are disabled when a modal form is displayed, other applications are not.

The startup form of an application is automatically shown after its Load event is executed.

Note   Controls are not painted immediately after the form is shown.  If you experience problems painting controls, use the DoEvents statement or the Refresh method to allow the Paint event to complete processing.


See Also

Activate Event

Hide Method

Load Statement

Unload Statement

Visible Property


Show Method Example

The example uses the Show method to show a hidden form.  To try this example, paste the code into the Declarations section of a non-MDI form.  Then press F5 and click the form.

Sub Form_Click ()
Dim Msg	' Declare variable.
Hide	' Hide form.
Msg = "Choose OK to make the form reappear."
MsgBox Msg	' Display message.
Show	' Show form again.
End Sub


MouseMove Event

See Also	Example

Applies To

Form (not MDI form), check box, command button, data control, directory list box, file list box, frame, grid, image, label, list box, OLE control, option button, picture box, text box.

Description

Occurs when the user moves the mouse.

Syntax

Sub Form_MouseMove (Button As Integer, Shift As Integer, X As Single, Y As Single)

Sub ctlname_MouseMove ([Index As Integer,] Button As Integer, Shift As Integer, X As Single, Y As Single)

Remarks

The MouseMove event uses these arguments:

Argument	Description

Index	Uniquely identifies a control if it is in a control array.

Button	The state of the mouse buttons, in which a bit is set if the button is down.  The Button argument is a bit field, with bits corresponding to the left button (bit 0), right button (bit 1), and middle button (bit 2) [image] values 1, 2, and 4, respectively.  It indicates the complete state of the mouse buttons; some, all, or none of these three bits can be set, indicating that some, all, or none of the buttons is pressed.

Shift	The state of the Shift, Ctrl and Alt keys.  Bit is set if the key is down.  The Shift argument is a bit field, with the least-significant bits corresponding to the Shift key (bit 0), the Ctrl key (bit 1), and the Alt key (bit 2 ).  These bits correspond to the values 1, 2, and 4, respectively.  Shift indicates the state of these keys.  Some, all, or none of the bits can be set, indicating that some, all, or none of the keys is pressed.  For example, if both Ctrl and Alt were pressed, the value of Shift would be 6.

X ,Y	The current location of the mouse pointer.  X and Y are always expressed in terms of the coordinate system set by the ScaleHeight, Scale Width, ScaleLeft, and ScaleTop properties of the object.

The MouseMove event is generated continually as the mouse pointer moves across objects.  Unless another object has captured the mouse, an object recognizes a MouseMove event whenever the mouse position is within its borders.

If you need to test for the Button or Shift arguments, you can declare constants that define the bits within the argument by loading the CONSTANT.TXT file into a module.  These mouse button constants have the following values:

Constant	Value

LEFT_BUTTON	1

RIGHT_BUTTON	2

MIDDLE_BUTTON	4

SHIFT_MASK	1

CTRL_MASK	2

ALT_MASK	4

These are in CONSTANT.TXT.  The constants act as bit masks you can use to test for any combination of buttons without having to figure out the unique bit field value for each combination.

You test for a condition by first assigning each result to a temporary integer variable and then comparing the Button or Shift arguments to a bit mask.  Use the And operator with each argument to test if the condition is greater than zero, indicating the key or button is pressed [image] for example:

LeftDown = (Button And LEFT_BUTTON) > 0
CtrlDown = (Shift And CTRL_MASK) > 0

Then, in a procedure, you can test for any combination of conditions [image] for example:

If LeftDown And CtrlDown Then

Note   You can use MouseDown and MouseUp event procedures to respond to events caused by pressing and releasing mouse buttons.

The Button argument for MouseMove differs from the Button argument for MouseDown and MouseUp.  For MouseMove, the Button argument indicates the current state of all buttons; a single MouseMove event can indicate that some, all, or no button is pressed.  For MouseDown or MouseUp, the Button argument indicates exactly one button per event.

Any time you move a window inside a MouseMove event, it can cascade.  MouseMove events are generated when the window moves underneath the pointer.  A MouseMove event can be generated even if the mouse is perfectly stationary.


See Also

Help:

Click Event

DblClick Event

MousePointer Property

MouseDown, MouseUp Events

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"


MouseMove Event Example

The example demonstrates a simple paint application.  The MouseDown procedure works with a related MouseMove procedure to paint when any mouse button is pressed.  The MouseUp procedure turns off the paintbrush.  To try this example, paste the code into the Declarations section of a form.  Then press F5, click the form and move the mouse while the mouse button is pressed.

Dim PaintNow As Integer	' Declare variable.
Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)
PaintNow = True	' Paintbrush on.
End Sub

Sub Form_MouseUp (Button As Integer, X As Single, Y As Single)
PaintNow = False	' Turn off painting.
End Sub

Sub Form_MouseMove (Button As Integer, Shift As Integer, X As Single, Y As Single)
If PaintNow Then
PSet (X, Y)	' Draw a point.
End If
End Sub

Sub Form_Load ()
DrawWidth = 10	' Use wider paintbrush.
ForeColor = RGB(0, 0, 255)	' Set drawing color.
End Sub


LinkItem Property

See Also	Example

Applies To

Label, picture box, text box.

Description

Specifies the data passed to a destination control in a DDE conversation with another application; corresponds to the item argument in the standard DDE syntax, with application, topic, and item as arguments.

Usage

[form.]{label|picturebox|textbox}.LinkItem[ = stringexpression ]

Remarks

To set this property, specify a recognizable unit of data in an application as a reference [image] for example, a cell reference such as "R1C1" in Microsoft Excel.

Use LinkItem in combination with the LinkTopic property to specify the complete data link for a destination control to a source application.  To activate this link, set the LinkMode property.

You set LinkItem only for a control used as a destination.  When a Visual Basic form is a source in a DDE conversation, the name of any label, picture box, or text box on the form can be the item argument in the application|topic!item string used by the destination.  For example, the syntax:  =VizBasicApplication|MyForm!TextBox1 represents a valid reference from Microsoft Excel to a Visual Basic application.  You would enter this syntax for a destination cell in the Microsoft Excel formula bar.

Avoiding infinite loops  A DDE control can potentially act as destination and source simultaneously, causing an infinite loop if a destination-source pair is also a source-destination pair with itself.  For instance, a text box may be both a source (through its parent form) and destination of the same cell in Microsoft Excel.  When data in a Visual Basic text box changes, sending data to Microsoft Excel, the cell in Microsoft Excel changes, sending the change to the text box, and so on, causing the loop.

To avoid such loops, use related but not identical items for destination-source and source-destination links in both directions between applications.  For example, in Microsoft Excel, use related cells (precedents or dependents) to link a worksheet with a Visual Basic control, thus avoiding using a single item as both destination and source.  You should document any application|topic pairs you establish if you include a Paste Link command for run-time use.

Note	Setting a permanent data link at design time with the Paste Link command from the Edit menu also sets the LinkMode, LinkTopic, and LinkItem properties.  This creates a link that is saved with the form.  Each time the form is loaded, Visual Basic attempts to reestablish the conversation.

Data Type

String


See Also

Help:

Creating a DDE Source or Destination Link

LinkSend Method

LinkMode Property

LinkTopic Property

Using DDE

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


LinkMode Property

See Also	Example

Applies To

Form, label, picture box, text box.

Description

Determines the type of link used for a DDE conversation and activates the connection as follows:

Control [image] allows a destination control on a Visual Basic form to initiate a conversation as specified through the control's LinkTopic and LinkItem properties.

Form [image] allows a destination application to initiate a conversation with a Visual Basic source form, as specified through the destination application's application|topic!item expression.

Usage

[form.][label.|picturebox.|textbox.]LinkMode[ = mode ]

Remarks

For controls used as destinations in DDE conversations, the LinkMode property settings are:

Setting	Description

0	(Default) None.  No DDE interaction.

1	Automatic.  Destination control is updated each time the linked data changes.

2	Manual.  Destination control is updated only when the LinkRequest method is invoked.

3	Notify.  A LinkNotify event occurs whenever the linked data changes, but the destination control is updated only when the LinkRequest method is invoked.

For forms used as sources in DDE conversations, the LinkMode property settings are:

Setting	Description

0	(Default) None.  No DDE interaction.  No destination application can initiate a conversation with the source form as the topic, and no application can poke data to the form.  If LinkMode is 0 (None) at design time, you cannot change it to 1 (Source) at run time.

1	Source.  Allows any label, picture box, or text box on a form to supply data to any destination application that establishes a DDE conversation with the form.  If such a link exists, Visual Basic automatically notifies the destination whenever the contents of a control are changed.  In addition, a destination application can poke data to any label, picture box, or text box on the form.  If LinkMode is 1 (Source) at design time, you can change it to 0 (None) and back at run time.

The following conditions also apply to the LinkMode property:

Setting LinkMode to a nonzero value for a destination control causes Visual Basic to attempt to initiate the conversation specified in the LinkTopic and LinkItem properties.  The source updates the destination control according to the type of link specified (automatic, manual, or notify).

If a label, picture box, or text box has established an automatic link with a source application, a Change event occurs for that control each time new data is entered, whether or not the value of the data differs from the control's current contents.  Note that this is the only way a Change event can occur for a label control.

If a source application terminates a conversation with a Visual Basic destination control, the value for that controls LinkMode setting changes to 0 (None).

If you leave LinkMode for a form set to the default 0 (None) at design time, you cannot change LinkMode at run time. If you want a form to act as a source, you must set LinkMode to 1 (Source) at design time. You can then change the value of LinkMode at run time.

Note	Setting a permanent data link at design time with the Paste Link command from the Edit menu also sets the LinkMode, LinkTopic, and LinkItem properties.  This creates a link that is saved with the form.  Each time the form is loaded, Visual Basic attempts to reestablish the conversation.

Data Type

Integer


See Also

Help:

Creating a DDE Source or Destination Link

LinkClose Event

LinkError Event

LinkExecute Method

LinkItem Property

LinkNotify Event

LinkOpen Event

LinkSend Method

LinkTimeout Property

LinkTopic Property

Using DDE

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


LinkTimeout Property

See Also

Applies To

Label, picture box, text box.

Description

Determines the amount of time a control waits for a response to a DDE message.

Usage

[form.]{label|picturebox|textbox}.LinkTimeout[ = duration ]

Remarks

By default, the LinkTimeout property is set to 50 (equivalent to 5 seconds).  You can specify other settings in tenths of a second.

DDE response time from source applications varies.  Use this property to adjust the time a destination control waits for a response from a source application.  This helps avoid generating an error by Visual Basic if a given source application takes too long to respond.

Note	The maximum length of time that a control can wait is 65535 tenths of a second, or about 1 hour 49 minutes.  Setting LinkTimeout to -1 tells the control to wait the maximum length of time for a response in a DDE conversation.  The user can force the control to stop waiting by pressing the Esc key.

Data Type

Integer


See Also

Help:

LinkClose Event

LinkItem Property

LinkMode Property

LinkOpen Event

LinkSend Method

LinkTopic Property

Using DDE

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


LinkTopic Property

See Also	Example

Applies To

Form, label, picture box, text box.

Description

For a destination control [image] determines the source application and the topic.  You use LinkTopic with the LinkItem property to specify the complete data link.

For a source form [image] determines the topic that the source form responds to in a DDE conversation.

Usage

[form.][label.|picturebox.|textbox.]LinkTopic[ = link ]

Remarks

The LinkTopic property consists of a string that supplies part of the information necessary to set up either a destination link or source link.  The string you use depends on whether you're working with a destination control or a source form.  Each string corresponds to one or more elements of standard DDE syntax [image] application, topic, and item.

Destination control  To set LinkTopic for a destination control, use a string with the syntax application|topic, as follows:

application is the name of the application from which data is requested, usually the executable file name without any extension [image] for example, "Excel" (for Microsoft Excel).

The "pipe" character (|, or character code 124) separates the application from the topic.

topic is the fundamental data grouping used in that application [image] for example, a worksheet in Microsoft Excel.

In addition, for a destination control only, you need to set the related LinkItem property to specify the item element for the link.  A cell reference such as "R1C1," for example, would correspond to an item in a Microsoft Excel worksheet.

Source form  To set LinkTopic for a source, change the default string, FormN, to an appropriate identifier for the form.  A destination application uses this string as the topic argument when establishing a DDE link with the form.  Although this string is all you need to set LinkTopic within Visual Basic for a source form, the destination application itself also needs to specify:

The application element that the destination application uses, which is either the Visual Basic project name without the .MAK extension (if you are running your application in the Visual Basic development environment), or the Visual Basic application name without the .EXE extension (if you are running your application as a stand-alone executable file).  The EXEName property of the App object provides this string in your Visual Basic code unless the file name was changed by the user.  (App.EXEName always returns the actual file name of the application on disk, whereas DDE always uses the original name that was specified in the Make EXE dialog.)

The item element that the destination application uses, which corresponds to the Name property for the label, picture box, or text box on the source form.

An example of a valid reference from Microsoft Excel to a Visual Basic application acting as a source is:  =VizBasicApplication|FormN!TextBox1.  You would enter this reference for a destination cell in the Microsoft Excel formula bar.

Strings and syntax  While the standard definition for a DDE link includes the application, topic, and item elements, the actual syntax used within applications for a destination link to a source application may vary slightly.  For example, within Microsoft Excel, you use the syntax application|topic!item.  Within Microsoft Word for Windows, you use application topic item (no pipe character or exclamation mark).  Within a Visual Basic application, you use application|topic; the exclamation mark (!) for topic is implicit.

Activating and maintaining data links  To activate the data link set with LinkTopic, set the LinkMode property to the appropriate nonzero value to specify the type of link you want.  As a general rule, you should set LinkMode after you specify LinkTopic.  For a destination control, changing LinkTopic breaks an existing link and terminates the DDE conversation.  For a source form, changing LinkTopic breaks all destination links that are using that topic.  For these reasons, you should always set the LinkMode property to 0 before changing LinkTopic.  After changing LinkTopic for a destination control, you must set LinkMode to 1 (Automatic), 2 (Manual), or 3 (Notify) to establish a conversation with the new topic.

Note	Setting a permanent data link at design time with the Paste Link command from the Edit menu also sets the LinkMode, LinkTopic, and LinkItem properties.  This creates a link that is saved with the form.  Each time the form is loaded, Visual Basic attempts to reestablish the conversation.

Data Type

String


See Also

Help:

Creating a DDE Source or Destination Link

LinkClose Event

LinkError Event

LinkItem Property

LinkMode Property

LinkOpen Event

LinkSend Method

Using DDE

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


LinkItem, LInkMode, LinkTopic Properties Example

In the example, each mouse click causes a cell in a Microsoft Excel worksheet to update the contents of a Visual Basic text box.  To try this example, start Microsoft Excel, open a new worksheet named Sheet1, and put some data in the first column.  Then in Visual Basic, create a form with a text box.  Paste the code into the Declarations section and press F5 to run the program.

Sub Form_Click ()

Dim CurRow As String

Static Row	' Worksheet row number.

Row = Row + 1	' Increment Row.

If Row = 1 Then	' First time only.

' Make sure the link is not active.

Text1.LinkMode = 0

' Set the application name and topic name.

Text1.LinkTopic = "Excel|Sheet1"

Text1.LinkItem = "R1C1"	' Set the LinkItem.

Text1.LinkMode = 1	' Activate the link to 	' Automatic.

Else

' Update the Row in the data item.

CurRow = "R" & Row & "C1"

Text1.LinkItem = CurRow	' Set the LinkItem.

End If

End Sub


LinkClose Event

See Also

Applies To

Form, MDI Form, label, picture box, text box.

Description

Occurs when a DDE conversation terminates.  Either application in a DDE conversation may terminate a conversation at any time.

Syntax

Sub {Form|MDIForm}_LinkClose ( )

Sub ctlname_LinkClose (Index As Integer)

Remarks

The argument Index uniquely identifies a control if it is in a control array.  Typically, you use a LinkClose procedure to notify the user that a DDE conversation has been terminated.  You might also include troubleshooting information on reestablishing a connection or where to go for assistance.  For brief messages, use the MsgBox function or statement.


See Also

Help:

LinkError Event

LinkExecute Event

LinkExecute Method

LinkMode Property

LinkNotify Event

LinkOpen Event

LinkTopic Property

Using DDE

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


LinkError Event

See Also	Example

Applies To

Form, MDI Form, label, picture box, text box.

Description

Occurs when there is an error during a DDE conversation.  This event is recognized only as the result of a DDE-related error that occurs when no Visual Basic code is being executed.  The error number is passed as an argument.

Syntax

Sub {Form|MDIForm}_LinkError (LinkErr As Integer)

Sub ctlname_LinkError ([Index As Integer,]LinkErr As Integer)

Remarks

The LinkError event uses these arguments:

Argument	Description

Index	Uniquely identifies a control if it is in a control array.

LinkErr	The error number.

Use a LinkError procedure to notify the user of the particular error that has occurred.  You might also include code to fix the problem, or troubleshooting information on reestablishing a connection or on where to go for assistance.  For brief messages, use the MsgBox function and MsgBox statement.

The following table lists all error numbers returned for the LinkErr argument and a brief explanation of each error.

Error number	Explanation

1	The other application has requested data in the wrong format.  This error may occur several times in succession as Visual Basic tries to find a format the other application recognizes.

6	The destination application attempted to continue performing DDE after you set the LinkMode on your source form to 0 (None).

7	All the source links are in use (there is a limit of 128 links per source).

8	For destination controls: an automatic link or LinkRequest method failed to update the data in the control.

For source forms: the destination attempted to poke data to a control and the attempt failed.

11	Not enough memory for DDE.

The missing numbers in this table correspond to error values that were supported in Visual Basic 1.0 but no longer occur in more recent versions of Visual Basic.


See Also

Help:

LinkClose Event

LinkExecute Event

LinkExecute Method

LinkItem Property

LinkMode Property

LinkNotify Event

LinkOpen Event

LinkTopic Property

Using DDE

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


LinkError Event Example

The example is attached to a text box control, MyTextBox, which handles selected errors.  The procedure displays a message (adapted from the error list in the LinkError Event topic), based on the error number passed as the argument LinkErr.  Note that you can adapt this code to a source form by substituting Form_LinkError for MyTextBox_LinkError.  This example is for illustration only.

Sub MyTextBox_LinkError (LinkErr As Integer)

Dim Msg

Select Case LinkErr

Case 1

Msg = "Data in wrong format."

Case 11

Msg = "Out of memory for DDE."

End Select

MsgBox Msg, 48, "MyTextBox"

End Sub


LinkExecute Event

See Also	Example

Applies To

Form, MDI Form.

Description

Occurs when a command string is sent by a destination application in a DDE conversation. The destination application expects the source application to perform the operation described by the string.

Syntax

Sub {Form|MDIForm}_LinkExecute (CmdStr As String, Cancel As Integer)

Remarks

The LinkExecute event uses these arguments:

Argument	Description

CmdStr	The command string sent by the destination application.

Cancel	This argument's value at the end of the LinkExecute event procedure tells the destination whether the command string was accepted or refused.  Setting Cancel = 0 informs the destination that the command string was accepted.  Setting Cancel to any nonzero value informs the destination that the command string was rejected.  (The default is set to -1, indicating Cancel.)

There is no required syntax for CmdStr.  How your application responds to different strings is completely up to you.

If you have not created a LinkExecute event procedure, Visual Basic rejects command strings from destination applications.


See Also

Help:

Attaching an Event Procedure to a Form or Control

LinkClose Event

LinkError Event

LinkExecute Method

LinkMode Property

LinkNotify Event

LinkOpen Event

LinkTopic Property

Using DDE

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


LinkExecute Event Example

The example defines a set of commands for destinations to use in DDE conversations to which your application will respond.  This example is for illustration only.

Sub Form_LinkExecute (CmdStr As String, Cancel As Integer)

Cancel = False

Select Case LCase(cmdStr)

Case "{big}"

WindowState = 2	' Maximize window.

Case "{little}"

WindowState = 1	' Minimize window.

Case "{hide}"

Visible = False	' Hide form.

Case "{view}"

Visible = True	' Display form.

Case Else

Cancel = True	' Execute not allowed.

End Select

End Sub


LinkNotify Event

See Also	Example

Applies To

Label, picture box, text box.

Description

Occurs when the source has changed the data defined by the DDE link, if the LinkMode property of the destination control is set to 3 (Notify).

Syntax

Sub ctlname_LinkNotify (Index As Integer)

Remarks

The argument Index uniquely identifies a control if it is in a control array.  Typically, in the LinkNotify event your code notifies the user, gets the new data immediately, or defers getting the data until later.  You can use the LinkRequest method to obtain the new data from the source.


See Also

Help:

Attaching an Event Procedure to a Form or Control

LinkClose Event

LinkError Event

LinkExecute Method

LinkMode Property

LinkOpen Event

LinkRequest Method

LinkTopic Property

Using DDE

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


LinkNotify Event Example

The example is attached to a picture box control, Picture1, which has its LinkMode property set to 3 (Notify) and its LinkTopic and LinkItem properties set to specify picture data in the source.  When the source changes this data, the procedure updates the picture box immediately only if the picture box is on the active form (the form that has the focus); otherwise it sets a flag variable.  The example is for illustration only.

Sub Picture1_LinkNotify ()

If Screen.ActiveForm Is Me Then

Picture1.LinkRequest	' Picture is on active form, so update.

Else

NewDataFlag = True	' Assumed to be a module-level variable.

End If

End Sub


LinkOpen Event

See Also

Applies To

Form, MDI Form, label, picture box, text box.

Description

Occurs when a DDE conversation is being initiated.

Syntax

Sub {Form|MDIForm}_LinkOpen (Cancel As Integer)

Sub ctlname_LinkOpen ([Index As Integer,]Cancel As Integer)

Remarks

The LinkOpen event uses these arguments:

Argument	Description

Index	Uniquely identifies a control if it is in a control array.

Cancel	When the LinkOpen event procedure ends, the value of this argument determines whether the DDE conversation is established or not.  Leaving Cancel = 0 establishes the conversation.  Setting Cancel to any nonzero value refuses the conversation.

This event occurs for forms when a destination application is initiating a DDE conversation with the form.  It occurs for controls when a control is initiating a DDE conversation with a source application.


See Also

Help:

LinkClose Event

LinkError Event

LinkExecute Event

LinkExecute Method

LinkMode Property

LinkNotify Event

LinkTopic Property

Using DDE

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


access key

A key pressed while holding down the Alt key that enables the user to open a menu, carry out a command, select a control, or move to a control.


active window

The window that appears in the foreground with a highlighted title bar or border to distinguish it from other visible windows.


assignment statement

A statement such as Text1.Text = "My Name" that assigns a value to a variable or to a property.


binary format

Encoded in a machine-readable format.  Different from ASCII or ANSI formats, which encode data as text.


bit

The smallest unit of data a computer can store.  Bits are expressed as 1 or 0.


bit field

A value in which each bit represents a state or condition.  1 indicates the state or condition is on and 0 indicates it is off.


bit mask

A value used with bit-wise operators (And, Eqv, Imp, Not, Or, Xor) to test, set, or reset the state of individual bits in a bit-field value.


bitmap

A graphic object stored as a collection of bits; a map of the display pixels that make up a picture.  Each pixel is represented by single or many bits.


Cancel button

A button you click to cancel changes.  This is also the generic term for any command button on a form that has the Cancel property set to True, allowing you to press Esc or to click the button to cancel changes on that form.


Caption

The property you set to specify the text displayed on a control or form.


check box

A control used to represent an option (on/off, true/false) you can set by selecting or clearing.  An X in a check box indicates it is selected.


client

In an active link of a dynamic data exchange (DDE) conversation, refers to an application, form, or control that requests data from another application acting as a server.  Note the terms "client" and "server" have been replaced in DDE terminology with the terms "destination" and "source."


combo box

A control, similar to a text box and a list box combined, in which the user can either enter a value or select from a list of options.


container

A parent object that contains child forms or controls.


control

An object that has a set of properties and one or more events it recognizes that you can place on a form.  You use controls to get user input, display output, and to trigger event procedures.  You can manipulate most controls using methods.  Some controls are interactive (responsive to user actions), while others are static (accessible only through code).


Control-menu box

Opens the Control menu, which displays commands that enable you to move or resize the title bar, to switch to other Windows-based applications, or to close the current application.


Control-menu commands

Commands that enable you to move or resize the title bar, to switch to other Windows-based applications, or to close the current application.


constant

A value that cannot change during program execution, including literal numbers, strings, and symbolic constants defined with the Const statement.


control array

A group of controls of the same type that share a common name, type, and event procedures.  Each constituent control has a unique index number.  When a control in the array recognizes an event, it calls the event procedure for the group and passes the index as an additional argument, allowing your code to determine which control recognized the event.


Control Panel

A program built into Microsoft Windows that controls your system configuration.  Through the Control Panel, you can adjust various hardware and software options such as desktop colors and patterns, printers, date and number formats, and fonts for printers and monitors.


cross hair

A cross-shaped pointer displayed when you select a control from the Toolbox and move the mouse over a form.  In the MousePointer property, this pointer is called "Cross."


custom control

A DLL file having the extension .VBX which, when loaded into Visual Basic, extends the Toolbox by adding extra controls.


DDE

Dynamic data exchange [image] an established protocol for exchanging data through active links between applications that run under Microsoft Windows.


declaration

Definition of a constant, variable, or user-defined type, that specifies the name and data type; for DLL procedures, specifies the name, library, and arguments.


design time

Any time when you're building an application in the design environment [image] creating controls, setting control or form properties, writing code, and so on.  In contrast, during run time, you run and interact with the application as if you were a user.


device context

A link between a Windows-based application, a device driver, and an output device such as a display, printer, or plotter.


dialog box

A type of form you can create in a Form window.  A dialog box can either request information the application needs or provide extra information to the user.  Normally, dialog boxes are shown modally.


DLL

Dynamic-link library [image] a library of routines loaded and linked into applications at run time.  DLLs include utility routines for standard application tasks such as retrieving configuration information, managing memory, and handling user actions.  Custom controls are DLLs used to add controls.  Other DLLs may provide specific functions not intrinsic to Microsoft Windows.


drag-and-drop operation

Features that enable the user to drag a control and drop it onto a form or another control using the mouse.  An object can be a source (an item the user drags) or a target (an item on which the user drops a source).


editing key

The Insert, Delete, or Backspace key.


Enter button

A button next to the Settings box in the Properties window that you click to save changes in a property setting.


enumerated data type

A data type simulated with the Integer data type that applies to certain form and control properties.


executable file

A Windows-based application that can run outside the development environment.


focus

In the Microsoft Windows environment, only one window, form, or control can receive mouse clicks or keyboard input.  This object "has the focus."  The focus can be set by the user or by the application.  Focus is usually indicated by a highlighted caption or border.


form

A window or dialog box.  Forms are containers for controls.  An MDI form can also be a container for child forms and some controls.


form code

All the procedures and declarations saved in the same file as a form and its controls.  Procedures in a form file are callable only from within that file.


frame

A rectangular control.  Provides a graphical and functional grouping for controls.


function key

Any of the keys labeled F1 through F16.  Function keys often handle shortcuts for frequently carried out commands and actions.  You can assign a function key as a shortcut key.


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.


general procedure

A procedure that must be explicitly called by another procedure, unlike an event procedure, which remains idle until invoked in response to events caused by the user or program code or that were triggered by the system.


graphics method

A method that operates on a form, picture box, or the Printer object and performs run-time drawing operations, including animation or simulation.  The graphics methods are Circle, Cls, Line, Point, Print, and PSet.


grid

The dots or points, measured in pixels, on the Form window when you're in design mode.  Using this grid ensures that controls are positioned uniformly.


handle

A unique integer value used to identify and access a window, form, or control.


hierarchical menu

A menu that contains at least one level of submenus.


horizontal scroll bar

A control consisting of a horizontal bar, two scroll arrows, and a small box to enable various scrolling methods.  Primarily used as a graphical tool for quickly navigating through a long list of items or a large amount of information, and for indicating the current position on a scale.  Can also be used as an input device or an indicator of speed or quantity.


icon

A graphic representation of an object or concept; commonly used to represent minimized applications in Microsoft Windows .  Essentially a bitmap (an image made up of pixels on the screen) with a maximum size of 32 x 32.


index

A number that identifies an element in an array, control array, or a collection.


keyboard modifier

Refers to the Shift, Ctrl, or Alt key.  One or more of these keys are often combined with another keyboard command to modify the action carried out by that command.


keyword

A symbol recognized as part of the programming language [image] for example, a statement or function name, operator, or method.


label

A control that contains text the user cannot directly change during run time.


list box

A control that displays a list of choices.


Long data type

A four-byte integer (whole number between -2,147,483,648 and 2,147483,647, inclusive).


Maximize button

A button in the upper-right corner that enlarges a window to fill the entire screen.


metafile

A file that stores an image in terms of graphical objects (lines, circles, polygons) rather than pixels.  When resized, a metafile tends to preserve an image better than a bitmap does.


millisecond

One one-thousandth of a second.


Minimize button

A button in the upper-right corner that shrinks a window to an icon.


modal

A type of window or dialog box that requires the user to take some action before the focus can switch to another form or dialog box.


modeless

Describes a window or dialog box that does not require user action before the focus can switch to another form or dialog box.  The Code window is an example of a modeless window.


navigation key

A key used for moving and selecting, such as the Home, End, PageUp, PageDown, Up Arrow, Down Arrow, Right Arrow, Left Arrow, and Tab keys.


object

In Visual Basic, a term that refers to forms, controls, and the App, Clipboard, Debug, Printer, and Screen objects.


Object box

  A list box located at the upper-left corner of the Code window that lists forms and controls in the form to which the code is attached.  Also, a list box located at the top of the Properties window that lists the form and its controls.


OLE

Object linking and embedding [image] the process of creating applications that contain components from various other source applications.


option button

A control used to display an option or, more typically, a group of related options from which you can select only one.


Paste Link command

A command that inserts Clipboard contents copied from another Windows-based application.  It also creates a link with that application to update the copied data automatically.


path

A designation for the location of files or directories on your disk.  For example, C:\VB\ICONS is the path to the \ICONS subdirectory of the \VB directory on drive C.


pen

The color specified by a Line, Point, or Circle statement, or by the current ForeColor or FillColor setting.


persistent bitmap

A bitmap, accessed with the Image property, that stores output from graphics methods (Circle, Line, Point, Print, and PSet) in memory.  This output, or "persistent graphics," is redrawn when certain kinds of screen events occur [image] for example, when a form is redisplayed after being hidden behind another window.


picture box

A control that can contain a graphical image (bitmap, icon, or metafile), other controls, or can serve as a drawing area for graphics methods.  Can also be a container for other controls, can be used to group controls such as to create an option button grouping, or create a toolbar on a form.


pixel

An abbreviation for picture element; a dot that represents the smallest graphic unit of measurement on a screen.  A pixel is a screen-dependent unit:  the dimensions of screen elements vary with the display system and resolution used.  By contrast, the twip is a screen-independent unit of measure.


poke

To modify data in a source application without the source application's explicit permission, as in the LinkPoke DDE method.


point

In typesetting, a point is 1/72 inch.  The height of fonts is usually expressed in points.


Printer object

A drawing object you use in code to determine how text and graphics are printed on a page and to send output directly to a printer.


procedure call

Tells Visual Basic to execute a procedure.


procedure template

The beginning and end statements that are automatically provided when you specify a Sub procedure, Function procedure, or event procedure in the Code window.


project

A collection of forms, modules, and custom controls that make up an application.


Project window

A window that displays a list of all the forms and modules in your project or application.


Property list

A two-column list in the Properties window that shows all properties and their current settings for the selected object.


Properties window

A window used to display or change the design-time properties of a selected form or control.


relational operators

Symbol	Description

<	Less than

<=	Less than or equal to

>	Greater than

>=	Greater than or equal to

<>	Not equal

=	Equal


reserved word

A keyword that can only be used in conformity with its syntax; it includes predefined statements, methods, functions, and operators.


Restore button

A button in the upper-right corner of a maximized window that returns the window to its original size.


scoping

The parts of a program in which a symbol or object exists or is visible.  Depending on where it is declared, a variable or constant may have lifetime or visibility only in a specific form, module, or procedure.


separator bar

A bar that divides commands into logical groups on a menu.


Settings box

A text box in the top of the Properties window in which you select, modify, or enter property settings.


shortcut key

A function key or key combination (such as F5 or Ctrl+C) that carries out a command.


String data type

Data comprising a sequence of contiguous characters, including letters, numerals, spaces, and punctuation marks.


submenu

A menu that is opened from another menu.  It displays its own list of commands.


Sub procedure

A procedure that performs a specific task within a program but returns no value.  A Sub procedure begins with a Sub statement and ends with an End Sub statement.


syntax

The way that programming language elements must be used in executable statements.


tab order

The order (as set by the TabIndex property) in which the focus moves between controls on a form as the user presses the Tab or Shift+Tab key.


text file

A file that is meant to contain only ASCII text.


Windows API

API is an acronym for Application Programming Interface.  Consists of the functions, messages, data structures, data types, and statements you can use in creating applications that run under Microsoft Windows.  The parts of the API you use most are code elements included for calling API functions from Windows.  This includes procedure declarations (for the Windows functions), user-defined type definitions (for data structures passed to those functions), and constant declarations (for values passed to and returned from those functions).


three-dot button

A button in the Properties window that opens a dialog box in which you select or enter settings for certain properties.


Shortcut box

A drop-down list box in the Menu Design window from which you select a shortcut key for a menu item.


default color box

A box in the Color palette that displays the currently selected foreground and background colors for the form or control.


Checked check box

A check box in the Menu Design window that you select to have a check mark appear at the left of a menu item whenever the user selects that item.


Enabled check box

A check box in the Menu Design window that you select if you want the menu item to respond to events or to be unavailable and appear dimmed.


Visible check box

A check box in the Menu Design window that you select if you want the menu item to appear on the menu.


client area

The area in an MDI form which is used to display MDI child forms.  The client area does not include the MDI form's title bar, border, menu bar, or aligned controls placed in the MDI form.


compile time

The point at which a program is compiled.  Compile errors are caused by programming mistakes such as misspelled words, missing separators, or for example, a Next statement used without a corresponding For statement.


data type

The characteristic of a variable that determines its attributes and the kind of data it can hold.  Fundamental data types include Variant (the default), Integer, Long, Single, Double, Currency, and String.  You can combine fundamental data types into user-defined types using the Type statement.  You can create arrays of fundamental or user-defined types using the Dim statement.  You can include both arrays and user-defined types within other user-defined types.


destination

When two or more programs that support dynamic data exchange (DDE) are running simultaneously, the program designated to receive the information and commands is the destination.


position indicator

An indicator that shows the position of the selected form or control relative to its container.  For forms, position is always shown in twips.  For controls, position is shown in the units of measure specified in the ScaleMode property of the container.


size indicator

The indicator that shows the size of a selected form or control.  For forms, size is always shown in twips.  For controls, size is shown in the units of measure specified in the ScaleMode property of the container.


image control

A graphical control you can use to display a picture.


instance

Any one of a set of objects sharing the same type.  For example, multiple instances of a form type share the same code and are loaded with the same controls with which the form type was designed.  During run time, the individual properties of controls on each form instance can be set to different values.


MDI child

In a multiple-document interface (MDI) application, the forms contained within the MDI form are child forms.


MDI form

A window making up the background of a multiple-document interface (MDI) application.  The MDI form is used as the container for any MDI child forms in the application.


object data type

Object types include the generic types Form and Control, and specific types MDIForm, user-defined form types, and standard and custom-control types.  A user-defined form type corresponds to its Name property.  A custom-control type corresponds to its class name.  The standard control types include CheckBox, ComboBox, CommandButton, DirListBox, DriveListBox, FileListBox, Frame, HScrollBar, Image, Label, Line, ListBox, OptionButton, PictureBox, Shape, TextBox, Timer, and VScrollBar.  The grid and OLE custom controls have the types Grid and OLE, respectively.  Object-type specifications are keywords but not reserved words.


system modal

Describes a window or dialog box that requires the user to take some action.  This term means the same as "modal" except that the focus cannot switch to any other form or dialog in any running applications.


valid date separators

Characters used to separate the day, month, and year when date values are formatted.  The characters are specified by settings in the International section of the Control Panel or by the Format, Format& functions.


VarType

The VarType function returns a value that provides information about the type of data stored in a Variant.

Symbolic constant	Value	Meaning
V_EMPTY	0	Empty
V_NULL	1	Null
V_INTEGER	2	Integer
V_LONG	3	Long
V_SINGLE	4	Single
V_DOUBLE	5	Double
V_CURRENCY	6	Currency
V_DATE	7	Date
V_STRING	8	String


variable naming

A variable is a location in memory containing a value that can change as an application runs.  Each variable has a unique name that identifies it within its level of scope.  Variable names must be limited to 40 characters, must begin with an alpha character, cannot contain an embedded period, and cannot be the same as a procedure name in scope.


Variant data type

A special data type that can contain numeric, string, or date data as well as the special values Empty and Null.  The VarType function defines how the data in a Variant is treated.


Change Event

See Also	Example

Applies To

Combo box, directory list box, drive list box, horizontal scroll bar, label, picture box, text box, vertical scroll bar.

Description

Indicates that the contents of a control have changed.  How and when this event occurs varies with the control:

Combo box [image] changes the text in the text box portion of the control.  Occurs only if the Style property is 0 (Dropdown Combo) or 1 (Simple Combo) and the user changes the text or you change the Text property from code.

Directory list box [image] changes the selected directory.  Occurs when the user double-clicks a new directory or when you change the Path property from code.

Drive list box [image] changes the selected drive.  Occurs when the user selects a new drive or when you change the Drive property from code.

Horizontal and vertical scroll bar [image] moves the scroll box portion of the scroll bar.  Occurs when the user scrolls or when you change the Value property from code.

Label [image] changes the contents of the label.  Occurs when a DDE link updates data or when you change the Caption property from code.

Picture box [image] changes the contents of the picture box.  Occurs when a DDE link updates data or when you change the Picture property from code.

Text box [image] changes the contents of the text box.  Occurs when the user changes the text or when you change the Text property from code.

Syntax

Sub ctlname_Change (Index As Integer)

Remarks

The argument Index uniquely identifies a control if it is in a control array.  A Change procedure can synchronize or coordinate data display among controls.  For example, you can use a scroll bar's Change procedure to update the scroll bar's Value property setting in a text box.  Or you might use a Change procedure to display data and formulas in a work area and results in another area.

Change procedures are also useful for updating properties in file-system controls.  For example, you can update the Path property for a directory list box to reflect a change in a drive list box's Drive property.

Note	A Change procedure can sometimes cause a cascading event.  This occurs when the control's Change event alters the control's contents [image] for example, by setting a property in code that determines the control's value, such as the Text property setting for a text box.  To prevent a cascading event:

If possible, avoid writing a Change procedure for a control that alters the control's contents.  If you do write such a procedure, be sure to set a flag variable that blocks out further changes while the current change is in progress.

Avoid creating two or more controls whose Change procedures affect each other [image] for example, two text boxes that update each other.

Also avoid using a MsgBox function or statement in this event for horizontal or vertical scroll bars.


See Also

Help:

KeyDown, KeyUp Events

KeyPress Event

LinkTopic Property

LostFocus Event

PathChange Event

PatternChange Event

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Change Event Example

The example displays the numeric setting of a horizontal scroll bar's Value property in a text box. To try this example, create a form with a text box and a horizontal scroll bar (set Min = 0, Max = 1000, LargeChange = 100, and SmallChange = 1).  To try this example, paste the code into the Declarations section of a form that contains a horizontal scroll bar and a text box.  Then press F5 and click the horizontal scroll bar.

Sub Form_Load ()

HScroll1.Min = 0	' Set Minimum.

HScroll1.Max = 1000	' Set Maximum.

HScroll1.LargeChange = 100	' Set LargeChange.

HScroll1.SmallChange = 1	' Set SmallChange.

End Sub

Sub HScroll1_Change ()

Text1.Text = HScroll1.Value

End Sub


Click Event

See Also	Example

Applies To

Form (not MDI form), check box, combo box, command button, directory list box, file list box, frame, grid, image, label, list box, menu, OLE control, option button, picture box, text box.

Description

Occurs when the user presses and then releases a mouse button over an object.  It may also occur when the value of a control is changed.

For a form, this event occurs when the user clicks either a blank area or a disabled control.  For a control, this event occurs when the user:

Clicks a control with the left or right mouse button.  With a check box, command button or option button the Click event only occurs when the user clicks the left mouse button.

Selects an item in a combo box or list box, either by pressing the arrow keys or by clicking the mouse button.

Presses the Spacebar when a command button, option button, or check box has the focus,

Presses Enter when a form has a command button with its Default property set to True.

Presses Esc when a form has a Cancel button [image] a command button with its Cancel property set to True.

Presses an access key combination for a control.  For example, if the caption of a command button is "&Go", then pressing Alt+G triggers the event.

You can also trigger the Click event in code by:

Setting a command button's Value property to True.

Setting an option button's Value property to True.

Changing a check box's Value property setting.

Syntax

Sub Form_Click ( )

Sub ctlname_Click (Index As Integer)

Remarks

The argument Index uniquely identifies a control if it is in a control array.  Typically, you attach a Click procedure to a command button, menu, or picture box to carry out commands and command-like actions.  For the other applicable controls, use this event to trigger actions in response to a change in the control.

You can use a control's Value property to test for the state of the control from code.  When a Click event is generated for a file list box, list box, label, or picture box, Visual Basic also calls the related events in this order:  MouseDown, MouseUp, Click.  When you're attaching procedures for these related events, be sure that their actions don't conflict.

Note	To distinguish between the left, right, and middle mouse buttons, use the MouseDown and MouseUp events.


See Also

Help:

Cancel Property

DblClick Event

Default Property

Mousedown, MouseUp Events

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"


Click Event Example

In this example, each time a picture box is clicked it moves diagonally across a form.  To try this example, paste the code into the Declarations section of a form that contains a picture box positioned at the lower left corner of the form.  Then press F5 and click the picture box.

Sub Picture1_Click ()

Picture1.Move Picture1.Left + 750, Picture1.Top - 550

End Sub


DblClick Event

See Also	Example

Applies To

Form (not MDI form), combo box, file list box, frame, grid, image, label, list box, OLE control, option button, picture box, text box.

Description

Occurs when the user presses and releases a mouse button and then presses and released it again over an object.

For a form, the DblClick event occurs when the user double-clicks a disabled control or a blank area of a form.  For a control, it occurs when the user:

Double-clicks a control with the left mouse button.

Double-clicks an item in a combo box whose Style property = 1 (Simple); in a file list box; or in a list box.

Syntax

Sub Form_DblClick ( )

Sub ctlname_DblClick (Index As Integer)

Remarks

The argument Index uniquely identifies a control if it is in a control array.  You can use a DblClick event procedure for an "implied action" such as double-clicking an icon to open a window or document.  This type of procedure is also useful for carrying out multiple steps with a single action, such as double-clicking to select an item in a list box and to close the dialog box.

To produce such shortcut effects in Visual Basic, you can use a DblClick procedure for a list box or file list box in tandem with a default button [image] a command button with its Default property set to True.  As part of the DblClick procedure for the list box, you simply call the default button's Click procedure.

For those objects that receive mouse events, the events occur in this order: MouseDown, Click, MouseUp, and DblClick.

If DblClick does not occur within the system's double-click time limit, the object recognizes another Click event.  The double-click time limit may vary because the user can set the double-click speed with the Control Panel.  When you are attaching procedures for these related events, be sure that their actions don't conflict.  Controls that do not receive DblClick events may receive two clicks instead of a DblClick.

Note	To distinguish between the left, right, and middle mouse buttons, use the MouseDown and MouseUp events.


See Also

Help

Click Event

MouseDown, MouseUp Events

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"


DblClick Event Example

The example displays a selected list item in a text box when either a command button is clicked or a list item is double-clicked.  To try this example, paste the code into the Declarations section of a form that contains list box, a text box and a command button.  Then press F5 and click the command button or double click a list box item.

Sub Form_Load ()

List1.AddItem "John"	' Add list box entries.

List1.AddItem "Paul"

List1.AddItem "George"

List1.AddItem "Ringo"

End Sub

Sub List1_DblClick ()

Command1.Value = True	' Trigger Click event.

End Sub

Sub Command1_Click ()

Text1.Text = List1.Text	' Display selection.

End Sub


DragDrop Event

See Also	Example

Applies To

Form, MDI form, check box, combo box, command button, data control, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, list box, OLE control, option button, picture box, text box, vertical scroll bar.

Description

Occurs when a drag-and-drop operation is completed as a result of dragging a control over a form or control and releasing the mouse button; or using the Drag method with its action argument = 2 (Drop).

Syntax

Sub Form_DragDrop (Source As Control, X As Single, Y As Single)

Sub MDIForm_DragDrop (Source As Control, X As Single, Y As Single)

Sub ctlname_DragDrop ([Index As Integer,]Source As Control, X As Single, Y As Single)

Remarks

The DragDrop event uses these arguments:

Argument	Description

Index	Uniquely identifies a control if it is in a control array.

Source	The control being dragged.  You can refer to properties and methods with this argument [image] for example, Source.Visible = 0.

X, Y	The current horizontal (X) and vertical (Y) position of the mouse pointer within the target form or control.  These coordinates are always expressed in terms of the target's coordinate system as set by the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties.

Use a DragDrop event procedure to control what happens after a drag operation has been completed.  For example, you can move the source control to a new location or copy a file from one location to another.

When multiple controls can potentially be used in a Source argument:

Use the TypeOf reserved word with the If statement to determine the type of control used with Source.

Use the control's Tag property to identify a control, and then use a DragDrop procedure.

Note	Use the DragMode property and Drag method to specify the way dragging is initiated.  Once dragging has been initiated, you can handle events that precede a DragDrop event with a DragOver procedure.


See Also

Help:

Drag Method

DragIcon Property

DragMode Property

DragOver Event

MouseDown, MouseUp Events

MouseMove Event

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"


DragDrop Event Example

The example demonstrates the visual effect of dropping a picture box onto another picture box.  To try this example, paste the code into the Declarations section of a form that contains three picture box controls.  Set the DragMode property for Picture1 and Picture2 to 1 (Automatic)  Use the Picture property to assign bitmaps to Picture1 and Picture2.  Then press F5 and drag Picture1 or Picture2 over Picture3..

Sub Picture3_DragDrop (Source As Control, X as Single, Y As Single)

If TypeOf Source Is PictureBox Then

' Set Picture3 bitmap to same as source control.

Picture3.Picture = Source.Picture

End If

End Sub


DragOver Event

See Also	Example

Applies To

Form, MDI form, check box, combo box, command button, data control, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, list box, OLE control, option button, picture box, text box, vertical scroll bar.

Description

Occurs when a drag-and-drop operation is in progress.  You can use this event to monitor when the mouse pointer enters, leaves, or is directly over a valid target.  The mouse pointer position determines which target object receives this event.

Syntax

Sub Form_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

Sub MDIForm_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

Sub ctlname_DragOver ([Index As Integer,]Source As Control, X As Single, Y As Single, State As Integer)

Remarks

The DragOver event uses these arguments:

Argument	Description

Index	Uniquely identifies a control if it is in a control array.

Source	The control being dragged.  You can refer to properties and methods with this argument [image] for example, Source.Visible = False.

X, Y	The current horizontal (X) and vertical (Y) position of the mouse pointer within the target form or control.  These coordinates are always expressed in terms of the target's coordinate system as set by the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties.

State	The transition state of the control being dragged in relation to a target form or control:

0 - Enter (source control is being dragged within the range of a target).

1 - Leave (source control is being dragged out of the range of a target).

2 - Over (source control has moved from one position in the target to another).

Use a DragOver event procedure to determine what happens after dragging is initiated and before a control drops onto a target.  For example, you might verify a valid target range by highlighting the target (set the BackColor or ForeColor property from code) or by displaying a special drag pointer (set the DragIcon or MousePointer property from code).

Use the argument State to determine actions at key transition points.  For example, you might highlight a possible target on State 0 (Enter) and restore the object's previous appearance on State 1 (Leave).

When an object receives a DragOver event with State = 0 (Enter):

If the source control is dropped on a valid target, a DragDrop event is generated.

If the source control is not dropped on a valid target, another DragOver event is generated with State = 1 (Leave).

Note	Use the DragMode property and Drag method to specify the way dragging is initiated.  For suggested techniques with the Source argument, see the Remarks for the DragDrop Event topic.


See Also

Help:

Drag Method

DragDrop Event

DragIcon Property

DragMode Property

MouseDown, MouseUp Events

MouseMove Event

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"


DragOver Event Example

The example demonstrates one way to indicate a valid drop target.  The drag pointer changes from the default arrow to a special icon when a text box is dragged over a picture box.  The drag pointer returns to the default when the source is dragged elsewhere.  To try this example, paste the code into the Declarations section of a form that contains a small text box and a picture box.  Set the text box DragMode property to 1.  Then press F5 and drag the text box over the picture box.

Sub Picture1_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

Const ENTER = 0	' Define constants.

Const LEAVE = 1

Select Case State

Case ENTER

' Load icon.

Source.DragIcon = LoadPicture("ICONS\ARROWS\POINT03.ICO")

Case LEAVE

Source.DragIcon = LoadPicture()	' Unload icon.

End Select

End Sub

Sub Picture1_DragDrop (Source As Control, X As Single, Y As Single)

Source.DragIcon = LoadPicture()	' Unload icon.

End Sub


DropDown Event

See Also	Example

Applies To

Combo box.

Description

Occurs when the list portion of a combo box is about to drop down; this event does not occur if a combo box's Style property is set to 1 (Simple Combo).

Syntax

Sub ctlname_DropDown (Index As Integer)

Remarks

The argument Index uniquely identifies a control if it is in a control array.  Use a DropDown procedure to make final updates to a combo box list before the user makes a selection.  This allows you to add or remove items from the list, using the AddItem or RemoveItem methods.  This flexibility is useful when you want some interplay between controls [image] for example, if what you want to load into a combo box list depends on what the user selects in an option button group.


See Also

Help:

Style Property

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"


DropDown Event Example

The example updates a combo box based on the user's selection in an option button group.  To try this example, paste the code into the Declarations section of a form that contains a combo box and two option buttons.  Set the Name property of both option buttons to OptionGroup.  Then press F5 and click the option buttons.  The combo box reflects different carriers depending on the option button selected.

Sub Form_Load ()

Combo1.Text = ""	' Clear combox box.

End Sub

Sub Combo1_DropDown ()

While Combo1.ListCount	' Delete existing items.

Combo1.RemoveItem 0

Wend

If OptionGroup(0).Value = True Then

Combo1.AddItem "Gray Goose Express", 0

Combo1.AddItem "Wild Fargo Carriers", 1

Else

Combo1.AddItem "Pegasus Overnight"

End If

End Sub


GotFocus Event

See Also	Example

Applies To

Form (not MDI form), check box, combo box, command button, directory list box, drive list box, file list box, grid, horizontal scroll bar, list box, OLE control, option button, picture box, text box, vertical scroll bar.

Description

Occurs when an object receives the focus, either by user action such as tabbing to or clicking the object, or by changing the focus in code using the SetFocus method.  Note that a form receives the focus only when all visible controls are disabled.

Syntax

Sub Form_GotFocus ( )

Sub ctlname_GotFocus (Index As Integer)

Remarks

The argument Index uniquely identifies a control if it is in a control array.  Typically, you use a GotFocus procedure to specify the actions that occur when a control or form first receives the focus.  For example, by attaching a GotFocus procedure to each control on a form, you can guide the user by displaying brief instructions or status bar messages.  You can also provide visual cues by enabling, disabling, or showing other controls that depend on the control that has the focus.

Note	An object can receive the focus only if its Enabled and Visible properties are set to True.  To customize Visual Basic's keyboard interface for moving the focus, set the Tab order or specify access keys for controls on a form.


See Also

Help:

ActiveControl Property

ActiveForm Property

LostFocus Event

SetFocus Method

TabIndex Property

TabStop Property


GotFocus Event Example

The example displays a status bar message when a button in an option group gets the focus.  To try this example, paste the code into the Declarations section of a form that contains two option buttons and a label.  Set the Name property for both option buttons to OptionGroup. Then press F5 and click the option buttons.

Sub Form_Load ()

Label1.AutoSize = True

End Sub

Sub OptionGroup_GotFocus (Index As Integer)

Select Case Index

Case 0

Label1.Caption = "Option 1 has the focus."

Case 1

Label1.Caption = "Option 2 has the focus."

End Select

End Sub

Sub OptionGroup_LostFocus (Index As Integer)

Label1.Caption = ""

End Sub


LostFocus Event

See Also	Example

Applies To

Form, check box, combo box, command button, directory list box, drive list box, file list box, grid, horizontal scroll bar, list box, OLE control, option button, picture box, text box, vertical scroll bar.

Description

Occurs when an object loses the focus, either by user action such as tabbing to or clicking another object, or by changing the focus in code using the SetFocus method.

Syntax

Sub Form_LostFocus ( )

Sub ctlname_LostFocus ([Index As Integer])

Remarks

The argument Index uniquely identifies a control if it is in a control array.  A LostFocus procedure is primarily useful for verification and validation updates.  Using LostFocus can cause validation to take place as the user leaves the control.  Another use for this type of procedure is enabling, disabling, hiding, and displaying other objects, as in a GotFocus procedure.  You can also reverse or change conditions that you set up in the object's GotFocus procedure.


See Also

Help:

ActiveControl Property

ActiveForm Property

GotFocus Event

SetFocus Method

TabIndex Property

TabStop Property


LostFocus Event Example

The example changes the color of a text box when it receives or loses the focus (selected with the mouse or Tab key) and displays the appropriate text in the label.  To try this example, paste the code into the Declarations section of a form that contains two text boxes and a label..  Then press F5 and move the focus between Text1 and Text2.

Sub Text1_GotFocus ()

' Show focus in red.

Text1.BackColor = RGB(255, 0, 0)

Label1.Caption = "Text1 has the focus."

End Sub

Sub Text1_LostFocus ()

' Show non-focus in blue.

Text1.BackColor = RGB(0, 0, 255)

Label1.Caption = "Text1 does not have the focus."

End Sub


MouseDown, MouseUp Events

See Also	Example

Apply To

Form (not MDI form), check box, command button, data control, directory list box, file list box, frame, grid, image, label, list box, option button, OLE control, picture box, text box.

Description

Occur when the user presses (MouseDown) or releases (MouseUp) a mouse button.

Syntax

Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)

Sub ctlname_MouseDown ([Index As Integer,]Button As Integer, Shift As Integer, X As Single, Y As Single)

Sub Form_MouseUp (Button As Integer, Shift As Integer, X As Single, Y As Single)

Sub ctlname_MouseUp ([Index As Integer,]Button As Integer, Shift As Integer, X As Single, Y As Single)

Remarks

The MouseDown and MouseUp events use these arguments:

Argument	Description

Index	Uniquely identifies a control if it is in a control array.

Button	The button was pressed (MouseDown) or released (MouseUp) to cause the event.  The Button argument is a bit field with bits corresponding to the left button (bit 0), right button (bit 1), and middle button (bit 2) [image] values 1, 2, and 4, respectively.  Only one of the bits is set, indicating which button caused the event.

Shift	The state of the Shift, Ctrl and Alt keys when the button specified in the Button argument was pressed or released.  A bit is set if the key is down.  The Shift argument is a bit field, with the least-significant bits corresponding to the Shift key (bit 0), the Ctrl key (bit 1), and the Alt key (bit 2 ).  These bits correspond to the values 1, 2, and 4, respectively.  Shift indicates the state of these keys.  Some, all, or none of the bits can be set, indicating that some, all, or none of the keys is pressed.  For example, if both Ctrl and Alt were pressed, the value of Shift would be 6.

X, Y	The current location of the mouse pointer. X and Y are always expressed in terms of the coordinate system set by the ScaleHeight, Scale Width, ScaleLeft, and ScaleTop properties of the object.

Use a MouseDown or MouseUp procedure to specify actions to occur when a given mouse button is pressed or released.  Unlike the Click and DblClick events, MouseDown and MouseUp events allow you to distinguish between the left, right, and middle mouse buttons.  You can also write code for mouse-keyboard combinations that use the Shift, Ctrl, and Alt keyboard modifiers.

The following applies to both Click and DblClick events:

If a mouse button is pressed while the pointer is over a form or control, that object "captures" the mouse and receives all mouse events up to and including the last MouseUp event.  This implies that the X, Y mouse-pointer coordinates given by a mouse event may not always be in the client area of the object that receives them.

If mouse buttons are pressed in succession, the object that captures the mouse after the first press receives all mouse events until all buttons are released.

If you need to test for the Button or Shift arguments, you can declare constants that define the bits within the argument by loading the CONSTANT.TXT file into a module.  These mouse button constants have the following values:

Constant	Value

LEFT_BUTTON	1

RIGHT_BUTTON	2

MIDDLE_BUTTON	4

SHIFT_MASK	1

CTRL_MASK	2

ALT_MASK	4

These constants are in CONSTANT.TXT.  The constants then act as bit masks you can use to test for any combination of buttons without having to figure out the unique bit field value for each combination.

Note	You can use a MouseMove procedure to respond to an event caused by moving the mouse.  The Button argument for MouseDown and MouseUp differs from the Button argument used for MouseMove.  For MouseDown or MouseUp, the Button argument indicates exactly one button per event; for MouseMove, it indicates the current state of all buttons.


See Also

Help:

Click Event

DblClick Event

MouseMove Event

MousePointer Property

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"


MouseDown, MouseUp Events Example

The example demonstrates a simple paint application.  The MouseDown procedure works with a related MouseMove procedure to paint when any mouse button is pressed and dragged.  The MouseUp procedure turns off the paintbrush.  To try this example, paste the code into the Declarations section of a form.  Then press F5, click the form and move the mouse while the mouse button is depressed.

Dim PaintNow As Integer

Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)

PaintNow = True	' Paintbrush on.

End Sub

Sub Form_MouseUp (Button As Integer, Shift As Integer, X As Single, Y As Single)

PaintNow = False	' Turn off painting.

End Sub

Sub Form_MouseMove (Button As Integer, Shift As Integer, X As Single, Y As Single)

If PaintNow Then

PSet (X, Y)	' Draw a point.

End If

End Sub

Sub Form_Load ()

DrawWidth = 10	' Use wider paintbrush.

ForeColor = RGB(0, 0, 255)	' Set drawing color.

End Sub


PathChange Event

See Also	Example

Applies To

File list box.

Description

Occurs when the path changes by setting the FileName or Path properties from code.

Syntax

Sub ctlname_PathChange ([Index As Integer])

Remarks

The argument Index uniquely identifies a control if it is in a control array.  You can use a PathChange procedure to respond to path changes in a file list box.  When you assign a string containing a new path to the FileName property, the file list box control invokes the PathChange event.


See Also

Help:

FileName Property

Path Property

Pattern Property

PatternChange Event

Programmer's Guide:

Chapter 18, "Using the File-System Controls"


PathChange Event Example

The example demonstrates how to update a label control to reflect the current path for a file list box.  Double-clicking a directory name displays a list of that directory's files in the file list box; it also displays the directory's complete path in the label control.  To try this example, paste the code into the Declarations section of a form that contains a label, a directory list box and a file list box.  Then press F5.

Sub File1_PathChange ()

Label1.Caption = "Path: " & Dir1.Path	' Show path in label.

End Sub

Sub Dir1_Change ()

File1.Path = Dir1.Path	' Set file path.

End Sub

Sub Form_Load ()

Label1.Caption = "Path: " & Dir1.Path	' Show path in label.

End Sub


PatternChange Event

See Also	Example

Applies To

File list box.

Description

Occurs when the file listing pattern (such as "*.*") has changed by setting the FileName or Pattern properties from code.

Syntax

Sub ctlname_PatternChange (Index As Integer)

Remarks

The argument Index uniquely identifies a control if it is in a control array.  You can use a PatternChange procedure to respond to pattern changes in a file list box.  When you assign a string containing a new pattern to the FileName property, the file list box invokes the PathChange event.


See Also

Help:

FileName Property

Path Property

PathChange Event

Pattern Property

Programmer's Guide:

Chapter 18, "Using the File-System Controls"


PatternChange Event Example

The example updates a file list box with files matching the pattern typed into a text box.  If a full path is entered into the text box, such as c:\bin\*.exe, the text is automatically parsed into path and pattern components.  To try this example, paste the code into the Declarations section of a form that contains a text box, a label, a file list box, and a command button.  Then press F5 and type a valid file pattern into the text box

Sub Form_Load ()

Command1.Default = True	' Set Default property.

Command1.Caption = "OK"	' Set Caption.

Command1.Default = True	' Set Default.

End Sub

Sub Command1_Click ()	' OK button clicked.

' Text is parsed into path and pattern components.

File1.FileName = Text1.Text

Label1.Caption = "Path: " & File1.Path

End Sub

Sub File1_PatternChange ()

Text1.Text = File1.Pattern	' Set text to new pattern.

End Sub


Timer Event

See Also	Example1	Example2

Applies To

Timer.

Description

Occurs when a preset interval for a timer control has elapsed.  The interval's frequency is stored in the control's Interval property, which specifies the length of time in milliseconds.

Syntax

Sub ctlname_Timer ([Index As Integer])

Remarks

The argument Index uniquely identifies a control if it is in a control array.  Use this procedure to tell Visual Basic what to do at every timer Interval.  When you are working with the Timer event:

The Interval property specifies the interval between Timer events in milliseconds.

Whenever the timer control's Enabled property is set to True and the Interval is greater than zero, the Timer event waits for the period specified in the Interval property.


See Also

Help:

Enabled Property

Interval Property

Timer Function

Programmer's Guide:

Chapter 17, "Interacting with the Environment"


Timer Event Example 1

The example demonstrates a digital clock.  To try this example, paste the code into the Declarations section of a form that contains a label and a timer control.  Then press F5.

Sub Form_Load ()

Timer1.Interval = 1000	' Set timer interval.

End Sub

Sub Timer1_Timer ()

Label1.Caption = Time	' Update time display.

End Sub


Timer Event Example 2

This example moves a picture box across a form.  To try this example, paste the code into the Declarations section of a form that contains a timer and a picture control.  Then press F5.  For a better visual effect you can assign a bitmap to the picture box using the Picture property.

Dim DeltaX, DeltaY As Integer	' Declare variables.

Sub Timer1_Timer ()

Picture1.Move Picture1.Left + Deltax, Picture1.Top + DeltaY

If Picture1.Left < ScaleLeft Then DeltaX = 100

If Picture1.Left + Picture1.Width > ScaleWidth + ScaleLeft Then

DeltaX = -100

End If

If Picture1.Top < ScaleTop Then DeltaY = 100

If Picture1.Top + Picture1.Height > ScaleHeight + ScaleTop Then

DeltaY = -100

End If

End Sub

Sub Form_Load ()

Timer1.Interval = 1000	' Set Interval.

DeltaX = 100	' Initialize variables.

DeltaY = 100

End Sub


Unload Event

See Also	Example

Applies To

Form, MDI Form.

Description

Occurs when a form is about to be removed from the screen.  When that form is reloaded, the contents of all its controls are reinitialized.  This event is triggered by user action (closing the form using the Control-menu box), or by an Unload statement.

Syntax

Sub {Form|MDIForm}_Unload (Cancel As Integer)

Remarks

Setting Cancel to any nonzero value prevents the form from being removed, but does not stop other events such as exiting from Windows.  Use the QueryUnload event to stop exiting from Windows.

Use an Unload event procedure to verify that the unloading of the form should proceed or to specify actions that should take place when the form is unloaded.  You can also include any form-level validation code you might need for closing the form or saving the data in it to a file.

The QueryUnload occurs before the Unload.

The Unload event can be caused by using the Unload statement, or by the user taking an action such as choosing the Close command on a form's Control menu, exiting the application with End Task button on the Windows Task Manager, closing the MDI form for which the current form is a child form, or exiting the Windows environment while the application is running.


See Also

Help:

Load Event

Load Statement

QueryUnload Event

Unload Statement

Programmer's Guide:

Chapter 18, "Using the File-System Controls"


Unload Event Example

The example demonstrates a simple procedure to close a form while querying the user with various message boxes.  In an actual application, you could add calls to general-purpose Sub procedures that emulate the processing of the Exit, Save, and Save As commands on Visual Basic's File menu.  To try this example, paste the code into the Declarations section of a form.  Then press F5.  Once the form is displayed, press Alt + F4 to close the form.

Sub Form_Unload (Cancel As Integer)

Dim Msg, Response	' Declare variables.

Msg = "Save Data before closing?"

Response = MsgBox(Msg, 3 + 32, "Save Dialog")

Select Case Response

Case 2	' Do not allow close.

Cancel = -1

Msg = "Command has been cancelled."

Case 6

' Enter code to save data here.

Msg = "Data saved."'

Case 7

Msg = "Data not saved."

End Select

MsgBox Msg, 0, "Confirm"	' Display message.

End Sub


Activate, Deactivate Events

See Also	Example

Apply To

Form, MDI form.

Description

Activate [image] occurs when a form becomes the active window.

Deactivate [image] occurs before a different form becomes the active window.

Syntax

Sub Form_Activate ( )

Sub MDIForm_Activate ( )

Sub Form_Deactivate ( )

Sub MDIForm_Deactivate ( )

Remarks

A form can become active by user action, such as clicking a form or control, or by using the Show or SetFocus methods in code.

The Activate event can occur only when a form is visible.  For example, a form loaded with the Load statement is not visible unless you use the Show method or set the form's Visible property to True.

The Activate and Deactivate events occur only when moving the focus within an application.  Moving the focus to or from a form in another application does not trigger either event.  The Deactivate event does not occur when unloading a form.

The Activate event occurs before the GotFocus event; the LostFocus event occurs before the Deactivate event.

These events occur for MDI child forms only when the focus changes from one child form to another.  In an MDI form with two child forms, for example, the child forms receive these events when the focus moves between them.  However, when the focus changes between a child form and a non-MDI child form, the parent MDI form gets the Activate and Deactivate events.


See Also

Help:

GotFocus Event

LostFocus Event

SetFocus Method

Show Method

Using MDI Features

Programmer's Guide:

Chapter 14, "Multiple-Document Interface (MDI) Applications"


Activate, Deactivate Events Example

The example updates a status bar with the caption of the active form.  To try this example, create a form (Form1) and a new MDI form (MDIForm1).  On the MDI form, draw a picture box containing a label.  On Form1, set the MDIChild property to True.  Paste the MDIForm_Load event code into the Declarations section of the MDI form.  Paste the Form_Activate event code into the Declarations section of the MDI child form.  Then press F5.

Sub MDIForm_Load ()

Form1.Caption = "Form #1"	' Set caption of Form1.

Dim NewForm As New Form1	' Create a new child form.

Load NewForm

NewForm.Caption = "Form #2"	' Set caption of new form.

NewForm.Show	' Display the new form.

End Sub

Sub Form_Activate ()

' Set status bar text.

MDIForm1.Label1.Caption = "Current form: " & Me.Caption

End Sub


KeyDown, KeyUp Events

See Also	Example

Apply To

Form, check box, combo box, command button, directory list box, drive list box, file list box, grid, horizontal scroll bar, list box, OLE control, option button, picture box, text box, vertical scroll bar.

Description

Occur when the user presses (KeyDown) or releases (KeyUp) a key while an object has the focus.  (To interpret ANSI characters, use the KeyPress event.)

Syntax

Sub Form_KeyDown (KeyCode As Integer, Shift As Integer)

Sub ctlname_KeyDown ([Index As Integer,]KeyCode As Integer, Shift As Integer)

Sub Form_KeyUp (KeyCode As Integer, Shift As Integer)

Sub ctlname_KeyUp ([Index As Integer,]KeyCode As Integer, Shift As Integer)

Remarks

The KeyDown and KeyUp events use these arguments:

Argument	Description

Index	Uniquely identifies a control if it is in a control array.

KeyCode	A key code, such as, KEY_F1 (F1 key) and KEY_HOME (Home key).  To specify key codes, use the constants in CONSTANT.TXT, a Visual Basic file that specifies system defaults.

Shift	The state of the Shift, Ctrl, and Alt keys at the time of the event.  The Shift argument is a bit field, with the least-significant bits corresponding to the Shift key (bit 0), the Ctrl key (bit 1), and the Alt key (bit 2 ).  These bits correspond to the values 1, 2, and 4, respectively.  Some, all, or none of the bits can be set, indicating that some, all, or none of the keys is pressed.  For example, if both Ctrl and Alt are pressed, the value of Shift is 6.

For both events, the object with the focus receives all keystrokes.  A form can have the focus only if it has no visible and enabled controls.  Although KeyDown and KeyUp can apply to most keys, they are most often used for:

Extended character keys such as function keys.

 	Navigation keys.

Combinations of keys with standard keyboard modifiers.

Distinguishing between the numeric keypad and regular number keys.

Use KeyDown and KeyUp event procedures for keyboard handlers if you need to respond to both the pressing and releasing of a key.

KeyDown and KeyUp are not invoked for:

The Enter key if the form has a command button with the Default property set to True.

The Esc key if the form has a command button with the Cancel property set to True.

The Tab key.

If you need to test for the Shift argument, you can declare constants that define the bits within the argument by loading the CONSTANT.TXT file into a module.  The Shift constants have the following values:

Constant	Value

SHIFT_MASK	1

CTRL_MASK	2

ALT_MASK	4

The constants act as bit masks that you can use to test for any combination of buttons.  You can place the constants at the procedure level or in the Declarations section of a module where you can use this syntax:

Global Const Constantname = expression

You test for a condition by first assigning each result to a temporary integer variable and then comparing Shift to a bit mask.  Use the And operator with the Shift argument to test whether the condition is greater than 0, indicating that the modifier was pressed [image] for example:

ShiftDown = (Shift And SHIFT_MASK) > 0

In a procedure, you can test for any combination of conditions [image] for example:

If ShiftDown And CtrlDown Then

Note	If the KeyPreview property is True, a form receives these events before controls on the form receive the events.  Use the KeyPreview property to create global keyboard-handling routines.


See Also

Help:

Keyboard

KeyPreview Property

Operator Precedence

SendKeys Statement

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


KeyDown, KeyUp Events Example

The example demonstrates a generic keyboard handler that responds to the F2 function key and to all the associated Alt, Shift, and Ctrl combinations.  To find the value of the key constants, look at the CONSTANT.TXT file or load it into a module.  To try this example, paste the code into the Declarations section of a form that contains a text box.  Then press F5 and press F2 with the Alt  Shift, and Ctrl keys.

Sub Text1_KeyDown (KeyCode As Integer, Shift As Integer)

Dim ShiftDown, AltDown, CtrlDown, Txt

Const KEY_F2 = &H71	' Define constants.

Const SHIFT_MASK = 1

Const CTRL_MASK = 2

Const ALT_MASK = 4

ShiftDown = (Shift And SHIFT_MASK) > 0

AltDown = (Shift And ALT_MASK) > 0

CtrlDown = (Shift And CTRL_MASK) > 0

If KeyCode = KEY_F2 Then	' Display key combinations.

If ShiftDown And CtrlDown And AltDown Then

Txt = "Shift + Ctrl + Alt F2."

ElseIf ShiftDown And AltDown Then

Txt = "Shift + Alt F2."

ElseIf ShiftDown And CtrlDown Then

Txt = "Shift + Ctrl + F2."

ElseIf CtrlDown And AltDown Then

Txt = "Ctl + Alt + F2."

ElseIf ShiftDown Then

Txt = "Shift F2."

ElseIf CtrlDown Then

Txt = "Ctrl F2."

ElseIf AltDown Then

Txt = "Alt F2."

ElseIf Shift = 0 Then

Txt = "F2."

End If

Text1.Text = "You pressed " & Txt

End If

End Sub


KeyPress Event

See Also	Example

Applies To

Form, check box, combo box, command button, directory list box, drive list box, file list box, grid, horizontal scroll bar, list box, OLE control, option button, picture box, text box, vertical scroll bar.

Description

Occurs when the user presses and releases an ANSI key.

Syntax

Sub Form_KeyPress (KeyAscii As Integer)

Sub control_KeyPress ([Index As Integer,]KeyAscii As Integer)

Remarks

The KeyPress event uses these arguments:

Argument	Description

Index	Uniquely identifies a control if it is in a control array.

KeyAscii	Returns a standard numeric ANSI keycode.  KeyAscii is passed by reference; changing it sends a different character to the object.  Changing KeyAscii to 0 cancels the keystroke so that the object receives no character.

The object with the focus receives the event.  A form can receive the event only if it has no visible and enabled controls, or if the KeyPreview property is True.  A KeyPress event can involve any printable keyboard character, the Ctrl key combined with a character from the standard alphabet or one of a few special characters, and the Enter or Backspace key.  A KeyPress event procedure is useful for intercepting keystrokes entered in a text box or combo box.  It allows you to immediately test keystrokes for validity or to format characters as they are typed.  Changing the value of the argument KeyAscii changes the character displayed.

You can convert the argument KeyAscii into a character by using the expression:

Chr(KeyAscii)

You can then perform string operations and translate the character back to an ANSI number that the control can understand by using the expression:

KeyAscii = Asc(char)

Use KeyDown and KeyUp event procedures to handle any keystroke not recognized by KeyPress, such as function keys, editing keys, navigation keys, and any combinations of these with keyboard modifiers.  Unlike the KeyDown and KeyUp events, KeyPress does not indicate the physical state of the keyboard; instead, it passes a character.

KeyPress interprets the uppercase and lowercase of each character as separate keycodes and, therefore, as two separate characters.  KeyDown and KeyUp interpret the uppercase and lowercase of each character by means of two arguments: KeyCode, which indicates the physical key (thus returning "A" and "a" as the same key); and Shift, which indicates the state of Shift+key and therefore returns either "A" or "a."

If the KeyPreview property is True, a form receives the event before controls on the form receive the event.  Use the KeyPreview property to create global keyboard-handling routines.

Note	The ANSI number for the keyboard combination of Ctrl+@ is 0.  Because Visual Basic recognizes a KeyAscii value of 0 as a null string, you should avoid using Ctrl+@ in your applications.


See Also

Help:

ANSI Table

Asc Function

Change Event

Chr, Chr$ Function

Keyboard

KeyPreview Property

SendKeys Statement

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


KeyPress Event Example

The example converts text entered into a text box to uppercase.  To try this example, paste the code into the Declarations section of a form that contains a text box.  Then press F5 and type something into the text box.

Sub Text1_KeyPress (KeyAscii As Integer)

Char = Chr(KeyAscii)

KeyAscii = Asc(UCase(Char))

End Sub


Load Event

See Also	Example

Applies To

Form, MDI form.

Description

Occurs when a form is loaded.  For a startup form, occurs when an application starts, as the result of a Load statement, or as the result of a reference to an unloaded form's properties or controls.

Syntax

Sub Form_Load ( )

Sub MDIForm_Load ( )

Remarks

Typically, you use a Load event procedure to include initialization code for a form [image] for example, specifying default settings for controls, indicating contents to be loaded into combo boxes or list boxes, and initializing form-level variables.

In code, when you reference a property on an unloaded form, the form is automatically loaded, but is not automatically made visible unless the MDIChild property is True.  If an MDI form is not loaded, and a child form is loaded, both the MDI form and the child form are automatically loaded and both become visible.  Other forms are not shown until you either use the Show method or set the Visible property to True.

The following code in an MDI form Load event automatically loads an MDI child form (assuming Form1 has its MDIChild property set to True):

Dim NewForm As New Form1

NewForm.Caption = "New Form"	' Loads form by reference.

Since all child forms become visible when loaded, the Caption property reference loads the form and makes it visible.

Note	When you create procedures for related events, such as Activate, GotFocus, Paint, and Resize, be sure that their actions don't conflict and that they don't cause recursive events.


See Also

Help:

Load Statement

QueryUnload Event

Unload Event

Unload Statement

Programmer's Guide:

Chapter 14, "Multiple-Document Interface (MDI) Applications"


Load Event Example

The example loads items into a combo box when a form is loaded.  To try this example, paste the code into the Declarations section of a form that contains a combo box.  Then press F5.

Sub Form_Load ()

Combo1.AddItem "Mozart"	' Add items to list.

Combo1.AddItem "Beethoven"

Combo1.AddItem "Rock 'n Roll"

Combo1.AddItem "Reggae"

Combo1.ListIndex = 2	' Set default selection.

End Sub


Paint Event

See Also	Example

Applies To

Form, picture box.

Description

Occurs when part or all of a form or picturebox is exposed after it has been moved or enlarged, or after a window that was covering the object has been moved.

Syntax

Sub Form_Paint ( )

Sub ctlname_Paint ([Index As Integer])

Remarks

The argument Index uniquely identifies a control if it is in a control array.

A Paint procedure is useful if you have output from graphics methods in your code.  With a Paint procedure, you can ensure that such output is repainted when necessary.

If the AutoRedraw property is True, repainting or redrawing is automatic so no Paint events are necessary.  The Paint event is also invoked when the Refresh method is used.

If ClipControls is False, graphics methods in the Paint event procedure affect only newly exposed areas of the form; otherwise, the graphics methods repaint all areas of the form not covered by controls (except image, label, line, and shape controls).

Using a Refresh method in a Resize event procedure forces repainting of the entire object every time a user resizes the form.

Note	Using a Paint event procedure for certain tasks can cause a cascading event.  In general, avoid using a Paint procedure for the following:

Moving or sizing a form or control.

Changing any variables that affect size or visual appearance such as setting an object's BackColor property.

Invoking a Refresh method.

A Resize event procedure may be more appropriate for some of these tasks.


See Also

Help:

AutoRedraw Property

Circle Method

ClipControls Property

Line Method

Print Method

PSet Method

Refresh Method

Resize Event

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Paint Event Example

The example draws a diamond that intersects the center point of each side of a form and adjusts automatically as the form is resized.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and resize the form.

Sub Form_Paint ()

Dim HalfX, HalfY	' Declare variables.

HalfX = ScaleLeft + ScaleWidth / 2	' Set to half of width.

HalfY = ScaleTop + ScaleHeight / 2	' Set to half of height.

' Draw a diamond.

Line (ScaleLeft, HalfY) - (HalfX, ScaleTop)

Line -(ScaleWidth + ScaleLeft, HalfY)

Line -(HalfX, ScaleHeight + ScaleTop)

Line -(ScaleLeft, HalfY)

End Sub

Sub Form_Resize

Refresh

End Sub


QueryUnload Event

See Also	Example

Applies To

Form, MDI form.

Description

Occurs before a form or application closes.  When an MDI form closes, the QueryUnload event occurs first in the MDI form and then in all child forms.  If no form cancels the QueryUnload event, the Unload event then occurs first in all other forms and last in an MDI form.  When a child form or a non-MDI form closes, the QueryUnload event in that form occurs before the form's Unload event.

Syntax

Sub Form_QueryUnload (Cancel As Integer, UnloadMode As Integer)

Sub MDIForm_QueryUnload (Cancel As Integer, UnloadMode As Integer)

Remarks

The QueryUnload event uses the following arguments:

Argument	Description

Cancel	Setting this argument to any value other than zero stops the QueryUnload event in all loaded forms and stops the form and application from closing.

UnloadMode	Indicates the reason for the QueryUnload event.

The UnloadMode argument can have these values:

Value	Description

0	The user has chosen the Close command from the Control-menu box on the form.

1	The Unload method has been invoked from code.

2	The current Windows-environment session is ending.

3	The Microsoft Windows Task Manager is closing the application.

4	An MDI child form is closing because the MDI form is closing.

This event is typically used to make sure there are no unfinished tasks in each form before an application closes.  For example, if a user has not yet saved some new data in any form, your application can ask the user if the data should be saved.

When an application closes, you can use either QueryUnload or Unload event procedures to set Cancel to True, stopping the closing process.  However, the QueryUnload event occurs in all forms before any are unloaded, and the Unload event occurs as each form is unloaded.


See Also

Help:

Unload Event

Unload Statement

Programmer's Guide:

Chapter 14, "Multiple-Document Interface (MDI) Applications"


QueryUnload Event Example

The example uses an MDI form containing two MDI child forms.  When you choose the Close command from the Control-menu box to close a form, you get a different message than if you choose the Exit command from the File menu.  To try this example, create an MDI form and then use the Menu Design window to create a File menu containing an Exit command named FileExit.  On Form1, set the MDIChild property to True.  Paste the code into the Declarations sections of the respective forms and press F5 to run the program.

' Paste into Declarations section of MDIForm1

Sub MDIForm_Load ()

Dim NewForm As New Form1	' New instance of Form1.

NewForm.Caption = "Form2"	' Set caption and show.

End Sub

Sub FileExit_Click ()

Unload MDIForm1	' Exit the application.

End Sub

Sub MDIForm_QueryUnload (Cancel As Integer, UnloadMode As Integer)

Dim Msg	' Declare variable.

' Set the message text.

Msg = "Do you really want to exit the application?"

' If user clicks the 'No' button, stop QueryUnload.

If MsgBox(Msg, 36, Me.Caption) = 7 Then Cancel = True

End Sub

' Paste into Declarations section of Form1

Sub Form_QueryUnload (Cancel As Integer, UnloadMode As Integer)

Dim Msg	' Declare variable.

If UnloadMode > 0 Then

' If exiting the application.

Msg = "Do you really want to exit the application?"

Else

' If just closing the form.

Msg = "Do you really want to close the form?"

End If

' If user clicks the 'No' button, stop QueryUnload.

If MsgBox(Msg, 36, Me.Caption) = 7 Then Cancel = True

End Sub


Scroll Event

See Also	Example

Applies To

Horizontal scroll bar, vertical scroll bar.

Description

Occurs while a user drags the box on a scroll bar.

Syntax

ctlname_Scroll ( )

Remarks

You can use this event to perform calculations or to manipulate controls that must be coordinated with ongoing changes in scroll bars.  In contrast, use the Change event when you want an update to occur only once, after a scroll bar changes.

Note	Avoid using a MsgBox statement or function in this event.


See Also

Help:

Change Event

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Scroll Event Example

The example changes the size of a shape control to correspond to the value of a horizontal scroll bar as you drag the box on the scroll bar.  To try this example, paste the code into the Declarations section of a form that contains a shape control, a label, and a horizontal scroll bar.  Set the Index property for the Shape control to 0 (to create a control array).  Then press F5 and move the scroll bar.

Sub Form_Load ()

' Move and size the first Shape control.

Shape1(0).Move HScroll1.Left, HScroll1.Top * 1.5, HScroll1.Width, HScroll1.Height

Label1.Caption = ""	' Set the Label caption.

Load Shape1(1)	' Create the second Shape.

' Move and size the second Shape control.

Shape1(1).Move Shape1(0).Left, Shape1(0).Top, 1, Shape1(0).Height

Shape1(1).BackStyle = 1	' Set BackStyle to Opaque.

Shape1(1).Visible = True	' Display the second Shape.

HScroll1.Min = 1	' Set Values of the Scroll bar.

HScroll1.Max = HScroll1.Width

End Sub

Sub HScroll1_Change ()

Label1.Caption = "Changed"	' Display message after change.

End Sub

Sub HScroll1_Scroll ()

Shape1(1).BackColor = &HFF0000	' Set Shape color to Blue.

Label1.Caption = "Changing"	' Display message while scrolling.

Shape1(1).Width = HScroll1.Value	' Size Shape to Scroll Value.

End Sub


Displaying or Hiding the Grid

See Also

When you're in design mode, the Form window displays a grid comprised of dots or points, the distance between which is measured in twips.  Use the grid to ensure that controls are positioned uniformly on a form.  You can display or hide the grid.

To display or hide the grid

1.	From the Options menu, choose Environment.

2.	Scroll down to select Show Grid.

3.	In the Setting box, select either Yes or No to display or hide the grid.

4.	Choose OK.


See Also

Help:

Aligning an Item to the Grid

Changing Grid Spacing

Programmer's Guide:

Chapter 5, "Managing Projects"


Changing Grid Spacing

See Also

You can adjust the spacing of the grid points displayed in the active Form window.  You specify grid spacing in pixels.

To change grid spacing

1.	From the Options menu, choose Environment.

2.	Scroll down and select Grid Width.  In the Setting box, type the width you want between horizontal points.

3.	Click the Enter button to accept the edit, or click the Cancel button to cancel the edit.

4.	Select Grid Height.  In the Setting box, type the height you want between vertical points.

5.	Click the Enter button to accept the edit, or click the Cancel button to cancel the edit.

6.	Choose OK.


See Also

Help:

Aligning an Item to the Grid

Displaying or Hiding the Grid

Programmer's Guide:

Chapter 5, "Managing Projects"


Displaying Graphics on a Form

See Also

You can add graphics to forms and controls at design time by setting the Picture property in the Properties window or by copying graphics from other applications and pasting them into Visual Basic.  A graphic can be displayed either as a foreground graphic, using a picture box or image control as the display area for a bitmap, icon, or metafile, or as a background graphic, using the entire Form window as the display area.  You can also add graphics at run time with code.

To add a foreground graphic at design time using the Properties window

1.	Draw a picture box or image control on the form.

2.	In the Properties window, select Picture.

In the Settings box, Visual Basic displays the current type of image and the down arrow to the right of the Settings box changes into a button with three dots.

3.	Click the button with three dots.

Visual Basic displays the Load Picture dialog box.

4.	In the dialog box, select or type the name of the graphic file you want.

5.	Choose OK.

Visual Basic displays the graphic inside the picture box.  If necessary, resize the picture box.

To add a background graphic at design time using the Properties window

1.	Click a blank part of the form to select it.

2.	From the Properties window, select Picture.

3.	Follow steps 3-5 as listed above.

Visual Basic displays the graphic inside the Form window.  If necessary, resize the form.

To add a graphic at design time by copying and pasting

1.	Open the other application and copy the graphic to the Clipboard.

2.	Switch to Visual Basic.

3.	Select the form or control onto which you want to paste the graphic.

4.	From the Edit menu, choose Paste (Ctrl+V).

Note	To delete a graphic at design time, select the Picture property in the Properties window and delete the contents of the Settings box.

Full-screen bitmaps for forms can be memory-intensive.  To save memory, use a picture box or image control to display a foreground graphic.

When using a Picture box, set the AutoSize property to True to automatically resize the control to fit the picture.  When Autosize is set to False, the size of the control remains constant and graphics are clipped when they exceed the area of the control.


See Also

Help:

Drawing Lines and Shapes on a Form

Form

Picture Box Control

Setting Form and Control Properties

Using Icons

Learning Visual Basic:

Using Color and Graphics

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Drawing Lines and Shapes on a Form

See Also

You can use the line control to draw simple lines on forms, and the shape control to draw rectangles (regular or rounded corners), squares (regular or rounded corners), ovals, and circles on forms.  Select each tool in the Toolbox.

To draw a line a form

1.	In the Toolbox, select the line control.

When the pointer moves onto the form, it changes to a cross hair.

2.	Click the form where you want the line to begin and hold down the mouse button.

3.	Drag the cross hair to where you want the line to end and release the mouse button.

4.	From the Properties window, select the BorderStyle property if you want to change the appearance of the line.

5.	In the Settings box, select the style you want.

6.	Click the Enter button to accept the setting.

To draw a shape on a form

1.	In the Toolbox, select the shape control.

When the pointer moves onto the form, it changes to a cross hair.

2.	Click and drag the cross hair to make the item the size you want.

3.	From the Properties window, select the Shape property.

4.	In the Settings box, select the style you want.

5.	Click the Enter button to accept the setting.

Note	To add color, set the BackColor property to the color you want.

To draw lines, rectangles, and filled-in boxes at run time, use the Line method.

To draw circles, ellipses, and arcs at run time, use the Circle method.


See Also

Help:

Displaying a Graphic on a Form

Picture Box Control

Setting Form and Control Properties

Learning Visual Basic:

Using Color and Graphics

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Drawing a Control

See Also

A control is a graphical object drawn with the tools in the Toolbox.  Each control has a set of properties, events, and methods that can be used to add specialized functionality to your application.

To draw a control

1.	In the Toolbox, select the tool you want.

2.	Click the form where you want to place the control.

As you move the pointer onto the form, it changes to a cross hair.

3.	Click and drag the cross hair to make the item the size you want.

Drawing shortcut

In the Toolbox, double-click the tool you want.

The control appears in the center of the form.  Move and resize it as desired for your application.

Note	Option buttons always work as part of a group.  Selection of one button within a container immediately clears all other buttons in the group.  If you want to create more than one option group on a form, draw each set of option buttons inside a frame or picture box.

For details on the properties, events, and methods that pertain to each control, see the individual control topics under Controls.


See Also

Help:

Attaching an Event Procedure to a Form or Control

Creating a Control Array

Setting Form and Control Properties

Learning Visual Basic:

Creating an Application

Working with Forms and Controls

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 3, "Creating and Using Controls"


Creating a Control Array

See Also

A control array is made up of a group of controls of the same type (for example, all list boxes) that share a common control name and a set of event procedures.  Each control in the array has a unique index number.  All items in a control array must have the same setting of the Name property.

To create a control array

1.	Draw the controls for the array.

2.	Select a control you want to include in the array.

3.	From the Properties window, select the Name property.

4.	In the Settings box, type a name for the control.

5.	Choose the Enter button.

6.	Repeat steps 2-5 for each control you want in the array, typing the same name as in step 4.

When you type the same Name for the second control, Visual Basic displays a dialog box asking you to confirm that you want to create a control array.

7.	Choose Yes to create the control array, or choose No to cancel the action.

Note	To remove a control from a control array, change the control's Name property.

When a control in the array recognizes an event, Visual Basic calls an event procedure for the group and passes the index as an additional argument, allowing you to determine which control recognizes the event.

Event procedures for control arrays are defined with the argument "(Index as Integer)."


See Also

Help:

Adding and Deleting Controls at Run Time

Creating a Menu Bar

Creating a Menu Control Array

Index Property (Control Arrays)

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Selecting Controls

See Also

To select a control

In the Form window, click the control you want.

To select multiple controls

1.	In the Form window, click one of the controls you want to select.

2.	With the control selected, press and hold down the Ctrl key, and then click each additional control you want to select.  You can deselect a control in a selection by holding down the Ctrl key and clicking the control.

Or

In the Form window, click and drag a box around the controls you want to select.

Note	To select multiple controls within a container (a frame or picture box), first deselect the container.  Then while pressing the Ctrl key, click and drag a box around the controls that you want to select.

Once you have selected multiple controls, you can change the setting of properties the controls have in common with one change in the Properties window.

To cancel a selection

Click anywhere on the form outside of the selected item.


See Also

Learning Visual Basic:

Working with Forms and Controls

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 3, "Creating and Using Controls"


Aligning an Item to the Grid

See Also

You can automatically or manually align items to the grid as you draw them in the Form window.  In either case, the grid doesn't have to be visible.

To automatically align items to the grid as you draw them

1.	From the Option menu, choose Environment.

2.	Scroll down to select Align To Grid.

3.	In the Setting box, choose Yes.

To manually align an item to the grid

1.	Select the item or items you want to align.

2.	From the Edit menu, choose Align to Grid.


See Also

Help:

Changing Grid Spacing

Displaying or Hiding the Grid


Creating a Menu Bar

See Also

You can use the Menu Design window to create a menu bar that displays the names of menus available to use in the active window.  You can also write code to make your menu respond dynamically to user preferences or run-time conditions, such as whether a menu command should be unavailable, or whether menu commands should be added or deleted.

To create a menu bar

1.	Click the form for which you want to create a menu bar.

2.	From the Window menu, choose Menu Design (Ctrl+M), or use the toolbar shortcut:

3.	In the Caption text box, type the menu item caption as you want it displayed on the menu bar.

To give the user keyboard access to the menu item, type an ampersand (&) before the letter you want to specify as the access key.  At run time, this letter is underlined, and the user can access the menu or command by pressing Alt plus the access key.

To create a separator bar in your menu, type a single hyphen (-) in this box.

4.	In the Name text box, type a control name that you'll use to refer to the menu item in code.  This name can be identical to the caption.

5.	Use the left and right arrows to change the level of a menu item (from a higher level to a lower level or vice versa.)  You can have up to four levels of submenus.

Use the up and down arrows to change the position of a menu item (up or down in the list box.)

Choose Next to move to the next line and add another item to the menu.

Choose Insert to add a line before the currently selected line.

Choose Delete to delete the currently selected line.

6.	Repeat steps 3-5 to add menu items.

7.	Choose OK to accept all the changes and apply them to the selected form.

The menu you created is visible at design time, but no events are generated until you write code.

Optional features for custom menus:

In the Index text box, type a number that determines the control's position within the control array.

To assign a shortcut key to a menu item, select a key from the Shortcut drop-down list.

Select the Window List check box if you want the current menu control to include the name of open MDI child forms.

Enter a unique number in the HelpContextID if you plan to provide a context-sensitive Help topic for the current control.

Select the Checked box if you want a small check mark to appear at the left of a menu item to indicate that the control is turned on or to indicate which of several modes is in effect.

Select the Enabled box if you want the menu item to initially respond to events.  Clear the box if you want the menu item to be unavailable and appear dimmed on the menu.  An initially unavailable item can later be enabled in code.

Select the Visible box if you want the menu item to appear on the menu.

Note	For details on the properties, events, and methods that apply to menus, see the Menu topic.


See Also

Help:

Attaching an Event Procedure to a Form or Control

Creating a Menu Control Array

Specifying Access Keys

Learning Visual Basic:

Adding Menus

Programmer's Guide:

Chapter 4, "Menus and Dialogs"


Creating a Menu Control Array

See Also

A menu control array is made up of one or more menu items that share a common name and event procedures.  Each menu item has a unique index number, but all the items share the same setting of the Name property.  You can designate one or more contiguous menu items at the same menu level as a control array.  This enables you to dynamically add or remove menu items during run time.

To create a menu control array with one menu item

1.	Create the menu item.

2.	In the Index text box, enter a number.

To create a menu control array with more than one menu item

1.	Create a menu item.

2.	In the Index text box, enter a number.  This number determines the menu item's position in the control array.

3.	Create another menu item with the same control name.

4.	In the Index text box, enter a unique number.

5.	Repeat steps 2-4 for each additional menu item.

Note	When a control in the array recognizes an event, Visual Basic calls an event procedure for the group and passes the index as an additional argument, allowing you to determine which control recognizes the event.


See Also

Help:

Adding and Deleting Controls at Run Time

Attaching an Event Procedure to a Form or Control

Programmer's Guide:

Chapter 4, "Menus and Dialogs"


Adding and Deleting Menu Commands at Run Time

See Also

After using the Menu Design window to create a control array with one or more menu items, you can write code (using the Load and Unload statements) to dynamically add or delete menu items in the array at run time.

To add or delete menu items in a control array at run time

1.	Create a menu control array.

2.	Open the Code window by double-clicking a control or the form itself.

3.	Go to the event or procedure where you want to Load or Unload members of the control array.

Note	At run time, you cannot remove commands created at design time.


See Also

Help:

Adding and Deleting Controls at Run Time

Programmer's Guide:

Chapter 4, "Menus and Dialogs"


Setting Form and Control Properties

See Also

Properties are named attributes of a form or control.  They define an object's characteristics, such as size, color, and screen location, and aspects of the object's behavior, such as whether it is enabled or not.  You can set properties in the Properties window at design time, and in code at run time.

To set form or control properties in the Properties Window at design time

1.	Click a blank part of a form to select the form; or click a control to select the control.

2.	From the Window menu, choose Properties (F4), or use the toolbar shortcut:

3.	From the Properties window, select the property you want either by clicking the property name in the Property list or by pressing Ctrl+Shift+ the first letter of the property name you want to select.  If several properties begin with the same letter, continue pressing Ctrl+Shift+ the first letter key until the property you want is selected.

Visual Basic displays the current setting for the property in the Settings box.

4.	In the Settings box, enter the setting you want.

For a property that requires entering text or a number, type the information.

For a property that has enumerated or Boolean values, click the down arrow to the right of the Settings box and select the option you want from the combo box or double-click the property name to cycle through the list of available choices.

For a number of properties, the down arrow changes into a button with three dots.  Click this button to display a dialog box in which you select the settings for the property.

5.	Click the Enter button to accept the setting or click the Cancel button to cancel it.

6.	Repeat steps 3-5 for each property you want to set for the selected form or control.

Note	To set a property that is shared by more than one control on a form, select the controls that share the property you want to change.  Change the property in the Properties window to affect all selected controls.

To set form or control properties at run time

Place a reference to the property (object.property) on the left side of an assignment statement.  For example:

Text1.Text = "Your Name"


See Also

Help:

Properties List

Learning Visual Basic:

Creating an Application

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"


Accessing Screen Properties

See Also

Like forms and controls, the Screen object has a set of predefined properties.  Unlike form and control properties, however, Screen properties are available only at run time and thus cannot be set in the Properties window.  You can access and manipulate Screen properties only in code at run time.  Screen properties are global for the current project.

To access a Screen property through code

Use the syntax Screen.propertyname [image] for example, Screen.Width.

The Screen properties are:

ActiveControl

ActiveForm

FontCount

Fonts

Height

MousePointer

TwipsPerPixelX

TwipsPerPixelY

Width


See Also

Help:

App Object

Clipboard Object

Debug Object

Printer Object

Screen Object

Setting Form and Control Properties


Setting Colors

See Also

You can set background and foreground colors for forms and controls using the Color palette.

To set colors with the Color palette

1.	From the Window menu, choose Color Palette.

The box on the left side of the palette displays the currently selected colors [image] the foreground color in the inner box and the background color in the outer box.

2.	Select the form or control whose color you want to change.

3.	To change the foreground color for the selected object, click the inner box, then click a color on the color box; to change the background color for the selected object, click the outer box, then click a color on the color box.

To set colors in the Properties window

1.	From the Properties window, select the color property you want to set either by clicking the property name in the Property list or by pressing Ctrl+Shift+ the first letter of the property name you want to select.

Visual Basic displays the current color setting in the Settings box, and the down arrow to the right of the Settings box changes into a button with three dots.

2.	Click the button with three dots or double-click the color property name.

3.	Click the color you want from the available choices.

Note	You can set normal RGB colors with the BackColor and ForeColor properties or in code using the RGB or QBColor functions in code.

If you specify colors using the system color constants from the CONSTANT.TXT file, Visual Basic substitutes the color-scheme choices the user has made in the Control Panel settings.


See Also

Help:

Creating Custom Colors


Creating Custom Colors

See Also

You can create custom colors using the Color palette.

To add a color to the Color palette

1.	From the Window menu, choose Color Palette.

2.	Click the Custom Colors button.

Visual Basic displays a row of color boxes at the bottom of the Color palette that you can use to set custom colors.

3.	Select a blank color box.

4.	Click the Define Colors button.

Visual Basic displays a dialog box with various color settings.

5.	Click anywhere in the large box to select a color.

6.	Click the bar at the right of the box to select the color you want, or click and drag the arrow displayed at the right of the bar to vary the shade and brightness of the color.

Visual Basic displays the selected color in the Color display box.

7.	Optional:  To fine-tune the color, adjust the numbers for the red, green, and blue color elements.

8.	Choose Add Color to add the color to the Color palette.

Note	Custom colors you have created are among the choices available from the Settings box of the Properties window.


See Also

Help:

Setting Colors


Guidelines for Entering and Editing Code

See Also

You enter and edit code in the Code window.  The Code window has automatic formatting and syntax checking capabilities built in.  If the syntax checker is turned on, Visual Basic displays a message when you enter code that has a syntax error.

Using the Code Window

To enter code, click the Code window and start typing.

To correct mistakes as you type, press Backspace.

To delete text, select it and press Del.

To move the insertion point, click where you want the insertion point to be, or use the Arrow keys.

To indent text, select the line or lines you want to indent, and press Tab.  To remove an indent, press Shift+Tab.

To switch between insert mode and overtype mode, press Ins.

To enter a comment in your code, start the comment with an apostrophe ( ' ).

To complete a Visual Basic statement, press Enter at the end of the line or move the pointer off the line.

To write multiple statements on one line, use a colon (:) as a separator.  For example:  For I = 1 to 100: A(I) = I: Next I

To view two procedures at a time, split the window by moving the split bar down the side of the Code window.

To accept arguments in a procedure, separate the arguments by commas if there is more than one, and enclose all the arguments in parentheses following the name of the procedure.  For example, Sub IncrementXY(X, Y).

To pass arguments to a procedure, separate the arguments by commas if there is more than one, following the name of the procedure being called.  For example, IncrementXY X, Y.  Enclose the arguments in parentheses following the procedure name only if the the Call keyword is being used before the procedure name.  For example, Call IncrementXY(X, Y).

To get Help on syntax for Visual Basic functions, statements, properties, events, or methods while working in the Code window, type or select the keyword, the property, event, or method name, and press F1.

Declarations and Variables

To make an assignment of one variable to another, use the syntax destination = source.

To name a variable, begin the name with a letter and use no more than 40 letters and numbers.


See Also

Help:

Attaching an Event Procedure to a Form or Control

Creating a General Procedure

Data Types

Entering Declarations in Code

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 6, "Programming Fundamentals"

Chapter 7, "Variables, Constants, and Data Types"


Attaching an Event Procedure to a Form or Control

See Also

The code you attach to a form or control is called an event procedure.  Every form and control has a set of predefined events that it can recognize.  You attach event procedures only for events to which you want a form or control to respond.

To attach an event procedure to a form or control

1.	Double-click a blank part of the form to open the form's Code window.  To attach code to a control, double-click the control.

2.	In the Procedure box, select the event to which you want to attach code.

3.	Enter the code you want in the template provided, following guidelines for entering and editing code and declarations.

4.	Repeat steps 2 and 3 as necessary to attach additional event procedures to the item.

Syntax

Use this syntax when writing an event procedure:

Sub ItemName_EventName (arguments)

local variable and constant definitions

statements

End Sub

Note	When attaching an event procedure, you can also select a form or control from the Object box in the Code window.  The information displayed in the Procedure box then changes to reflect the predefined events for the object you have selected.  Bold text in the Procedure box indicates event procedures for which you have written code.

Instead of using the template provided for you by Visual Basic, you can also create a new procedure by typing Sub ProcedureName in the Code window.

If you change the Name property of a control after attaching a procedure to it, you must also change the name of the procedure to match the name of the control.  Otherwise, Visual Basic won't be able to match the control to the procedure.  You can find the procedure by selecting (general) from the Code window's Object box and then selecting the procedure from the Procedure box.

For a list of the events that apply to forms and each type of control, see the topics under the Properties, Events, and Programming Language indexes.  For a list of all Visual Basic events, see the Events index.


See Also

Help:

Creating a General Procedure

Learning Visual Basic:

Writing Event-Driven Programs

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 3, "Creating and Using Controls"

Chapter 4, "Menus and Dialogs"


Entering Declarations in Code

See Also

Declarations are nonexecutable code statements that name external procedures, constants or variables and define their attributes (such as data type).  You write declarations for forms or modules.  To enter module-level declarations, go to the Declarations section of the form or module.  To enter global declarations, go to the Declarations section of a module and use the Global statement for constants and variables.

You can also enter procedure-level declarations.  For whatever code level and technique you use to declare a variable or constant, specific scoping rules may apply.  For details on scoping declarations, see Chapter 7, "Variables, Constants, and Data Types," in the Programmer's Guide.

To open the Declarations section for a form

1.	Double-click the form to open the Code window.

2.	In the Object box, select (General).

The Procedure box automatically displays (Declarations).

3.	Enter the declarations you want, following the guidelines for entering and editing code.

To open the Declarations section for a module

1.	In the Project window, select the module you want to open and click the View Code button.

2.	In the Procedure box, select (Declarations).

3.	Enter the declarations you want.

Note	Visual Basic comes with the file CONSTANT.TXT.  This file specifies system defaults such as colors, key codes, and defaults for properties and events.  You can load CONSTANT.TXT into any module and modify it to your specifications.


See Also

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application".

Chapter 7, "Variables, Constants, and Data Types"


Creating a General Procedure

See Also

A general procedure tells the application how to perform a specific task.  Once the procedure is defined, it must be explicitly invoked by the application.  By contrast, an event procedure remains idle until called upon to respond to events caused by the user or triggered by the system.  You can place a general procedure in either form code or in a module.  General procedures in a form can be accessed only from within that form; general procedures in a module can be accessed from any form or module in your application.  Using general procedures can help divide complex application code into more manageable units.

To create a general procedure

1.	Open the Code window for the form or module for which you want to write the procedure.

2.	From the View menu, choose New Procedure.

3.	In the text box, type a name for the procedure.

4.	Select Sub to create a Sub procedure or Function to create a Function procedure.

Note that a Function procedure returns a value and a Sub procedure does not.

5.	Choose OK.

Visual Basic sets up a template so you can enter code for the general procedure.

Note	You can also create a new procedure by typing Sub ProcedureName or Function ProcedureName in the Code window.

Syntax

Use this general syntax when writing a Sub procedure:

Sub ProcedureName (arguments)

local variable and constant declarations

statements

End Sub

Use this syntax when writing a Function procedure:

Function ProcedureName (arguments) As datatype

local variable and constant declarations

statements

ProcedureName = return value

End Function

Use general procedures for:

Sharing code among controls on one form.  Write a general procedure in form code and attach an event procedure to each control that invokes the general procedure.

Sharing code among multiple forms.  Create a module and write the shared code there as a general procedure.  For each form or control you want to share the code, attach an event procedure that calls the general procedure.

If you have too much code in a module you may exceed memory limitations.  It may help if you create one or more modules and offload code by attaching to the form or its controls short event procedures that call general procedures in the module(s).  Place global declarations in any module.

Multiple-form application startup.  Create a module and write a general procedure called Main for your startup routine.


See Also

Help:

Guidelines for Entering and Editing Code

Programmer's Guide:

Chapter 6, "Programming Fundamentals"

Chapter 7, "Variables, Constants, and Data Types""


Turning Syntax Checking On or Off

See Also

The Visual Basic Code window includes a syntax-checking feature that:

Checks each line of code for syntax errors (such as a misspelled keyword or missing separator) as you enter it, and alerts you if there are errors.

Translates the code to an internal form if the syntax is correct, which speeds the transition to run mode.

This feature is turned on when you first start up Visual Basic, but you can turn it off if you prefer to write all your code without being alerted to errors as they occur.

To turn syntax checking on or off

1.	From the Options menu, choose Environment.

2.	Select Syntax Checking.

3.	In the Setting box, select either Yes or No to enable or disable syntax checking.

Note	When you make a change to the Environment options, those changes are saved in the Visual Basic initialization file (VB.INI).


See Also

Help:

Guidelines for Entering and Editing Code


Using Example Code from Online Help

See Also

You can copy example code from online Help, paste it into the current Code window, and then edit the code to fit your needs.  Code examples are provided in the Programming Language, Properties, and Events topics.

To copy and paste example code from Help into your code

1.	Find the topic you want.

2.	Click the word Example in the non-scrolling region of the topic to jump to the code sample.

3.	In the secondary window that contains the code sample, choose Copy.

4.	In the Copy window, select the code you want to copy to the Code window and choose the Copy button.

5.	In the Code window, click where you want to insert the example code.

6.	From Visual Basic's Edit menu, choose Paste (Ctrl+V).

Note	After copying example code from Help, you may need to modify variables, constants, and references to form and control names to fit your application.  Be sure that you add an apostrophe ( ' ) at the beginning of each comment, especially if it wraps to a second line.  Failure to do so may prevent the code from executing.


See Also

Help:

Guidelines for Entering and Editing Code

Replacing Text in Code

Programmer's Guide:

Chapter 1, "Introduction"


Importing a Text File into Code

See Also

You can import a text file containing code into the current project and use it in your code.

To import a text file into the Code window

1.	From the File menu, choose Load Text.

2.	From the Files box, select the file you want to import.

3.	Choose Replace to replace all code in the current Code window with the imported text; choose Merge to add the text at the insertion point; or choose New to open a new module and load the text there.

Note	For compatibility with Microsoft Windows, Visual Basic uses the character codes in the ANSI character set, instead of the ASCII character set.


See Also

Help:

Guidelines for Entering and Editing Code

Using Example Code from Online Help


Finding a Procedure

See Also

To find a procedure in a Code window

1.	From the Window menu, choose Procedures (F2).

2.	From the Modules list box, choose the module containing the procedure you want to find.

3.	Select the procedure you want either by scrolling through the entries in the Procedures list box and clicking the procedure name, or by pressing the keyboard key for the first letter of the procedure name.  If you press the first letter key and the procedure you want is not selected, continue to press the key until the procedure you want is selected.

4.	Choose OK.

The procedure you have chosen is displayed in the Code window.

To find the next or previous procedure in a Code window

From the View menu, choose Next Procedure or Previous Procedure.

Keyboard Shortcuts

Press	To

Ctrl+Down Arrow	Display the next procedure.

Ctrl+Up Arrow	Display the previous procedure.

Page Down	Page down through the procedures in your code.

Page Up	Page back up through the procedures in your code.

F2	Display View Procedures dialog.


See Also

Help:

Replacing Text in Code

Searching for Text in Code


Searching for Text in Code

See Also

To search for specific text in the Code window

1.	From the Edit menu, choose Find (Ctrl+F).

2.	In the Find What text box, type the text you want to search for.  If any text is selected when you choose the command, this text is displayed in the text box.  If no text is selected, the word at the current insertion point is displayed.

3.	Select a Search option button to specify where to look for the text:

Current Procedure searches in the current procedure only.

Current Module searches in the active module only.

All Modules searches all the code in your project, including all forms.

4.	To set limits on the search, select the Match Whole Word Only check box to search only for the complete word by itself, and not as part of another word.  Select the Use Pattern Matching check box to search using pattern matching characters.

5.	Choose OK.

Visual Basic finds the first occurrence of the text.

6.	To find the next or previous occurrence of the text, choose Find Next or Find Previous from the Edit menu.

Keyboard Shortcuts

Press	To

Ctrl+F	Find: display Find dialog box.

F3	Find Next: repeat text search down through your code.

Shift+F3	Find Previous: repeat text search up through your code.


See Also

Help:

Finding a Procedure

Replacing Text in Code


Replacing Text in Code

See Also

To replace text in the Code window

1.	From the Edit menu, choose Replace (Ctrl+R).

2.	In the Find What text box, type the text you want to search for.  If any text is selected when you choose the command, this text is displayed here.  If no text is selected, the word at the current insertion point is displayed.

3.	In the Replace With text box, type the replacement text.

4.	Select a Search option button to specify where to look for the text:

Current Procedure searches in the current procedure only.

Current Module searches in the active module only.

All Modules searches all the code in your project, including all forms.

5.	Select Syntax Checking On if you want the syntax checked after each replacement is made.

6.	To set limits on the search, select the Match Whole Word Only check box to search only for the complete word by itself, and not as part of another word.  Select the Use Pattern Matching check box to search using pattern matching characters.

7.	Choose Verify if you want to confirm before changing each occurrence of the text, or choose Replace All to change all occurrences of the search text automatically.


See Also

Help:

Finding a Procedure

Searching for Text in Code


Splitting a Code Window Into Panes

You can split the Code window horizontally into two panes to view different code segments for a form or module at the same time.  Each pane scrolls separately, both horizontally and vertically.  The Procedure and Object box options refer to the pane that has the focus.  Code changes are immediately reflected in both panes.

To split the Code window into panes

Under the window's title bar, click and drag the split bar down.

To remove a split from the Code window

Click and drag the split bar back up to the title bar.


Saving Your Work

See Also

In Visual Basic, you can save entire projects as well as specific forms and modules.

To save a new or existing project

1.	From the File menu, choose Save Project, or use the toolbar shortcut:

If you have not previously saved the project, Visual Basic displays a dialog box in which you name and save the project.

2.	In the File Name text box, type a project name.

Unless you type a different file-name extension, Visual Basic automatically adds the extension .MAK.

3.	Choose OK.

If you have unsaved forms or modules in the project, Visual Basic prompts you to save them as well.

To save a new form or module

1.	Click the Form window for the form you want to save

or

Click the Code window for the module you want to save

or

Select the form or module you want to save in the Project window.

2.	From the File menu, choose Save File As (Ctrl+A).

3.	In the File Name text box, type a name for the form or module.

Unless you type a different file-name extension, Visual Basic automatically adds the extension .FRM for forms and .BAS for modules.

4.	Select Save As Text if you want the form or module saved as text.

5.	Choose OK.

To save changes to an existing form or module

1.	Click the form or module you want to save.

or

Select the form or module you want to save in the Project window.

2.	From the File menu, choose Save File (Ctrl+S).

To save code as a text file

1.	Click the module or form code you want to save.

2.	From the File menu, choose Save Text.

3.	In the File Name text box, type a name for the module.

Unless you type a different file-name extension, Visual Basic automatically adds the extension .TXT.

4.	Choose OK.


See Also

Help:

Importing a Text File into Code

Learning Visual Basic:

Creating an Application

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 5, "Managing Projects"


Debugging Checklist

See Also

There are three types of errors you may encounter as you run your application:

Compile errors [image] occur as a result of code that is incorrectly constructed.  You may have an incorrectly matched control structure, such as a Next statement without a corresponding For statement, or programming mistakes that violate the rules of Basic, such as a misspelled word, a missing separator, or a type mismatch.

Compile errors include syntax errors, which are errors in the grammar or punctuation recognized by Visual Basic.  Examples of syntax errors include passing an incorrect number of arguments to an intrinsic function or forgetting to match parentheses.

Run-time errors [image] occur after the application starts to execute.  Examples of run-time errors include attempting an illegal operation, such as writing to a file that doesn't exist, or dividing by zero.

Logical errors [image] the program doesn't perform as intended, and produces incorrect results.

Debugging is a process by which you find and resolve errors in your code.  To debug code in Visual Basic, consider the ideas suggested below.  These techniques can also be applied in different sequences.

1.	Print the code, if you find it easier to read code on paper instead of online.

2.	Run the application to find trouble spots:

From the Run menu, choose Start (F5) to begin running the application.

Run until an error stops execution, or halt execution manually when you suspect an error by choosing Break from the Run menu (Ctrl+Break).

Resolve all compile errors and run-time errors.

From the Run menu, choose Continue (F5) to continue running the application.

3.	Use debugging tools and techniques to isolate bugs and to monitor code flow:

Set breakpoints to halt execution at certain points to look for problems such as incorrect variable types, mixups in variable names, flaws in logical comparisons, endless loops, garbled output, problems with arrays, and so on.  You can also set breakpoints to monitor code flow or examine information in the current state.

Add a watch expression at design time or while in break mode to allow you to monitor the value of a particular expression as your code execution progresses.

Single step (F8) or procedure step (Shift+F8) through your code to trace through the application as it's running.

Use the Debug window to test individual lines of code or procedures, or to change values.

Enter break mode and choose Calls (Ctrl+L) from the Debug window to see where your code is currently executing and trace the path showing how it got there.

4.	Try out bug fixes and then make edits:

Test individual lines of new or debugged code in the Debug window.

Search and replace code for all occurrences of an error, checking other procedures, forms, or modules with related code.

From the Run menu, choose Restart (Shift+F5) to reset application variables and properties and restart the application from the beginning.


See Also

Help:

Continuing Execution

Ending Execution

Finding a Procedure

Guidelines for Entering and Editing Code

Halting Execution

Restarting Execution

Starting Execution

Learning Visual Basic

Debugging Your Application

Programmer's Guide:

Chapter 9, "Debugging"


Saving and Loading Forms in ASCII Format

See Also

Visual Basic can save and load both binary format and ASCII format forms.  Binary format forms load quickly but you can edit them only in Visual Basic.  ASCII format forms take longer to load but you can edit them with any text editor.  Visual Basic saves forms in binary format by default.  You can load binary files in Visual Basic only if their binary format is recognized by the current or previous version of Visual Basic.

To always save all new forms and modules as ASCII text

1.	From the Options menu, choose Environment.

2.	In the list, select Default Save As Format, and in the Setting combo box, choose Text.

To save an individual form as ASCII text

1.	In the Project window, select the file you want to save.

2.	From the File menu, choose Save File As.

3.	In the Save File As dialog box, check the Save As Text check box.

4.	Type a new name for the file if necessary and choose OK.

Once you save a form as text, that form is saved in ASCII text format (for example, when you choose Save from the File menu) until you use the Save As command to save it as binary.

To load an ASCII format form

From the File menu, choose the Add File command and specify the file name.

If an error occurs while loading an ASCII form file, Visual Basic writes an error message to a file with the base name of the form file and the extension .LOG, and displays a message on screen when it has finished loading the file.

Note	Don't confuse saving and loading ASCII format form files with the Save Text and Load Text commands on the File menu.  Use these commands to save and load nonform code modules or to save only the procedures in a form file as text.  If you create separate files using the Save Text command, those files will not be included in the project.


See Also

Help:

Environment Command (Options Menu)

Load and Save Text Commands

Save File Command

Saving Your Work

Programmer's Guide:

Appendix A, "ASCII File Format"


Setting Options

See Also

You can use the commands on the Options menu to set new preferences or reset default values for the programming environment or for specific projects.  Programming environment options include the foreground and background colors in a Code window, the number of spaces for the Tab key in a Code window, syntax checking, and whether variables must be declared before being referenced.  You can also set the number of horizontal and vertical grid lines on forms in design mode, and you can specify whether grid lines are visible and whether controls snap to the grid lines when placed on a form.

To set preferences for the programing environment

1.	From the Options menu, choose Environment.

2.	In the Setting combo box, select an option.

3.	In the text box portion of the Setting combo box, enter a new value.

4.	Choose OK.

Preferences for specific projects include a command-line argument setting to allow testing of command-line arguments for the application, specification of the name of the startup form for the application, and a specification for the application's Help file.

To set preferences for a specific project

1.	From the Options menu, choose Project.

2.	In the Setting combo box, select an option.

3.	In the text box portion of the Setting combo box, enter a new value.

4.	Choose OK.

You can also restore one, many, or all options to their original default values.

To restore selected preferences to default values

1.	From the Options menu, choose Environment or Project.

2.	In the Setting combo box, select an option or multiple options.

3.	Choose Reset.

To restore all preferences to default values

1.	From the Options menu, choose Environment or Project.

2.	Choose Reset All.


See Also

Help:

Environment Command (Options Menu)

Project Command (Options Menu)

Programmer's Guide:

Chapter 2, "Creating Your First Visual Basic Application"


Using MDI Features

See Also

Visual Basic's multiple-document interface (MDI) features enable you to create applications in which a single parent form (an MDI form) provides a background for multiple child forms (forms whose MDIChild property is True).  When you create MDI applications, keep the following in mind:

When an MDI child form is the startup form, the MDI form is loaded automatically; but MDI child forms are loaded only when specified as the startup form, when referenced in code, or when specified in a Load statement.

The menu bar designed for an MDI child form is displayed on the MDI form at run time when the MDI child form is active, even though it appears on the child form at design time.

The only controls you can place on an MDI form are a picture box or a custom control that has an Align property.  However, you can place other controls in the picture box.  Typically, you use the picture box to create a toolbar.  A picture box on an MDI form has the same width as the ScaleWidth of the MDI form, but it can have any height up to the ScaleHeight of the form.  The picture box must be aligned to the top or bottom of the MDI form client area.

If you want several MDI child forms in an MDI application to function identically, you can use multiple instances of a single form type, or an array of forms of a single type, instead of designing different child forms.  MDI child forms can be loaded or instantiated dynamically at run time using the Dim statement.  After creating a new instance of a form, you can change that instance's properties without affecting other forms.

Use the Me keyword to use common event procedures to reference the currently active instance of a form or the currently active form array element.  Similarly, the ActiveForm property of the MDI form specifies the MDI child form that has the focus (or that was most recently active).

Check the WindowList check box in the Menu Design window of the MDI form or an MDI child form when you want that menu control to display a list of open child forms at run time.

Use the Arrange method to rearrange child forms and their icons.


See Also

Help:

MDIChild Property

Me

Programmer's Guide:

Chapter 8, "Objects and Instances"

Chapter 14, "Multiple-Document Interface (MDI) Applications"


Using Custom Controls

See Also

You can use custom controls in your applications by loading them into the programming environment using the Add File command on the File menu, or by specifying their definition files (files with a .VBX extension) in a project's .MAK file.  For example, Visual Basic has a default project file called AUTOLOAD.MAK that includes two custom-control file specifications [image] GRID.VBX for the grid control, and OLECLIENT.VBX for the OLE control.  When Visual Basic starts with no other file specification, the default AUTOLOAD.MAK project is loaded and the icons for the grid and OLE controls appear at the bottom of the Toolbox.  You use custom controls the same way as other controls in Visual Basic.


See Also

Help:

Grid Control

OLE Control

Programmer's Guide:

Chapter 13, "Using the Grid Control"

Chapter 21, "Object Linking and Embedding (OLE)"


Using Watch Expressions

See Also

There are two ways to watch, or monitor, expressions in Visual Basic.  You can simply watch the value of the expression in the Debug window, or you can suspend program execution when the expression is true or changed.

When you watch the value of an expression, you generally set a breakpoint in a procedure in which you want to know the expression's value, and then use the Instant watch command to see the expression's value when program execution is suspended in that procedure.  When you use Instant watch, you have the option of also placing the expression in the Debug window.

You can also use the last two options in the Watch Type group to suspend application execution either when an expression becomes nonzero or each time the expression's value changes from zero to nonzero or from nonzero to zero.  Note that the term "true" when used with watchpoints refers to the logical (nonzero) state true, rather than to the bitwise complement of zero (that is, Not False, expressed as the intrinsic constant True (whose value is always -1).

For example, if you choose the Break When Expression is True option for a variable named MyVar in a procedure, program execution is suspended as soon as MyVar acquires a nonzero value.  However, if you choose it for the expression MyVar > 5, execution is not suspended until the expression MyVar > 5 evaluates to True.  Note that a simple string variable cannot be evaluated by itself; it must be used in a comparative expression like StrVar$ <> "" or be evaluated, as in the function call Len(StrVar$), in order for a watchpoint to suspend execution when it changes from an empty (zero length) to nonempty state.

The Context option for an expression can be no wider than the scope of the components of the expression.  For example, local variables can have only Procedure context.  Expressions whose components are defined at form or module level can have Procedure or Form/Module context, and globally scoped expressions can have any context.


See Also

Help:

Edit Watch Command

Programmer's Guide:

Chapter 9, "Debugging"


Using Dynamic Data Exchange (DDE)

See Also

Visual Basic's DDE features enable your applications to directly and continuously exchange data with other Windows-based applications that support DDE.  These data exchanges are called conversations.  You start data exchanges by establishing DDE links, which you can create at design time or run time.  Links you create at design time (see Creating a DDE Source or Destination Link) are simplest because they are automatically reestablished whenever the application is run.  However, when you create links at design time, the application with which you communicate must contain Copy and PasteLink commands.  Similarly, when you run the Visual Basic project at a later time, the other application must be available or an error will occur.  With design-time links, all updates to controls are made immediately and automatically whenever a data change occurs.  Links that are established at design time may fail at run time if the other application is unable to refresh them.

Links created at run time are more flexible, but they require you to write enabling code that sets the properties of the controls involved in the data exchange.  There are several advantages to creating links in code:

The other applications do not need Copy and PasteLink commands.

Your application can start the other application before initiating a conversation.

You can trap and handle errors.

When DDE links are created at run time, your application can choose when updates of data between linked controls actually occur.


See Also

Help:

DDE Example Between Visual Basic and Excel for Windows

Example of Source/Destination DDE Between Visual Basic Applications

LinkClose Event

LinkError Event

LinkExecute Event

LinkExecute Method

LinkItem Property

LinkMode Property

LinkNotify Event

LinkOpen Event

LinkPoke Method

LinkRequest Method

LinkSend Method

LinkTimeOut Property

LinkTopic Property

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


Starting Execution

See Also

One way to test your application is to run it and work with it as a user would.

To start execution

1.	From the Run menu, choose Start (F5), or use the toolbar shortcut:

2.	Test your application by using each control on each form.

The program ends when all forms are closed and no code is executing, when Visual Basic encounters an End statement in your code, or when you choose the End command from the Run menu or use the toolbar shortcut: .

If your application doesn't run, it may be because:

Visual Basic encounters a syntax error or some other compile error in your code.

Visual Basic encounters a logic error in your code, which may result in a compile or run-time error.

To get context-sensitive Help, press F1 while an error message is on the screen.  Consider the suggestions provided to correct the error before you try to execute the application again.


See Also

Help:

Continuing Execution

Debugging Checklist

Ending Execution

Halting Execution

Restarting Execution

Specifying a Startup Form

Learning Visual Basic

Creating an Application

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 9, "Debugging"


Halting Execution

See Also

As you run your application, it may halt for one of the following reasons:

An untrapped run-time error occurs.

Visual Basic encounters a breakpoint you set previously.

Visual Basic encounters a watch expression that you have set to break if its value changes or becomes true.

Visual Basic encounters a Stop statement or an End statement in your code.

You halt execution manually at a given point.

To halt execution manually

From the Run menu, choose Break (Ctrl+Break), or use the toolbar shortcut:

To continue execution when your application has halted

From the Run menu, choose Continue (F5), or use the toolbar shortcut:

or

From the Debug menu, choose Single Step (F8) or Procedure Step (Shift +F8).


See Also

Help:

Continuing Execution

Debugging Checklist

Ending Execution

Restarting Execution

Starting Execution

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 9, "Debugging"


Continuing Execution

See Also

As you run your application, it may halt for one of the following reasons:

An untrapped run-time error occurs.

Visual Basic encounters a breakpoint you set previously.

Visual Basic encounters a watch expression that you have set to break if its value changes or becomes true.

Visual Basic encounters a Stop statement or an End statement in your code.

You halt execution manually at a given point.

To continue execution when your application has halted (in all cases except after an End statement)

From the Run menu, choose Continue (F5), or use the toolbar shortcut:

or

From the Debug menu, choose Single Step (F8) or Procedure Step (Shift +F8).

Note	While in break mode, the edits you make to your code may cause syntax errors or other compile errors.  Visual Basic evaluates each new line of code before making the change and alerts you about errors in your code.  If you make a change that prevents execution from continuing, Visual Basic displays an alert with the option of canceling the change or of proceeding.  If you cancel the change, Visual Basic reverses the change by either deleting the incorrect line of new code or restoring the previous state of an old line of code.  If you choose to proceed, Visual Basic ends execution and returns to design mode.

You may want to change the sequence of your code with the Set Next Statement command (Debug Menu) to either rerun the changed statement or to bypass it.


See Also

Help:

Debugging Checklist

Ending Execution

Executing a Specific Statement

Restarting Execution

Starting Execution

Programmer's Guide:

Chapter 9, "Debugging"


Restarting Execution

See Also

You can restart execution of your application from break mode.  Restarting an application returns it to a newly initialized state, resetting all variables and removing any suspended procedures from memory.

To restart execution

From the Run menu, choose Restart (Shift+F5).

Visual Basic returns your application to a newly initialized state and starts running the application from the beginning.


See Also

Help:

Continuing Execution

Debugging Checklist

Ending Execution

Halting Execution

Starting Execution

Programmer's Guide:

Chapter 9, "Debugging"


Ending Execution

See Also

To end execution

From the Run menu, choose End, or use the toolbar shortcut:

or

Unload the last remaining form in the application.


See Also

Help:

Halting Execution

Restarting Execution

Starting Execution

Programmer's Guide:

Chapter 9, "Debugging"


Executing a Specific Statement

See Also

While execution of your code is halted, you can control the execution sequence of statements within a procedure.  You can resume execution at a statement you choose without executing any intervening code.

To set the next statement to be executed

1.	In the Code window, position the insertion point anywhere within the statement.

2.	From the Debug menu, choose Set Next Statement.

Note	You can skip only to statements within the same procedure.

During run time you can use a GoTo statement to branch to a specified line within a procedure.

Used in combination with single stepping, executing specific statements with the Set Next Statement command enables you to step through procedures one statement at a time, and to closely examine your code.  It's also helpful for correcting or avoiding run-time error conditions.


See Also

Help:

Debugging Checklist

Finding a Procedure

Tracing Execution

Programmer's Guide:

Chapter 9, "Debugging"


Tracing Execution

See Also

Tracing execution is useful in Visual Basic because in event-driven programming, it may not be obvious which statement is executed first.  Use these techniques to trace the execution of code:

Single stepping [image] tracing through each line of the procedure.  This shows you the effect of each statement on variables.

Procedure stepping [image] executing each procedure as if it were a single statement.  Use this instead of single stepping to step across procedure calls rather than into the called procedure.

To trace execution from the current statement

From the Debug menu, choose Single Step (F8), or use the toolbar shortcut [image] to execute code one line at a time.

From the Debug menu, choose Procedure Step (Shift+F8), or use the toolbar shortcut [image] to step across procedure calls.

To trace execution from the beginning of the program in break mode or run time

1.	From the Run menu, choose End, or use the toolbar shortcut:

Visual Basic resets all variables, removes any suspended procedures from memory, and returns to design time.

2.	From the Debug menu, choose Single Step (F8); or choose Procedure Step (Shift+F8).

The program runs until the first event procedure or Sub Main begins executing.

Note	You can also set a breakpoint or watch expression within a procedure before you start running the application.  When the application halts at the breakpoint, trace from that point.


See Also

Help:

Debugging Checklist

Finding a Procedure

Programmer's Guide:

Chapter 9, "Debugging"


Setting and Clearing Breakpoints

See Also

A breakpoint is a line in a program that you set to interrupt normal execution.  You set breakpoints to halt execution at specific statements in a procedure [image] for example, where you suspect problems may exist.  You clear breakpoints when you no longer need them to halt execution.

To set a breakpoint

1.	Position the insertion point anywhere in a line of the procedure where you want execution to halt.

2.	From the Debug menu, choose Toggle Breakpoint (F9), or use the toolbar shortcut:

Visual Basic adds the breakpoint and highlights the line using the breakpoint color set in the Environment Options dialog box.

3.	If the application is not running, choose Start (F5) from the Run menu, or use the toolbar shortcut: .  If the application halted during execution, choose Continue (F5) to continue through the program; or choose Restart (Shift+F5) from the Run menu to reset variables and run the application from the beginning.

Visual Basic halts execution whenever it encounters a breakpoint.

To clear a breakpoint

1.	Position the insertion point anywhere on a line of the procedure containing the breakpoint.

2.	From the Debug menu, choose Toggle Breakpoint (F9), or use the toolbar shortcut:

Visual Basic clears the breakpoint and removes the highlighting.

To clear all breakpoints in the application

From the Debug menu, choose Clear All Breakpoints.

Visual Basic clears all breakpoints in the application.

Note	Breakpoints set in code are not saved when you save forms and modules.  Closing a project or quitting Visual Basic automatically clears them.  Breakpoints also have no effect when creating an executable file since they are not saved.  A Stop statement, however, halts an executable file.

If you set a breakpoint on a line that contains several statements separated by colons (:), the break will always occur at the first statement on the line.


See Also

Help:

Adding, Editing, and Deleting Watch Expressions

Debugging Checklist

Programmer's Guide:

Chapter 9, "Debugging"


Adding, Editing, and Deleting Watch Expressions

See Also

A watch expression is an expression you define which Visual Basic then monitors for you.  When your application enters break mode, the watch expressions you have selected appear in the Watch pane of the Debug window where you can observe their values.  You can delete them once you are satisfied that the results are as you expect.

To add a watch expression

1.	From the Debug menu, choose Add Watch.

2.	Enter the expression you want evaluated in the Expression box.

3.	Click an option button in the Context group to select the range for when the expression will be evaluated.

4.	Click an option button in the Watch Type group to select how Visual Basic should respond to the watch expression.

5.	Choose OK.

To edit a watch expression

1.	From the Debug menu, choose Edit Watch (Ctrl+W).

2.	Select the watch expression you want to edit from the Current Expressions list.

3.	Choose Edit.

4.	Make the changes you want to the expression, the context, and the watch type.

5.	Choose OK.

To delete a watch expression

1.	From the Debug menu, choose Edit Watch (Ctrl+W).

2.	Select the watch expression you want to delete from the Current Expressions list, if you want to delete only one watch expression.

3.	Click Delete to delete a single watch expression or click Delete All to delete all the current watch expressions.

Note	Watch expressions are not saved when you save forms and modules.  Closing a project or quitting Visual Basic automatically clears them.


See Also

Help:

Debugging Checklist

Setting and Clearing Breakpoints

Programmer's Guide:

Chapter 9, "Debugging"


Using Instant Watch

See Also

While in break mode, you may want to check the current value of some variable or expression for which you have not defined a watch expression.  Do this using the Instant Watch command.

To display an instant watch

1.	Highlight an expression in either the Code window or the Immediate pane of the Debug window.

2.	From the Debug menu, choose Instant Watch (Shift+F9), or use the toolbar shortcut:

The Instant Watch dialog box displays the current value of the expression you selected.

3.	If you want to add a watch expression based on the expression in the Instant Watch dialog, click the Add Watch button.


See Also

Help:

Adding, Editing, and Deleting Watch Expressions

Debugging Checklist

Setting and Clearing Breakpoints

Programmer's Guide:

Chapter 9, "Debugging"


Using the Debug Window

See Also

To execute code in the Debug window while in break mode

1.	Type a line of code in the Debug window.

2.	Press Enter to execute the statement.

Use the Debug window to:

Test problematic or newly written code.

Query or change the value of a variable while running an application.  While execution is halted, assign the variable a new value as you would in code.

Query or change a property value while running an application.

Simulate a run-time error.  To see which error-message dialog box is associated with a given error code, type:

error errornumber

Call procedures as you would in code.

View debugging output while the program is running.

Note	Debug window statements are executed in a context [image] that is, as if they are entered in a specific form or module.  This context appears in the title bar of the Debug window.

If you need help on syntax for functions, statements, properties, events, or methods while working in the Debug window, select the keyword or the property, event, or method name, and press F1.

While in the Debug window, you can do most of the things you do in the Code window, but statements in the Debug window are not saved with the project.  If you want to save such code, copy or cut it and then paste it into the Code window.


See Also

Help:

Debugging Checklist

Programmer's Guide:

Chapter 9, "Debugging"


Specifying a Startup Form

See Also

 An application does not have to start up with the first form in the project; you can start your application with any form or a Sub Main procedure in a module.

To specify a startup form

1.	From the Options menu, choose Project.

Visual Basic displays a dialog box.

2.	Select Set Startup Form.

3.	In the Setting box, select the form you want to start your application.

4.	Choose OK.

Instead of loading a form, Visual Basic can invoke a procedure to start an application.

To specify a startup procedure

1.	Write a general Sub procedure called Main and save it in a module.

2.	From the Options menu, choose Project.

Visual Basic displays a dialog box.

3.	Select Set Startup Form.

4.	In the Project Options Setting box, choose Sub Main.

5.	Choose OK.

When the project starts execution, Sub Main is called immediately.


See Also

Programmer's Guide:

Chapter 5, "Managing Projects"


Assigning an Icon to a Form

See Also

You can assign a unique icon to any form that the user can minimize at run time.  If you do not assign an icon to a form, the form.ico file in the \icons\misc directory is the default.

To assign an icon to a form with the Properties window

1.	Click a blank part of the form to select it.

2.	In the Properties window, select Icon.

The down arrow to the right of the Settings box changes into a button with three dots.

3.	Click the button with three dots.

Visual Basic displays the Load Icon dialog box.

4.	Type or select the name of the icon you want to use.

5.	Choose OK.

Note	You can assign a unique icon to any form that the user can minimize at run time.  A unique icon can provide the user with a visual cue as to the function of a form or application.  Visual Basic's Icon Library is a good source for icons.


See Also

Help:

Setting Form and Control Properties

Specifying a Startup Form

Using Icons

Programmer's Guide:

Chapter 5, "Managing Projects"


Specifying Access Keys

See Also

An access key gives the user quick keyboard access to a menu, command, or control.  Unlike shortcut keys, access keys do not execute commands when pressed.  At design time, you designate a letter in the caption to be the access key.  At run time, this letter is underlined, and the user can access the menu or command by pressing Alt plus the letter.

To assign an access key to a control with the Properties window

1.	Click the control to select it.

2.	From the Properties window, select Caption.

3.	Type the caption in the Settings box.  Include an ampersand (&) in the caption immediately preceding the character you want to appear underlined at run time.  For example, if you type "&Add," the caption on the control appears as Add, and the access key is Alt+A.

4.	Click the Enter button.

To assign an access key to a menu or command with the Menu Design window

1.	Click the form with the menu bar.

2.	From the Window menu, choose Menu Design (Ctrl+M).

3.	In the Caption text box, type the menu name as you want it displayed on the menu bar.  Include an ampersand (&) immediately preceding the character you want to appear underlined at run time.  For example, if you type "Fi&le" the caption on the control appears as File, and the access key is Alt+L.

4.	Choose OK.


See Also

Help:

Creating a Menu Bar

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 4, "Menus and Dialogs"


Setting Tab Order

See Also

By default, Visual Basic assigns tab order to controls in the order you draw them on a form.  Each new control is placed last in the tab order.  To allow you to control the order that controls gain focus in your application, you can change the tab order at design time with the Properties window, or at run time through code.

To change tab order at design time

1.	Click a control to select it.

2.	From the Properties window, select TabIndex.

Visual Basic displays the current tab position in the Settings box.

3.	Type the number for the tab order position you want the control to have.

4.	Click the Enter button.

You can test the tab order at design time by pressing Tab.

To enable or disable a tab stop at design time

1.	Click a control to select it.

2.	From the Properties window, select TabStop.

Visual Basic displays the current Boolean value in the Settings box.

3.	Select True to designate the control as a tab stop, or select False to bypass the control in the tab order.

4.	Click the Enter button.

Note	When you change a control's tab order position, Visual Basic automatically renumbers the tab order positions of other controls to reflect insertions and deletions.

A control whose TabStop property has been set to False maintains its position in the actual tab order as set by the TabIndex property, even though the control is skipped when you cycle through the controls with the Tab key.


See Also

Help:

TabIndex Property

TabStop Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Creating a DDE Source or Destination Link

See Also

You can create data links between a Visual Basic application and other applications that support DDE.  The application that initiates the DDE conversation is the destination.  The application that responds to the destination is the source.  You use these links to get information from, or supply information to, another application.

To create a destination link

1.	In the source application, select the data item you want to link.

2.	From the source application's Edit menu, choose Copy.

3.	In your Visual Basic application, select the control (text box, label, or picture box) you want to receive the data.

4.	From Visual Basic's Edit menu, choose Paste Link.

If the link is successful, the control displays the data selected from the source application.

To create a source link

1.	In your Visual Basic application, select the form or control that contains the data you want to supply.

2.	From Visual Basic's Edit menu, choose Copy (Ctrl+C).

3.	In the destination application, select the destination for the data.

4.	From the destination application's Edit menu, choose Paste Link.

If the link is successful, the contents of the control are displayed in the destination application.

Note	The Paste Link command establishes an automatic link [image] a change in the source's data will automatically cause an update in the destination's data.  When an application with an automatic link is opened, a DDE conversation with the source application is automatically reestablished.  In contrast, a manual link requires user action to establish a DDE conversation and to update data.  Use the LinkMode property to specify an Automatic (1), Manual (2), or Notify (3) link for the destination control.


See Also

Help:

LinkItem Property

LinkRequest Method

LinkTimeout Property

LinkTopic Property

Programmer's Guide:

Chapter 20, "Communicating with Other Applications"


Icon Library

See Also

Visual Basic comes with a collection of over 450 icons in the ICONS directory that you can use to enhance your applications.  The Using Icons topic describes how to use icons in your applications.

The Icon Library includes these categories:

Arrows and pointers

Communication (networks, servers, printers, phones)

Computers (computers, disk drives, diskettes, keyboards, mouse devices)

 	Drag-and-drop (hands and arrows dragging and dropping file folders)

Elements (earth, water, fire, clouds, weather, the sun, phases of the moon)

Flags

Industry and transportation (bicycles, cars, airplanes, factories, tools)

Mail (mailboxes, envelopes, stamps, forms)

Miscellaneous (people, clocks, first-aid signs, locks and keys, buttons, punctuation marks, default form icons)

Office (card files, charts, file cabinets, folders, graphs, paper clips, labels)

Traffic signs

Writing (books, notepads, pens, pencils)

You can view the Icon Library either online with the IconWorks sample application included with Visual Basic, or in Appendix B, "Icon Library," of the Programmer's Guide.

Note	You may use the Icon Library icons or modified versions of them in your Visual Basic applications.  However, you are not allowed to make and sell copies of the Icon Library or any portion of it.


See Also

Help:

Assigning an Icon to a Form

Displaying Graphics on a Form

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Using Icons

See Also

There are a number of ways you can use icons to enhance your Visual Basic applications.  First determine the name and location of the file that contains the icon you want to use.  You can view the Icon Library icons to determine file names and directory locations using Appendix B, "Icon Library," of the Programmer's Guide, or by using the IconWorks sample application included with Visual Basic.

You can do the following with icons:

Display an icon on a form or in a picture box or image control during design time or run time.

Assign a drag icon to be displayed when a control is dragged during run time by setting the control's DragIcon property.

Assign an icon to a form to be displayed when the form is minimized during run time by setting the form's Icon property.

Assign an icon to a Visual Basic application  to be displayed in a Microsoft Windows program group by specifying the form whose icon is to be used in the Make EXE File dialog box.

Tips

For a minimized form, an application in a Microsoft Windows program group, and a control being dragged, the graphic representation must be in icon (.ICO) format.

You can view, modify, and create icons with the IconWorks sample application included in the \SAMPLES\ICONWRKS subdirectory of the main Visual Basic directory.

Some pairs of the Icon Library icons can be used in tandem.  For example, the pair of icons below represent the same file cabinet with its bottom drawer open and closed.

The unfilled parts of Icon Library icons are transparent.  This makes the background color of your control, form, or desktop visible.


See Also

Help:

Assigning an Icon to a Form

Displaying Graphics on a Form

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Keyboard Guide


Keyboard Guide

Code Window Keys

Debug Window Keys

Form Window Keys

Global Keys

Menu Design Window Keys

Project Window Keys

Properties Window Keys

Toolbox Keys


Global Keys

Use these key combinations in all Visual Basic windows:

Press	To

F5	Run an application.

F8	Execute code one line at a time.

Shift+F8	Execute statements one line at a time without stepping into procedure  calls.

Ctrl+Break	Stop running a Visual Basic application.

Ctrl+B	Show the Debug window (break mode only).

Shift+F5	Restart an application from the beginning after an interruption.

Use these key combinations in all Windows-based applications:

Press	To

F1	Open Help.

Alt+F6	Toggle between the last two active windows.

Alt+Esc	Cycle through top-level Windows-based applications.

Alt+Tab	Cycle through top-level Windows-based applications, restoring minimized applications.

Ctrl+Esc	Open the Task List.

Alt+Hyphen	Open the current window's Control menu.

Alt+Spacebar	Open the application's Control menu.

Alt or F10	Select the Control-menu box.

Alt+F4	(Visual Basic) Close the active window; if all windows are closed, close Visual Basic.

Alt+F4 	Close the application.

Ctrl+C	Copy the selection to the Clipboard.

Ctrl+X	Cut the selection to the Clipboard.

Ctrl+V	Paste the Clipboard selection.

Ctrl+Z	Undo the last edit.


Code Window Keys

Use these key combinations in the Code window:

Press	To

F1	Get context-sensitive Help on functions and statements, methods, properties, or events.

Ctrl+C	Copy the selected text to the Clipboard.

Ctrl+X	Cut the selected text to the Clipboard.

Del	Delete the selected text without placing it on the Clipboard.

Ctrl+V	Paste the Clipboard contents at the insertion point.

Ctrl+Z	Undo the last editing action in the current line.

Ctrl+N	Insert a blank line above the current line.

Ctrl+Y	Cut the current line to the Clipboard.

F2	Display the View Procedures dialog box.

Ctrl+F2	Move the insertion point into the Object box.

Shift+F2	Go to the definition of the selected procedure.

Ctrl+Down Arrow	Display the next procedure.

Ctrl+Up Arrow	Display the previous procedure.

Page Down	Page down through the procedures in your code.

Page Up	Page up through the procedures in your code.

Ctrl+Page Down	Shift viewing of your code one page to the right.

Ctrl+Page Up	Shift viewing of your code one page to the left.

F6	Switch between Code window panes (when the window is split).

F9	Set or remove a breakpoint.

F3	Find Next: repeat text search down through your code.  If no text search has been done, the Find dialog box is displayed.

Shift+F3	Find Previous: repeat text search up through your code.  If no text search has been done, the Find dialog box is displayed.

F5	Run an application (or continue running, if in break mode).

F8	Execute code one line at a time (single step).

Shift+F8	Execute code one procedure at a time (procedure step).

Ctrl+Break	Stop running a Visual Basic application.

Shift+F5	Restart an application from the beginning.

Use these key combinations for menu shortcuts in the Code window:

Press	To

Ctrl+D	Add File

Ctrl+S	Save File

Ctrl+A	Save File As

Ctrl+P	Print

Ctrl+F	Find

F3	Find Next

Shift+F3	Find Previous

Ctrl+R	Replace

Shift+F9	Instant Watch (break mode only)

Ctrl+W	Edit Watch

Ctrl+L	Calls Window (break mode only)

Ctrl+B	Debug window (break mode only)


Form Window Keys

Use these key combinations in the Form window:

Press	To

Shift+Ctrl+Alpha	Select a property in the Property list of the Properties window.

Alpha	Enter a value in the Settings box in the Properties window.

F7	Open the Code window for the selected object.

Ctrl+C	Copy the selected controls to the Clipboard.

Ctrl+X	Cut the selected controls to the Clipboard.

Del	Delete the selected controls without placing them on the Clipboard.

Ctrl+V	Paste the Clipboard contents on the form.

Ctrl+Z	Undo a deletion of controls.

Tab	Cycle forward through controls in tab order.

Shift+Tab	Cycle backward through controls in tab order.

Ctrl+Click	Add or remove a control from the selection.

Click+Drag	Select multiple controls.

Ctrl+Click+Drag	Add or remove controls from the current selection.

Ctrl+M	Display the Menu Design window (design time only).

F4	Display the Properties window (design time only).

Ctrl+ =	Bring to front (affects overlapping controls at design time only).

Ctrl+Hyphen	Send to back (affects overlapping controls at design time only).

To deselect all controls, click the form.  To select controls in a container, first deselect the container and then Ctrl+Click+Drag around the desired controls.


Debug Window Keys

Use these key combinations in the Immediate pane of the Debug window:

Press	To

Enter	Run a line of code.

Ctrl+Z	Undo the last edit action in the current line.

Ctrl+C	Copy the selected text to the Clipboard.

Ctrl+V	Paste the Clipboard contents at the insertion point.

Ctrl+X	Cut the selected text to the Clipboard.

Ctrl+L	Display Calls dialog box (break mode only).

Ctrl+W	Display Edit Watch dialog box.

Shift+F9	Display Instant Watch dialog box.

F5	Continue running an application.

Shift+F5	Restart an application.

F8	Execute code one line at a time (single step).

Shift+F8	Execute code one procedure at a time (procedure step).

Del	Delete the selected text without placing it on the Clipboard.

F2	Display View Procedures dialog box.

Ctrl+Enter	Insert carriage return.

F6	Switch to Watch pane.

Use these key combinations in the Watch pane of the Debug window:

Press	To

Enter	Display Edit Watch dialog box for selected watch expression.

F2	Display View Procedures dialog box.

F6	Switch to Immediate pane.

Ctrl+F	Find.

F3	Find Next.

Shift+F3	Find Previous.

Ctrl+R	Replace.

Ctrl+ =	Bring to front.

Ctrl+Hyphen	Send to back.

Ctrl+Down	Next Procedure.

Ctrl+Up	Previous Procedure.

Shift+F2	Procedure Definition.

Right Arrow	Shift viewing of the watch expression to the right.

Left Arrow	Shift viewing of the watch expression to the left.


Menu Design Window Keys

Use these key combinations in the Menu Design window:

Press	To

Tab	Cycle forward through the boxes and buttons.

Shift+Tab	Cycle backward through the boxes and buttons.

Enter	Cycle forward through menu items.

Alt+R	Move an item to a lower level in a hierarchical menu.

Alt+L	Move an item to a higher level in a hierarchical menu.

Alt+U	Move an item one line up.

Alt+B	Move an item one line down.

Use these key combinations when the Shortcut list box has the focus in the Menu Design window:

Press	To

F4	Open or close the list.

Alt+Down Arrow	Open or close the list.

Alt+Up Arrow	Open or close the list.

Page Down	Move to the last item in the list.

Page Up	Move to the first item in the list.

End	Move to the last item in the list.

Home	Move to the first item in the list.


Properties Window Keys

Use these key combinations when the Property list has the focus in the Properties window:

Press	To

F2	Switch focus to the Settings box.

F4	Switch focus to and open the Settings box.

Shift+Tab	Switch focus to the Object box.

Page Down	Move down through the Property list.

Page Up	Move up through the Property list.

Down Arrow	Move down through each property.

Up Arrow	Move up through each property.

Right Arrow	Move down through each property.

Left Arrow	Move up through each property.

End	Move to the last property in the list.

Home	Move to the first property in the list.

Alt+F6	Switch from the Properties window to the form.

Alpha	Enter setting for the selected property

Tab	Move the insertion point to the Settings box.

Ctrl+Shift+Alpha	Move to the next property in the list that begins with the alpha character.

Double-Click	Cycle through settings of enumerated properties or to switch focus to the Settings box for other property types.

Use these key combinations when the Settings box has the focus in the Properties window:

Press	To

Ctrl+Z	Undo the last editing action in the current line.

Ctrl+C	Copy the selected text to the Clipboard.

Ctrl+X	Cut the selected text to the Clipboard.

Del	Delete the selected text without placing it on the Clipboard.

Ctrl+V	Paste the Clipboard contents at the insertion point.

Enter	Move the insertion point into the Property list and commit the property change.

Shift+Tab	Switch focus to the Object box.

Tab	Move the focus to the Property list.

Esc	Cancel the property change.

Use these key combinations when a property has enumerated values and the Settings box has the focus in the Properties window:

Press	To

F4	Open or close the Settings box list.

Alt+Down Arrow	Open or close the Settings box list.

Alt+Up Arrow	Open or close the Settings box list.

Page Down	Move to the last item in the Settings box list.

Page Up	Move to the first item in the Settings box list.

Down Arrow	Move down through the items in the Settings box list.

Up Arrow	Move up through the items in the Settings box list.

Right Arrow	Move down through the items in the Settings box list.

Left Arrow	Move up through the items in the Settings box list.

End	Move to the last item in the Settings box list.

Home	Move to the first item in the Settings box list.

Use these key combinations when you set the BackColor, ForeColor, FillColor, or BorderColor properties, and the Settings box has the focus in the Properties window:

Press	To

Alt+Down Arrow	Display the Color palette.

Alt+Up Arrow	Display the Color palette.

Del	Reset to (None).

Use these key combinations when you set the Icon or Picture properties, and the Settings box has the focus in the Properties window:

Press	To

Alt+Down Arrow	Display the Load Icon or Load Picture dialog box.

Alt+Up Arrow	Display the Load Icon or Load Picture dialog box.

Del	Reset to (None).


Project Window Keys

Use these key combinations in the Project window:

Press	To

Enter	Open the selected file from the list.

Shift+Enter	Open the Code window for the selected file.

F7	Open the Code window for the selected file.

Home	Select the first file in the list.

End	Select the last file in the list.

Tab	Cycle between the list, the View Form, and the View Code buttons.


Toolbox Keys

Use these key combinations in the Toolbox:

Press	To

Enter	Place the selected control on the active form.

Down Arrow	Select the next tool down.

Up Arrow	Select the next tool up.

Left Arrow	Select the tool to the left.

Right Arrow	Select the tool to the right.

Tab	Move down through the Toolbox.

Shift+Tab	Move up through the Toolbox.

End	Select the last tool in the Toolbox.

Home	Select the pointer tool.


Visual Basic Menus


Visual Basic Menus

File Menu

Edit Menu

View Menu

Run Menu

Debug Menu

Options Menu

Window Menu

Help Menu


File Menu

New Project

Open Project

Save Project

Save Project As

New Form

New MDI Form

New Module

Add File

Remove File

Save File

Save File As

Load Text

Save Text

Print

Make EXE File

Exit


Edit Menu

Undo

Redo

Cut

Copy

Paste

Paste Link

Delete

Find

Find Next

Find Previous

Replace

Bring To Front

Send To Back

Align To Grid


View Menu

Code

New Procedure

Next Procedure

Previous Procedure

Procedure Definition

Toolbar


Debug Menu

Add Watch

Instant Watch

Edit Watch

Calls

Single Step

Procedure Step

Toggle Breakpoint

Clear All Breakpoints

Set Next Statement

Show Next Statement


Run Menu

Start

Continue

Break

End

Restart


Options Menu

Environment

Project


New Project Command (File Menu)

See Also

Description

Creates a new project.

You can have only one project open at a time in Visual Basic.  When you create a new project, Visual Basic prompts you to save your work in the current project, then closes all open files in the current project and creates a new one.  To specify default settings for new projects, you can modify the AUTOLOAD.MAK project with the forms, modules and custom controls you want for all new projects.


See Also

Help:

Open Project Command (File Menu)

Project Command (Options Menu)

Project Command (Window Menu)

Save Project, Save Project As... Commands (File Menu)

Programmer's Guide:

Chapter 5, "Managing Projects"


Open Project Command (File Menu)

See Also

Description

Closes the current project, if any, and loads an existing project.

Toolbar shortcut:

Dialog Box Options

Option	Description

File Name	Type or select a project file from the Files box.

Directories	Select a directory from the list.  Select the drive or directory where the project is stored if different from your current path.  (The current path is displayed above this box.)

Drives	Select a drive from the list.

List Files of Type	Select a file type from the list.  Files of the selected type will appear in the list box.

OK	Opens the selected file.

Cancel	Closes the dialog box without opening a file.


See Also

Help:

New Project Command (File Menu)

Project Command (Options Menu)

Project Command (Window Menu)

Save Project, Save Project As... Commands (File Menu)

Programmer's Guide:

Chapter 5, "Managing Projects"


Save Project, Save Project As... Command (File Menu)

See Also

Description

Saves the current project (.MAK) and all forms and modules in the current project.  If you have any new forms or modules, you'll be prompted to save them.

Forms and modules are stored in text format or in binary format.  You specify the format in the Save Project As dialog, or with the Project command on the Options menu.

Toolbar shortcut:

Dialog Box Options for Save Project As...

Option	Description

File Name	Type a file name for the project or accept the default file name.  Unless you specify otherwise, Visual Basic automatically adds the default file-name extension .MAK.

Directories	Select a directory from the list.  Select the drive or directory where the file is stored if different from your current path.  (Your current path is displayed above this box.)

List Files of Type	Select a file type from the list.  Files of the selected type will appear in the list box.

Drives	Select a drive from the list.

OK	Saves the project under the specified name.

Cancel	Closes the dialog box without saving the project.

If you type a new name for an existing project, Visual Basic creates a new project. The earlier version of the file remains under its earlier name.

If you type the name of an existing project, Visual Basic displays a message warning you that you'll be overwriting an existing file.  Choose:

OK	To replace the existing file.

Cancel	To close the dialog box without saving the file.


See Also

Help:

New Project Command (File Menu)

Open Project Command (File Menu)

Project Command (Options Menu)

Project Command (Window Menu)

Saving Your Work

Programmer's Guide:

Chapter 5, "Managing Projects"


New Form, New MDI Form, New Module Commands (File Menu)

See Also

Description

Creates a new form, a new multiple-document interface (MDI) form, or a new module, and adds it to your project.  Because a project can have only one MDI form, the New MDI Form command is unavailable if a project already has an MDI form.

New Form toolbar shortcut:

New Module toolbar shortcut:


See Also

Help:

MDIChild Property

New Project Command (File Menu)

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 14, "Multiple-Document Interface (MDI) Applications"


Add File Command (File Menu)

See Also

Description

Adds an existing form, module, or custom control file to your project.  You can use a form or module in any number of projects.

Dialog Box Options

Option	Description

File Name	Type or select a file name from the Files box.

Directories	Select a directory from the list.  Select the drive or directory where the file is stored if different from your current path.  (Your current path is displayed above this box.)

List Files of Type	Select a file type from the list:

VB Files (*.FRM; *.BAS; *.VBX) [image] lists all valid Visual Basic file types.

Form Files (*.FRM) [image] lists all forms.

Basic Files (*.BAS) [image] lists all modules.

Custom Controls (*.VBX) [image] lists all custom controls.

Drives	Select a drive from the list.

OK	Adds the file to the project.

Cancel	Closes the dialog box without adding the file to the project.


See Also

Help:

Remove File Command (File Menu)

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"


Remove File Command (File Menu)

See Also

Description

Removes the active form, module, or custom control file from your project.

Removing a file does not delete the file from your disk.  The file remains in all the other projects to which it has been added.

Files that have been removed from a project remain stored on your hard disk until you delete them, following standard procedures for your operating system.

When removing a form, module, or custom control from a project, make sure the remaining code does not refer to the removed file.


See Also

Help:

Add File Command (File Menu)

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"


Save File, Save File As... Commands (File Menu)

See Also

Description

Saves the active form or module to your disk with a name you specify.  The Save File command displays the Save As dialog box if no file name has been specified.

The dialog box enables you to specify a new name for a form, MDI form, or module.

Dialog Box Options for Save File As...

Option	Description

File Name	Type a file name or accept the default.  Unless you specify otherwise, Visual Basic automatically adds the default file-name extension .MAK for projects, .FRM for forms, and .BAS for modules.

Directories	Select a directory from the list.  Select the drive or directory where the file is stored if different from your current path.  (Your current path is displayed above this box.)

List Files of Type	Select a file type from the list:

All Files (*.*) [image] list files of all types.

Form Files (*.FRM) [image] list all form files.

Basic Files (*.BAS) [image] list all modules.

Drives	Select a drive from the list.

Save As Text	Select to save the current file in text format.  If not selected, files are saved in binary format.  You can set the Default Save As Format for all files with the Environment command on the Options menu.

OK	Saves the file under the specified name.

Cancel	Closes the dialog box without saving the file.

If you type a new name for an existing file, Visual Basic creates a new file.  The old version of the file remains on your disk with the old name.

If you type the name of an existing file, Visual Basic displays a message warning you that you'll be overwriting an existing file.  Choose:

OK	To replace the existing file.

Cancel	To close the dialog box without saving the file.


See Also

Help:

Add File Command (File Menu)

New Form, New MDI Form, New Module Commands (File Menu)

Saving Your Work

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"


Load Text, Save Text Commands (File Menu)

See Also

Description

Load Text [image] use to specify a text file from which you load code into a Visual Basic Code window.

Save Text [image] use to save the code in the current form, MDI form, or module as a text file.  To save a form or MDI form as text, including all property settings, choose the Save File As command from the File Menu.

Dialog Box Options

Options	Description

File Name	Type or select a file name from the Files box.

Directories	Select a directory from the list.  Select the drive or directory where the file is stored or where you want to store the file if different from your current path.  (Your current path is displayed above this box.)

List Files of Type	Select a file type from the list:

Text Files (*.TXT) [image] lists all text files.

Basic Files (*.BAS) [image] lists all modules.

All Files (*.*) [image] lists files of all types.

Drives	Select a drive from the list.

Replace	Replaces all the text in the active module with the code you're loading.

Merge	Adds the text you're loading to the code in the active module at the current insertion point without deleting existing code.

New	Creates a new module with the text you're loading.

Cancel	Closes the dialog box without loading the code.


See Also

Help:

Project Command (Options Menu)

Save File, Save File As... Commands (File Menu)

Save Project, Save Project As... Commands (File Menu)

Saving Your Work

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"


Print Command (File Menu)

See Also

Description

Prints forms and code to the printer specified in the Microsoft Windows Control Panel.

Dialog Box Options

Option	Description

Current 	Prints the active form or the code in the active Code window.

All	Prints all forms or all code in your application.

Form	Prints the current form or all forms in your application.

Form Text	Prints the text representation for the current form or all forms in your application.  Use this feature to print out all form and control properties and their values.

Code	Prints the code for the current file or for all forms and modules in your application.

OK	Prints your selection.

Cancel	Closes the dialog box without printing.


See Also

Programmer's Guide:

Chapter 16, "Displaying and Printing Information"


Make EXE File Command (File Menu)

See Also

Description

Creates an executable application by combining the forms and modules in a project into a single executable file.

An executable file runs without invoking Visual Basic.  To run an executable file, the run-time file VBRUN300.DLL must be in a directory on the user's path.

This command does not affect the project files.  You can still work with your original files without affecting the executable file.

Dialog Box Options

Options	Description

File Name	Type the file name for the executable file or accept the default.  Unless you specify otherwise, Visual Basic automatically adds the default file-name extension .EXE to an executable file.

Directories	Select a directory from the list.  Select the drive or directory where the file is to be stored if different from your current path.  (Your current path is displayed above this box.)

Drives	Select a drive from the list.

Application Title	Specify the title for your application or accept the default (the project name).  This title will appear in the Microsoft Windows Task Manager when the executable file is running.

Icon	Shows the icon that the Microsoft Windows Program Manager displays for the application.  The default icon is the icon for the startup form.

Use Icon From	Select an icon from among those you've assigned to the Icon property for forms in the project.

OK	Creates an executable version of your application.

Cancel	Closes the dialog box without making an executable file.


See Also

Help:

Icon Library

Icon Property

Programmer's Guide:

Chapter 5, "Managing Projects"


Exit Command (File Menu)

See Also

Description

Closes the current project and quits Visual Basic.  If you try to quit Visual Basic before saving changes to your work, you'll be prompted to save your work first.

Mouse shortcut: double-click the Control-menu box.  Keyboard shortcut: Alt+F4.


See Also

Programmer's Guide:

Chapter 1, "Introduction"


Redo, Undo Commands (Edit Menu)

See Also

Description

Undo [image] reverses the last editing action, such as typing text in the code editor or deleting controls.  When you delete one or more controls, you can use the Undo command to restore the controls and all their properties except for the TabIndex property, which cannot be restored.  TabIndex is reset to the end of the Tab order when using Undo.  For forms, Undo is unavailable if the form has been edited since the last control deletion.

Keyboard shortcut: Ctrl+Z.

Redo [image] restores the last text editing Undo actions if no other actions occur since the last Undo.

Keyboard shortcut: Ctrl+Backspace.

For text edits, you can use Undo and Redo to restore up to twenty editing actions.

These commands are unavailable if there was no previous editing action, or if any other action has been performed after the last editing action.


See Also

Programmer's Guide:

Chapter 1, "Introduction"


Cut, Copy, Paste, and Delete Commands (Edit Menu)

See Also

Description

Cut [image] removes the selected control or text and places it on the Clipboard.

Keyboard shortcut: Ctrl+X.

Copy [image] copies the selected control or text to the Clipboard.

Keyboard shortcut: Ctrl+C.

Paste [image] inserts a control or text that has been copied to the Clipboard.  Text is placed at the insertion point.  Pasted controls are placed at the upper left of the active form.

When you paste a control, it has the same properties and control Name as the control you copied.  You can keep the same name and create a control array, or paste the control with a different name.

Keyboard shortcut: Ctrl+V.

Delete [image] erases the currently selected control or text.

To remove a form or module from a project without deleting it from your disk, choose the Remove File command from the File menu.

To delete a file from your disk, follow standard deletion procedures for your operating system.

Keyboard shortcut: Del.


See Also

Help:

Remove File Command (File Menu)

Programmer's Guide:

Chapter 1, "Introduction"


Find, Find Next, Find Previous Commands (Edit Menu)

See Also

Description

Find [image] searches code in the project for specified text.

Find Next [image] searches code in the project for the next occurrence of the text you specified.

Find Previous [image] searches code in the project in reverse order for a previous occurrence of the text you specified.

Keyboard shortcut: Shift+F3.

If a search is successful, the dialog box closes and Visual Basic selects the located text.  If no match is found, Visual Basic displays a message stating that the text was not found.

Dialog Box Options

Option	Description

Find What	Type the text you want to search for.  If any text is selected when you choose the command, this text is displayed in the text box.  If no text is selected, the word at the current insertion point is displayed.

Search Current Procedure	Searches only the current procedure.

Search Current Module	Searches only the current module.

Search All Modules	Searches all the code in your project.

Match Whole Word Only 	Searches for the full word by itself and not as part of another word.

Use Pattern Matching	Searches using pattern matching characters.

OK	Stats the new search.

Cancel	Closes the dialog box without performing the search.


See Also

Help:

Finding a Procedure

Programmer's Guide:

Chapter 1, "Introduction"

Chapter 9, "Debugging"


Replace Command (Edit Menu)

See Also

Description

Searches code in the project for the specified text and replaces it with new text.

Dialog Box Options

Option	Description

Find What	Type the text you want to search for.  If any text is selected when you choose the command, this text is displayed in the text box.  If no text is selected, the word at the current insertion point is displayed.

Replace With	Type the new text.

Search Current Procedure	Searches only the current procedure.

Search Current Module	Searches only the code in the current module.

Search All Modules	Searches all the code in your project.

Syntax Checking On	Checks the syntax after making the replacement.

Match Whole Word Only 	Searches for the full word by itself and not as part of another word.

Use Pattern Matching	Searches using pattern matching characters.

Verify	Confirms before replacing the search text with the replacement text.

Replace All	Replaces all occurrences of the search text with the replacement text without stopping for confirmation.  If a syntax error is found while the Syntax Checking option is selected, the search ends after the error is found, and possibly before any text has been replaced.

Cancel	Closes the dialog box without replacing text.

If you select the Verify box, Visual Basic displays a message when the search text is found asking you to confirm that you want the text replaced.

Yes	Replaces the selected text, then continues the search.

No	Continues the search without changing the selected text.

Cancel	Cancels the search.


See Also

Help:

Find, Find Next, Find Previous Commands (Edit Menu)

Replacing Text in Code

Programmer's Guide:

Chapter 9, "Debugging"


Bring To Front, Send To Back Commands (Edit Menu)

See Also

Description

Bring To Front [image] moves the selected control to the front of all other objects.

Send To Back [image] moves the selected control behind all other objects.

Note	These commands work only with selected controls at design time.  In code, you can use the ZOrder method to move forms to the front or back of other forms, and controls to the front or back of other controls.


See Also

Help:

ZOrder Method

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Align To Grid Command (Edit Menu)

See Also

Description

Specifies whether the selected controls on a form automatically align to the grid.

To have all controls automatically align to the grid, use the Environment command on the Options menu.


See Also

Help:

Environment Command (Options Menu)


Code Command (View Menu)

See Also

Description

Displays or activates the Code window for the current form or module.

Keyboard shortcut: F7.


See Also

Help:

Guidelines for Entering and Editing Code

Programmer's Guide:

Chapter 6, "Programming Fundamentals"

Chapter 9, "Debugging"


New Procedure Command (View Menu)

See Also

Description

Creates a new Sub or Function procedure.

Dialog Box Options

Options	Description

Name	Type a name for the new procedure.

Sub	Creates a new Sub procedure.

Function	Creates a new Function procedure.

OK	Creates the procedure in the Code window.

Cancel	Closes the dialog box without creating a new procedure.


See Also

Help:

Guidelines for Entering and Editing Code

Next Procedure, Previous Procedure Command (View Menu)

Programmer's Guide:

Chapter 6, "Programming Fundamentals"


Next Procedure, Previous Procedure Commands (View Menu)

See Also

Description

Next Procedure [image] displays the next procedure in the current form or module.

Keyboard shortcut: Ctrl+Down Arrow.

Previous Procedure [image] displays the previous procedure.

Keyboard shortcut: Ctrl+Up Arrow.


See Also

Help:

Guidelines for Entering and Editing Code

New Procedure Command (View Menu)

Programmer's Guide:

Chapter 6, "Programming Fundamentals"

Chapter 9, "Debugging"


Procedure Definition Command (View Menu)

See Also

Description

Displays the code for a procedure called from within another procedure.  For example, in the Form_Load procedure, you might have a call to the Click event procedure for a menu item using mnuOpen_Click.  If you click this code in the Form_Load procedure and then choose the Procedure Definition command, the Code window displays the code for your mnuOpen_Click procedure.


See Also

Help:

Next Procedure, Previous Procedure Commands (View Menu)

Programmer's Guide:

Chapter 9, "Debugging"


Toolbar Command (View Menu)

See Also

Description

Displays or removes the toolbar.  A check mark appears in front of this command when the toolbar is visible.


See Also

Help:

Menu Bar and Toolbar

Programmer's Guide:

Back cover.


Start Command (Run Menu)

See Also

Description

Runs the application from the beginning (either a startup form or Sub Main as set with the Project command on the Options menu).  All forms being designed are closed, variables are initialized, and the startup form (if any) is loaded.

This command is available only at design time.

Toolbar button:   Keyboard shortcut: F5.


See Also

Help:

Break Command (Run Menu)

Continue Command (Run Menu)

End Command (Run Menu)

Restart Command (Run Menu)

Programmer's Guide:

Chapter 9, "Debugging"


Break Command (Run Menu)

See Also

Description

Stops execution of a program while it's running and switches to break mode.  If a statement is being executed when you choose this command, that statement is displayed in the Code window with a thin-line border around it, and highlighted in the colors you set with the Environment command on the Options menu.  If the application is waiting for events in the idle loop (that is, no statement is being executed), no statement is highlighted until an event occurs.

Some editing changes made during break mode may require you to restart your program for the changes to take effect.

This command is available only at run time.

Toolbar button:   Keyboard shortcut: Ctrl+Break.


See Also

Help:

Continue Command (Run Menu)

End Command (Run Menu)

Restart Command (Run Menu)

Start Command (Run Menu)

Programmer's Guide:

Chapter 9, "Debugging"


Continue Command (Run Menu)

See Also

Description

Continues executing your application after any kind of interruption.  An interruption can be caused by run-time errors, a Stop statement, a breakpoint in your code, choosing the Break command, or pressing Ctrl+Break while your program is running.

Choosing the Continue command doesn't restart the application.  It continues execution after the last successfully executed statement.

This command is available only in break mode.

Toolbar button:   Keyboard shortcut: F5.


See Also

Help:

Break Command (Run Menu)

End Command (Run Menu)

Restart Command (Run Menu)

Start Command (Run Menu)

Programmer's Guide:

Chapter 9, "Debugging"


End Command (Run Menu)

See Also

Description

Stops running the application and returns to design time.

This command is available during run time and while in break mode.

Toolbar shortcut:


See Also

Help:

Break Command (Run Menu)

Continue Command (Run Menu)

Restart Command (Run Menu)

Start Command (Run Menu)

Programmer's Guide:

Chapter 9, "Debugging"


Restart Command (Run Menu)

See Also

Description

Resets application variables to their initial value and starts running the application from the beginning.  Use the Restart command to reinitialize the variables before continuing an application that has been interrupted or halted.

If you choose this command while a program is running or in break mode, execution is terminated and then restarted.

This command is available during run time and break mode.

Keyboard shortcut: Shift+F5.


See Also

Help:

Break Command (Run Menu)

Continue Command (Run Menu)

End Command (Run Menu)

Start Command (Run Menu)

Programmer's Guide:

Chapter 9, "Debugging"


Add Watch Command (Debug Menu)

See Also

Description

Displays a dialog box in which you enter a watch expression.  The expression can be any valid Basic expression.  Watch expressions are updated in the upper pane of the Debug window each time you enter break mode.

When selecting a context for a watch expression, use the narrowest scope that fits your needs.  Selecting Global or Form/Module could slow your program considerably, since Visual Basic evaluates the expression after executing each line of code.  Selecting Procedure for a context will affect execution only while the selected procedure is in the list of active procedure calls, which you can see with the Calls command on the Debug Menu.

Dialog Box Options

Expression

Enter the expression to be watched.  The default is the term that was selected when you chose the command.

Context

Procedure

The expression is evaluated after executing every line of code while the procedure is in the call tree.

Form/Module

The expression is evaluated after executing every line of code.

Global

The expression is evaluated after executing every line of code.

Watch Type

Watch Expression

The expression and its value appear in the upper pane of the Debug window.

Break when Expression is True

Execution automatically breaks whenever the expression evaluates to True or any nonzero value (not valid for string expressions).

Break when Expression has Changed

Execution automatically breaks whenever the value of the expression changes.


See Also

Help:

Adding, Editing and Deleting a Watch Expression

Calls Command (Debug Menu)

Instant Watch Command (Debug Menu)

Setting and Clearing Breakpoints

Programmer's Guide:

Chapter 9, "Debugging"


Instant Watch Command (Debug Menu)

See Also

Description

Brings up a dialog box with the current value of the selected expression.  Available only during break mode.  While debugging your program, use this command to see the current value of a variable, property, or other expression.  Select the expression and then choose the command.

Toolbar shortcut:   Keyboard shortcut: Shift+F9.


See Also

Help:

Add Watch Command (Debug Menu)

Adding, Editing and Deleting a Watch Expression

Edit Watch Command (Debug Menu)

Setting and Clearing Breakpoints

Programmer's Guide:

Chapter 9, "Debugging"


Edit Watch Command (Debug Menu)

See Also

Description

Brings up a dialog box in which you can edit or delete a single watch expression, delete all watch expressions, or add watch expressions.

Dialog Box Options

Options	Description

Current Expressions	Select the expression you want to change.

Edit	Brings up the Edit Watch (Add Watch) dialog with the selected expression.  The Edit Watch and Add Watch dialogs are identical.

Add	Brings up the Add Watch dialog with no expression.

Delete	Deletes the selected expression from the Current Expressions list.

Delete All	Deletes all expressions from the Current Expressions list.

Close	Closes the dialog.


See Also

Help:

Add Watch Command (Debug Menu)

Adding, Editing and Deleting a Watch Expression

Instant Watch Command (Debug Menu)

Setting and Clearing Breakpoints

Toggle Breakpoint Command (Debug Menu)

Programmer's Guide:

Chapter 9, "Debugging"


Calls Command (Debug Menu)

See Also

Description

Displays a dialog with the list of currently active procedure calls.  Available only during break mode.

When Visual Basic is executing the code in a procedure, that procedure is added to a list of active procedure calls.  If that procedure then calls another procedure, there are then two procedures on the list of active procedure calls.  Each time a procedure calls another Sub or Function, it is added to the list.  Each procedure is removed from the list as execution is returned to the calling procedure.  Procedures called from the Debug window are also added to the calls list.

Toolbar shortcut:   Keyboard shortcut: Ctrl+L.


See Also

Programmer's Guide:

Chapter 9, "Debugging"


Single Step Command (Debug Menu)

See Also

Description

Executes one statement, advances to the next, then halts.  Use this command to run your code one line at a time when you want to see the effects of each statement.  This command is available only in break mode.

Single stepping traces through every line of Sub or Function procedures as they are invoked in your application.

If the next executable statement is outside the current module in an application that shares code, Visual Basic automatically opens the appropriate Code window.

When all statements have been executed, Visual Basic gives the focus to your application and waits for the next event.

Toolbar shortcut:   Keyboard shortcut: F8.


See Also

Help:

Executing a Specific Statement

Procedure Step Command (Debug Menu)

Programmer's Guide:

Chapter 9, "Debugging"


Procedure Step Command (Debug)

See Also

Description

This command treats Sub and Function procedures as a single executable statement as it executes one statement at a time, advances to the next executable statement, then halts.  This command is available only in break mode.

When all statements have been executed, Visual Basic gives the focus to your application and waits for the next event.

Toolbar shortcut:   Keyboard shortcut: Shift+F8.


See Also

Help:

Executing a Specific Statement

Single Step Command (Debug Menu)

Programmer's Guide:

Chapter 9, "Debugging"


Toggle Breakpoint Command (Debug Menu)

See Also

Description

Sets or removes a breakpoint at the current line.

A line of code in which a breakpoint has been set appears in the colors you specified with the Environment command on the Options menu.

This command is not available during run time.

Toolbar shortcut:   Keyboard shortcut: F9.


See Also

Help:

Add Watch Command (Debug Menu)

Adding, Editing and Deleting a Watch Expression

Edit Watch Command (Debug Menu)

Instant Watch Command (Debug Menu)

Setting and Clearing Breakpoints

Programmer's Guide:

Chapter 9, "Debugging"


Clear All Breakpoints Command (Debug Menu)

See Also

Description

Removes all breakpoints in your code.  When you turn off all breakpoints, your application can run in its entirety without breaking execution.

This command is not available during run time.


See Also

Help:

Add Watch Command (Debug Menu)

Adding, Editing and Deleting a Watch Expression

Edit Watch Command (Debug Menu)

Instant Watch Command (Debug Menu)

Setting and Clearing Breakpoints

Toggle Breakpoint Command (Debug Menu)

Programmer's Guide:

Chapter 9, "Debugging"


Set Next Statement Command (Debug Menu)

See Also

Description

Changes the execution sequence of your code so that the next statement executed is the one currently selected.  Any intervening code is not executed.  Use to rerun a statement or to skip over statements you don't want to execute.  This command is available only in break mode.

You can set only the next statement within the same procedure.


See Also

Help:

Executing a Specific Statement

Programmer's Guide:

Chapter 9, "Debugging"


Show Next Statement Command (Debug Menu)

See Also

Description

Shows the next statement to be executed when you continue running your application.

This command is available only in break mode.


See Also

Help:

Executing a Specific Statement

Programmer's Guide:

Chapter 9, "Debugging"


Environment Command (Options Menu)

See Also

Description

Determines the attributes of the Visual Basic environment.

Dialog Box Options

Option	Description

Tab Stop Width	Width in characters.  The default is 4.

Require Variable Declaration	Determines whether Visual Basic automatically inserts an Option Explicit statement in the Declarations section of each new form and module.  The default is No.

Syntax Checking	Determines whether each line is checked for correct syntax as you enter code.  The default is Yes.

File Save Format	Determines the format for saving new forms and modules (text or binary).  You can specify an alternate format with the Save As command on the File menu.  The default is binary.

Selection Text	Color of currently selected text.

Selection Background	Background color of currently selected text.

Next Statement Text	Color of the next statement to be executed.  Identified with the Show Next Statement command from the Debug menu during break mode.

Next Statement Background	Background color of the next statement to be executed.

Breakpoint Text	Color of any breakpoint statement.

Breakpoint Background	Background color of breakpoints.

Comment Text	Color of text preceded by Rem or an apostrophe ( ' ).

Comment Background	Background color of comment text.

Keyword Text	Color of text for all reserved words and keywords.

Identifier Text	Color of text of variables, properties, and object names.

Identifier Background	Background color of variables, properties, and object names.

Code window Text	Color of values, operators, and other text.

Code window Background	Background color of values, operators, and other text.

Debug window Text	Color of all text in the Debug window.

Debug window Background	Background color of all text in the Debug window.

Grid Width	Determines the number of horizontal twips between units of the grid used to place objects on a form at design time.  The default is about 120 twips.

Grid Height	Determines the number of vertical twips between units of the grid.  The default is about 120 twips.

Show Grid	Determines whether the grid is visible at design time.  The grid does not have to be visible to align controls.  The default is Yes.

Align To Grid	Determines whether objects placed on a form automatically align to the grid.  The default is Yes.

OK	Accepts the option settings and dismisses the dialog.

Cancel	Dismisses the dialog without saving any changes to the option settings.

Reset	Resets the current option to its default value.

Reset All	Resets all options to their default values.


See Also

Help:

Setting Options

Programmer's Guide:

Chapter 1, "Introduction"


Project Command (Options Menu)

See Also

Description

Determines option settings for the current project.

Dialog Box Options

Option	Description

Command Line Argument	Use this option to test the command line arguments you want to make available to users.  This is the text that would appear after the name of the executable file in the Command Line field of the Program Item Properties dialog in the Program Manager.

Start Up Form	The first form that is loaded when you run your application.  You can choose to specify Sub Main instead of a form.

Help File	The name of the Help file for your application.  Building a Help file requires the Microsoft Windows Help Compiler, which is available with the Visual Basic Professional Developer's Edition.  The HelpContextID property of forms and controls refers to specific topics in this file.


See Also

Help:

Setting Options

Programmer's Guide:

Chapter 1, "Introduction"


Window Menu Commands

See Also

Color Palette

Opens or activates the Color palette.

Debug

Opens or activates the Debug window.

Keyboard shortcut: Ctrl+B.

Menu Design

Opens or activates the Menu Design window.

Toolbar shortcut:   Keyboard shortcut: Ctrl+M.

Procedures

Opens the Procedures dialog box where you can select a procedure to view or edit.

Keyboard shortcut: F2.

Options	Description

Modules	Lists the modules in the current project.

Procedures	Lists the procedures in the selected module.

OK	Displays the selected procedure in the code window.

Cancel	Closes the dialog box.

Project

Opens or activates the Project window.

Properties

Opens or activates the Properties window.

Toolbar shortcut:   Keyboard shortcut: F4.

Toolbox

Opens or activates the Toolbox.

Data Manager

Opens or activates the Data Manager application.

Report Designer (Professional Edition Only)

Opens or activates the Crystal Reports for Visual Basic application.  This command is available only with the Professional Edition, and only if you elected to install Crystal Reports during setup.


See Also

Help:

Other Information Sources
(such as Data Manager Help,
and Crystal Reports Help)

Programmer's Guide:

Chapter 1, "Introduction"


Help Menu Commands

See Also

Contents

Runs Help and displays the Visual Basic Table of Contents.

Search For Help On

Displays Help's Search dialog so you can quickly find the information you need.

Obtaining Technical Support

Runs Help and displays information about Microsoft Product Support services.

Learning Microsoft Visual Basic

Runs quick lessons on using Visual Basic.

About Microsoft Visual Basic

Displays a dialog box with the version number, a copyright notice, and the amount of available memory.


See Also

Programmer's Guide:

Chapter 1, "Introduction"


Pattern Matching and Regular Expressions

See Also

The pattern matching used in the Find and Replace commands on the Code menu is implemented using regular expressions.  A regular expression is a set of characters that describes how to match a text string being searched for.  In its simplest form, a regular expression is a character-for-character match of the string you're trying to find.  In Visual Basic, you can use special characters (often called metacharacters) to make your text searches more versatile.  Regular expressions work much like the wildcard characters "*" and "?" that the operating system recognizes, but with a few enhancements.

The special characters and the way they are used is described below.

Expression	Description

*	Character wildcard.  Matches zero or more characters.  Must be enclosed in [ ] to match itself.  For example, a*a matches aa, a3a, aBa, and aBBBa.

?	Character wildcard.  Matches any one character.  Must be enclosed in [ ] to match itself.  For example, a?a matches aaa, a3a, and aBA, but not aBBBa.

#	Numeric wildcard.  Matches any one character from 0 through 9.  Must be enclosed in [ ] to match itself.  For example, a#a matches a0a, a1a, a2a, but not aaa or a10a.

[class ]	Character class.  Matches any one character in the class.  You can specify ranges by separating starting and ending characters with a hyphen.  For example, [a-z,0-9] matches any alphanumeric character.  Because the pattern matching is not case-sensitive, a-z works for both lowercase and uppercase letters.

A class can contain multiple clauses, each separated by a comma.  Each clause can consist of a single character or a range of characters.  For example, [D-Z,0-9] matches any letters and numbers but A, B, and C.

[!class]	Not character class.  Matches any character not specified in the class.  For example, [!a-z] matches anything but letters; [!0-9] matches anything but numbers.  You can use the exclamation point (!) only in the first character position of a class specification.  Other rules are the same as those in the character class.


See Also

Help:

Find, Find Next, Find Previous Commands (Edit Menu)


Load Picture, Load Icon Dialog Box Options

SeeAlso

Description

Loads an existing picture or icon file.

Dialog Box Options

Option	Description

File Name	Type or select a file name from the Files box.

Directories	Select a directory from the list.  Select the drive or directory where the file is stored if different from your current path.  (Your current path is displayed above this box.)

Drives	Select a drive from the list.

List Files of Type	Select a file type from the list:

All Picture Files (*.BMP, *.DIB, *.WMF, *.ICO) [image] lists all picture files.

Bitmaps(*.BMP, *.DIB) [image] lists bitmaps and DIBs.

Metafiles (*.WMF) [image] lists Microsoft Windows Metafiles.

All Files (*.*) [image] lists files of all types.

OK	Loads the selected file.

Cancel	Closes the dialog box without loading a picture file.


See Also

Help:

Icon Library

Icon Property

Picture Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"

Appendix B, "Icon Library"


Form

See Also	Properties	Events	Methods

Description

A form is a window or dialog box that makes up part of an application's interface.

Remarks

Forms have properties that determine aspects of their appearance, such as position, size, and color, and aspects of their behavior, such as whether they are resizable.

Forms can also respond to events initiated by the user or triggered by the system.  For example, you could write code in a form's Click event procedure that would allow the user to change the color of a form by clicking it.

In addition to properties and events, you can use methods to manipulate forms from code.  For example, you can use the Move method to change a form's location and size.

A special kind of form, the MDI form, can contain other forms called MDI child forms.  An MDI form is created with the New MDI Form command on the File menu; an MDI child form is created by choosing New Form from the File menu and then setting the MDIChild property to True.

You can create multiple instances of forms in code by using the New reserved word in Dim, Global, Set, and Static statements.

When designing forms, set the BorderStyle property to define a form's border and set the Caption property to put text in the title bar.  In code, you can use the Hide and Show methods to make forms invisible or visible at run time.

Note	You cannot use Hide on an MDI child form.

Setting BorderStyle to 0 removes the border.  If you want your form to have a border without the title bar, Control-box menu, Maximize button, and Minimize button, you can do so by deleting any text from the form's Caption property and setting the form's ControlBox, MaxButton, and MinButton properties to False.

Form is an object type.  You can declare variables as type Form before setting them to an instance of a type of form that was declared at design time.  Similarly, you can declare a parameter to a procedure as type Form.

Forms also can be server links in a DDE conversation, with a label, picture box, or text box control furnishing the data.


Properties

ActiveControl	FontBold	LinkTopic

ActiveForm	FontItalic	MaxButton

AutoRedraw	FontName	MDIChild

BackColor	FontSize	MinButton

BorderStyle	FontStrikethru	MousePointer

Caption	FontTransparent	Name

ClipControls	FontUnderline	Picture

ControlBox	ForeColor	ScaleHeight

Count	hDC	ScaleLeft

CurrentX	Height	ScaleMode

CurrentY	HelpContextID	ScaleTop

DrawMode	hWnd	ScaleWidth

DrawStyle	Icon	Tag

DrawWidth	Image	Top

Enabled	KeyPreview	Visible

FillColor	Left	Width

FillStyle	LinkMode	WindowState


Events

Activate	KeyPress	MouseDown

Click	KeyUp	MouseMove

DblClick	LinkClose	MouseUp

Deactivate	LinkError	Paint

DragDrop	LinkExecute	QueryUnload

DragOver	LinkOpen	Resize

GotFocus	Load	Unload

KeyDown	LostFocus


Methods

Circle	PrintForm	Show

Cls	Print	TextHeight

Hide	PSet	TextWidth

Line	Refresh	ZOrder

Move	SetFocus

Point	Scale


See Also

Help:

Controls

Forms Collection

MDIForm

Using DDE

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"

Chapter 5 , "Managing Projects"

Chapter 14, "Multiple-Document Interface (MDI) Applications"


Check Box Control

See Also	Properties	Events	Methods

Description

A check box displays an X when selected; the X disappears when the check box is cleared.  Use this control to give the user a True/False or Yes/No option.  You can use check boxes in groups to display multiple choices from which the user can select one or more.

Remarks

Check boxes and option buttons function similarly but with an important difference: any number of check boxes on a form can be selected at the same time.  In contrast, only one option button in a group can be selected.

To display text next to the check box, set the Caption property.  Use the Value property to determine the state of the box [image] selected, cleared, or unavailable.


Properties

Alignment	FontName	MousePointer

BackColor	FontSize	Name

Caption	FontStrikethru	Parent

DataField	FontUnderline	TabIndex

DataSource	ForeColor	TabStop

DragIcon	Height	Tag

DragMode	HelpContextID	Top

Enabled	hWnd	Value

FontBold	Index	Visible

FontItalic	Left	Width


Events

Click	KeyDown	MouseDown

DragDrop	KeyPress	MouseMove

DragOver	KeyUp	MouseUp

GotFocus	LostFocus


Methods

Drag	SetFocus

Move	ZOrder

Refresh


See Also

Help:

Data Access

Data Control

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Combo Box Control

See Also	Properties	Events	Methods

Description

A combo box combines the features of a text box and a list box.  Use a combo box to give the user the choice of typing in the text box portion or selecting an item from the list portion of the control.


Properties

BackColor	HelpContextID	SelLength

DragIcon	hWnd	SelStart

DragMode	Index	SelText

Enabled	ItemData	Sorted

FontBold	Left	Style

FontItalic	List	TabIndex

FontName	ListCount	TabStop

FontSize	ListIndex	Tag

FontStrikethru	MousePointer	Text

FontUnderline	Name	Top

ForeColor	NewIndex	Visible

Height	Parent	Width


Events

Change	DragOver	KeyPress

Click	DropDown	KeyUp

DblClick	GotFocus	LostFocus

DragDrop	KeyDown


Methods

AddItem	Refresh

Clear	RemoveItem

Drag	SetFocus

Move	ZOrder


See Also

Help:

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Command Button Control

See Also	Properties	Events	Methods

Description

A command button is chosen by the user to begin, interrupt, or end a process.  When chosen, a command button appears pushed in, and is sometimes called a "push button."

Remarks

To display text on a command button, set its Caption property.  A user can always choose a command button by clicking it.  To allow the user to choose it by pressing Enter, set the Default property to True.  To allow the user to choose the button by pressing Esc, set the button's Cancel property to True.


Properties

BackColor	FontSize	Parent

Cancel	FontStrikethru	TabIndex

Caption	FontUnderline	TabStop

Default	Height	Tag

DragIcon	HelpContextID	Top

DragMode	hWnd	Value

Enabled	Index	Visible

FontBold	Left	Width

FontItalic	MousePointer

FontName	Name


Events

Click	KeyDown	MouseDown

DragDrop	KeyPress	MouseMove

DragOver	KeyUp	MouseUp

GotFocus	LostFocus


Methods

Drag	SetFocus

Move	ZOrder

Refresh


See Also

Help:

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Directory List Box Control

See Also	Properties	Events	Methods

Description

A directory list box displays directories and paths at run time.  You can use this control to display a hierarchical list of directories.  This is useful if you want to create dialog boxes that, for example, enable the user to open a file from a list of files in all available directories.

Remarks

Set the List, ListCount, and ListIndex properties to enable a user to access items in a list.  If you also display a drive list box and file list box, you can write code to synchronize them with the directory list box and with each other.


Properties

BackColor	ForeColor	Name

DragIcon	Height	Parent

DragMode	HelpContextID	Path

Enabled	hWnd	TabIndex

FontBold	Index	TabStop

FontItalic	Left	Tag

FontName	List	Top

FontSize	ListCount	Visible

FontStrikethru	ListIndex	Width

FontUnderline	MousePointer


Events

Change	KeyPress

Click	KeyUp

DragDrop	LostFocus

DragOver	MouseDown

GotFocus	MouseMove

KeyDown	MouseUp


Methods

Drag	SetFocus

Move	ZOrder

Refresh


See Also

Help:

Drawing a Control

Drive List Box Control

File List Box Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 18, "Using the File-System Controls"


Drive List Box Control

See Also	Properties	Events	Methods

Description

A drive list box enables the user to select a valid disk drive at run time.  You can use this control to display a list of all the valid drives in the user's system.  This is useful if you want to create dialog boxes that enable the user to open a file from a list of files on a disk in a different drive.

Remarks

Set the List, ListCount, and ListIndex properties to enable a user to access items in the list.  If you also display a directory list box and file list box, you can write code to synchronize them with the drive list box and with each other.


Properties

BackColor	FontUnderline	MousePointer

DragIcon	ForeColor	Name

DragMode	HelpContextID	Parent

Drive	Height	TabIndex

Enabled	hWnd	TabStop

FontBold	Index	Tag

FontItalic	Left	Top

FontName	List	Visible

FontSize	ListCount	Width

FontStrikethru	ListIndex


Events

Change	KeyDown

DragDrop	KeyPress

DragOver	KeyUp

GotFocus	LostFocus


Methods

Drag	SetFocus

Move	ZOrder

Refresh


See Also

Help:

Directory List Box Control

Drawing a Control

File List Box Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 18, "Using the File-System Controls"


File List Box Control

See Also	Properties	Events	Methods

Description

A file list box locates and lists files in the directory specified by the Path property at run time.  You can use this control to display a list of files selected by their file attributes.  This is useful if you want to create dialog boxes in your application that, for example, enable the user to select a file or group of files.

Remarks

Set the List, ListCount, and ListIndex properties to enable a user to access items in the list.  If you also display the directory list box and drive list box controls, you can write code to synchronize them with the file list box and with each other.


Properties

Archive	Height	Parent

BackColor	HelpContextID	Path

DragIcon	Hidden	Pattern

DragMode	hWnd	ReadOnly

Enabled	Index	Selected

FileName	Left	System

FontBold	List	TabIndex

FontItalic	ListCount	TabStop

FontName	ListIndex	Tag

FontSize	MousePointer	Top

FontStrikethru	MultiSelect	TopIndex

FontUnderline	Name	Visible

ForeColor	Normal	Width


Events

Click	KeyDown	MouseMove

DblClick	KeyPress	MouseUp

DragDrop	KeyUp	PathChange

DragOver	LostFocus	PatternChange

GotFocus	MouseDown


Methods

Drag	SetFocus

Move	ZOrder

Refresh


See Also

Help:

Directory List Box Control

Drawing a Control

Drive List Box Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 18, "Using the File-System Controls"


Frame Control

See Also	Properties	Events	Methods

Description

A frame provides an identifiable grouping for controls.  You can also use a frame to subdivide a form functionally [image] for example, to separate a group of option buttons from other groups of option buttons.

Remarks

To group controls, first draw the frame and then draw the controls inside the frame.  This enables you to move the frame and controls together.  If you draw a control outside the frame and then try to move it inside, the control will be on top of the frame and you'll have to move the frame and controls separately.

To select multiple controls in a frame, hold down the Ctrl key while using the mouse to draw a box around the controls.


Properties

BackColor	FontSize	MousePointer

Caption	FontStrikethru	Name

ClipControls	FontUnderline	Parent

DragIcon	ForeColor	TabIndex

DragMode	HelpContextID	Tag

Enabled	Height	Top

FontBold	hWnd	Visible

FontItalic	Index	Width

FontName	Left


Events

Click	DragOver	MouseUp

DblClick	MouseDown

DragDrop	MouseMove


Methods

Drag	Refresh

Move	ZOrder


See Also

Help:

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Horizontal and Vertical Scroll Bar Controls

See Also	Properties	Events	Methods

Description

Scroll bars provide easy navigation through a long list of items or a large amount of information.  They also can provide an analog representation of current position.  You can use a scroll bar as an input device or indicator of speed or quantity [image] for example, to control the sound volume of a computer game or to view the time elapsed in a timed process.

Remarks

When you're using a scroll bar as an indicator of quantity or speed or as an input device, use the Max and Min properties to set the appropriate range of the control.

To specify the amount of change to report in a scroll bar, use the LargeChange property for clicking in the bar, and the SmallChange property for clicking the arrows at the ends of the bar.  The scroll bar's Value property increases or decreases by the amounts set for the LargeChange and SmallChange properties.  You can position the scroll box at run time by setting Value between 0 and 32,767, inclusive.


Properties

DragIcon	Left	TabStop

DragMode	Max	Tag

Enabled	Min	Top

Height	MousePointer	Value

HelpContextID	Name	Visible

hWnd	Parent	Width

Index	SmallChange

LargeChange	TabIndex


Events

Change	KeyPress

DragDrop	KeyUp

DragOver	LostFocus

GotFocus	Scroll

KeyDown


Methods

Drag	Refresh	ZOrder

Move	SetFocus


See Also

Help:

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Label Control

See Also	Properties	Events	Methods

Description

A label is a graphical control you can use to display text that the user can't change directly.

Remarks

You can write code that changes a label in response to events at run time.  For example, if your application takes a few minutes to commit a change, you could display a processing-status message in a label.  You can also use a label to identify a control, such as a text box, that does not have its own Caption property.

Set the AutoSize and WordWrap properties if you want the label to properly display variable-length lines or varying numbers of lines.

A label can also act as a destination link in a DDE conversation.  To do this, set the LinkTopic property to establish a link, set the LinkItem property to specify an item for the conversation, and set the LinkMode property to activate the link.  When these have been set, Visual Basic attempts to initiate the conversation and displays a message if it is unable to do so.


Properties

Alignment	FontBold	LinkMode

AutoSize	FontItalic	LinkTimeout

BackColor	FontName	LinkTopic

BackStyle	FontSize	MousePointer

BorderStyle	FontStrikethru	Name

Caption	FontUnderline	Parent

DataField	ForeColor	TabIndex

DataSource	Height	Tag

DragIcon	Index	Top

DragMode	Left	Visible

Enabled	LinkItem	Width

WordWrap


Events

Change	DragOver	LinkOpen

Click	LinkClose	MouseDown

DblClick	LinkError	MouseMove

DragDrop	LinkNotify	MouseUp


Methods

Drag	LinkRequest 	ZOrder

LinkExecute 	Move

LinkPoke	Refresh


See Also

Help:

Data Access

Data Control

Drawing a Control

TabIndex Property

Text Box Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 15, "Creating Graphics for Applications"


List Box Control

See Also	Properties	Events	Methods

Description

A list box displays a list of items from which the user can select one or more.  If the number of items exceeds what can be displayed, a scroll bar is automatically added to the list box.

If no item is selected, the ListIndex property value is -1.  The first item in the list is ListIndex 0, and ListCount is always one more than the largest ListIndex value.

Remarks

To add or delete items in a list, use the AddItem or RemoveItem method.  Set the List, ListCount, and ListIndex properties to enable a user to access items in the list.


Properties

BackColor	Height	NewIndex

Columns	HelpContextID	Parent

DragIcon	hWnd	Selected

DragMode	Index	Sorted

Enabled	ItemData	TabIndex

FontBold	Left	TabStop

FontItalic	List	Tag

FontName	ListCount	Text

FontSize	ListIndex	Top

FontStrikethru	MousePointer	TopIndex

FontUnderline	MultiSelect	Visible

ForeColor	Name	Width


Events

Click	GotFocus	LostFocus

DblClick	KeyDown	MouseDown

DragDrop	KeyPress	MouseMove

DragOver	KeyUp	MouseUp


Methods

AddItem	Move	SetFocus

Clear	Refresh	ZOrder

Drag	RemoveItem


See Also

Help:

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Menu Control

See Also	Properties	Events

Description

A menu control displays a customized menu for your application.  A menu can include commands, submenu titles, and separator bars.  Each menu you create can have up to four levels of submenus.

Remarks

To create a menu control, use the Menu Design window.  Enter the name of the menu in the Caption box.  To create a separator bar, enter a single hyphen (-) in the Caption box.  To display a check mark to the left of a menu item, check the Checked box.

While you can set some menu control properties in the Menu Design window, all menu properties are available in the Properties window.  To display the menu properties, select the menu name in the Objects list at the top of the Properties window.

When you create an MDI (Multiple-Document Interface) application, the menu bar on the MDI child form will replace the menu bar on the MDI form when the child form is active.


Properties

Caption	Index	Tag

Checked	Name	Visible

Enabled	Parent	WindowList

HelpContextID	ShortCut


Events

Click


See Also

Help:

Creating A Menu Bar

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 4, "Menus and Dialogs"

Chapter 14, "Multiple-Document Interface (MDI) Applications"


Option Button Control

See Also	Properties	Events	Methods

Description

An option button displays an option that can be turned on or off.

Remarks

Usually, option buttons are used as part of an option group to display multiple choices from which the user can select only one.  You can group option buttons by drawing them inside a frame, a picture box, or directly on a form.  To group option buttons in a frame or picture box, draw the frame or picture box first, and then draw the option buttons inside.  All option buttons within a frame or picture box are treated as a group.  Option buttons on a form are also treated as a separate group from any option buttons in a frame or picture box.

While option buttons and check boxes may appear to function similarly, there is an important difference:  when a user selects an option button, the other option buttons in the same group are automatically cancelled.  In contrast, any number of check boxes can be selected.


Properties

Alignment	FontStrikethru	Parent

BackColor	FontUnderline	TabIndex

Caption	ForeColor	TabStop

DragIcon	Height	Tag

DragMode	HelpContextID	Top

Enabled	hWnd	Value

FontBold	Index	Visible

FontItalic	Left	Width

FontName	MousePointer

FontSize	Name


Events

Click	GotFocus	LostFocus

DblClick	KeyDown	MouseDown

DragDrop	KeyPress	MouseMove

DragOver	KeyUp	MouseUp


Methods

Drag	SetFocus

Move	ZOrder

Refresh


See Also

Help:

Check Box Control

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Picture Box Control

See Also	Properties	Events	Methods

Description

A picture box can display a graphic from a bitmap, icon, or metafile.  It displays only as much of the graphic as fits into the rectangle that you've drawn with the picture box tool.

Remarks

You can also use a picture box to group option buttons and to display output from graphics methods and text written with the Print method.

To make a picture box automatically resize to display an entire graphic, set its AutoSize property to True.

To create animation or simulation, you can manipulate the graphics properties and methods in your code.  Graphics properties and events are useful for run-time print operations, such as modifying the format of a screen form for printing.

A picture box can also act as a destination link in a DDE conversation.

The picture box is the only standard Visual Basic control that you can place in the client area of an MDI form.  You can use it to group controls at the top or bottom of the client area to create a toolbar or status bar.


Properties

Graphics properties are indicated with an asterisk (*).'

Align	*FillStyle	LinkTimeout

*AutoRedraw	*FontBold	LinkTopic

AutoSize	*FontItalic	MousePointer

BackColor	*FontName	Name

BorderStyle	*FontSize	Parent

*ClipControls	*FontStrikethru	Picture

*CurrentX	*FontTransparent	*ScaleHeight

*CurrentY	*FontUnderline	*ScaleLeft

DataField	*ForeColor	*ScaleMode

DataSource	hDC	*ScaleTop

DragIcon	Height	*ScaleWidth

DragMode	HelpContextID	TabIndex

*DrawMode	hWnd	TabStop

*DrawStyle	Image	Tag

*DrawWidth	Index	Top

Enabled	Left	Visible

*FillColor	LinkItem	Width

LinkMode


Events

Change	KeyPress	LostFocus

Click	KeyUp	MouseDown

DblClick	LinkClose	MouseMove

DragDrop	LinkError	MouseUp

DragOver	LinkNotify	Paint

GotFocus	LinkOpen	Resize

KeyDown


Methods

Graphics methods are indicated with an asterisk (*).

*Circle	LinkRequest	Refresh

*Cls	LinkSend	*Scale

Drag	Move	SetFocus

*Line	*Point	*TextHeight

LinkExecute	*Print	*TextWidth

LinkPoke	*PSet	ZOrder


See Also

Help:

Data Access

Data Control

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 15, "Creating Graphics for Applications"


Text Box Control

See Also	Properties	Events	Methods

Description

A text box control, sometimes called an "edit field" or "edit control," can display information entered at design time, entered by the user, or assigned to the control in code at run time.

Remarks

To display multiple lines of text in a text box, set the MultiLine property to True.  If a multiline text box does not have a horizontal scroll bar, text in the box wraps automatically even when the text box is resized.  To customize the scroll bar combination on a text box, set the ScrollBars property.

A text box can also act as a destination link in a DDE conversation.


Properties

Alignment	ForeColor	Name

BackColor	Height	Parent

BorderStyle	HelpContextID	PasswordChar

DataField	HideSelection	ScrollBars

DataSource	hWnd	SelLength

DragIcon	Index	SelStart

DragMode	Left	SelText

Enabled	LinkItem	TabIndex

FontBold	LinkMode	TabStop

FontItalic	LinkTimeout	Tag

FontName	LinkTopic	Text

FontSize	MaxLength	Top

FontStrikethru	MousePointer	Visible

FontUnderline	MultiLine	Width


Events

Change	KeyDown	LinkOpen

Click	KeyPress	LostFocus

DblClick	KeyUp	MouseDown

DragDrop	LinkClose	MouseMove

DragOver	LinkError	MouseUp

GotFocus	LinkNotify


Methods

Drag	LinkRequest 	SetFocus

LinkExecute 	Move	ZOrder

LinkPoke	Refresh


See Also

Help:

Data Access

Data Control

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Timer Control

See Also	Properties	Events

Description

A timer can run code at a regular intervals by causing a Timer event.

Remarks

The timer, invisible to the user, is useful for background processing.

The timer's Enabled property cannot be set for a multiple selection of controls other than timers.


Properties

Enabled	Left	Tag

Index	Name	Top

Interval	Parent


Events

Timer


See Also

Help:

Drawing a Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Clipboard Object

Methods

Description

The Clipboard object is accessed with the keyword Clipboard, and is used to manipulate text and graphics on the Clipboard.  You can use this object to enable a user to copy, cut, and paste text or graphics in your application.

Remarks

The Clipboard can contain several pieces of data as long as each piece is in a different format.  For example, you can use the SetData method to put a bitmap on the Clipboard with the CF_BITMAP format, and then use the SetText method with the CF_TEXT format to put text on the Clipboard.  You can then use the GetText method to retrieve the text, or the GetData method to retrieve the picture.  Data on the Clipboard is lost when another set of data of the same format is placed on the Clipboard either through code or a menu command.


Methods

Clear	GetFormat	SetData

GetData	GetText	SetText


Debug Object

Methods

Description

The Debug object is accessed with the keyword Debug, and is used to send output to the Debug window at run time.


Method

Print


Printer Object

Properties	Methods

Description

The Printer object is accessed with the keyword Printer.  It is used to control text and graphics printed on a page and to send output directly to the default system printer.  For example, you can use this object to manipulate the appearance of your printed output by changing fonts.

Remarks

You may need to check and revise the layout of your forms if you want to print them.  When you use the Print method, graphical images are clipped at the bottom of the page and text is carried over to the next page.


Properties

CurrentX	FontName	ScaleHeight

CurrentY	Fonts	ScaleLeft

DrawMode	FontSize	ScaleMode

DrawStyle	FontStrikethru	ScaleTop

DrawWidth	FontTransparent	ScaleWidth

FillColor	FontUnderline	TwipsPerPixelX

FillStyle	ForeColor	TwipsPerPixelY

FontBold	hDC	Width

FontCount	Height

FontItalic	Page


Methods

Circle	NewPage	Scale

EndDoc	Print	TextHeight

Line	PSet	TextWidth


Screen Object

Properties

Description

The Screen object is accessed with the keyword Screen, and is used to manipulate forms according to their placement on the screen and to control the mouse pointer outside of your application's forms at run time.  For example, you could set the MousePointer property for the Screen object to the hourglass pointer while a modal form is displayed.


Properties

ActiveControl	Fonts	TwipsPerPixelX

ActiveForm	Height	TwipsPerPixelY

FontCount	MousePointer	Width


App Object

See Also	Properties

Description

The App object is a global object accessed with the App keyword.  It determines or specifies information about the application's title, the path and name of its executable and Help files, and whether or not there is a previous instance of the application running.

Remarks

The App object has no events or methods.


Properties

EXEName	PrevInstance

HelpFile	Title

Path


See Also

Help:

HelpContextID Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Image Control

See Also	Properties	Events	Methods

Description

Image is a graphical control that you can use to display a picture.

Remarks

The image control uses fewer resources and repaints faster than a picture box control, but it supports only a subset of the picture box properties, events, and methods.  Use the Stretch property to determine whether the picture is scaled to fit the control or vice versa.  Note that although you can place an image control within a container, an image control cannot act as a container.


Properties

BorderStyle	Height	Picture

DataField	Index	Stretch

DataSource	Left	Tag

DragIcon	MousePointer	Top

DragMode	Name	Visible

Enabled	Parent	Width


Events

Click	MouseDown

DblClick	MouseMove

DragDrop	MouseUp

DragOver


Methods

Drag	Refresh

Move	ZOrder


See Also

Help

Data Access

Data Control

Drawing a Control

Picture Box Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Line Control

See Also	Properties	Methods

Description

Line is a graphical control displayed as a horizontal, vertical, or diagonal line.

Remarks

You can use a line control at design time to draw lines on forms.  At run time, you can use a line control instead of, or in addition to, the Line method.  Lines drawn with the line control will remain on the form even if the AutoRedraw property is False.  Line controls can be displayed on forms, in picture boxes, and in frames.  You cannot use the Move method to move a line control at run time but you can move or resize it by altering its X1, X2, Y1, Y2 properties.  Note that the effect of setting the BorderStyle property depends on the setting of the Borderwidth property.  If BorderWidth is not 1 and BorderStyle is not 0 or 6, BorderStyle is set to 1.


Properties

BorderColor	Name

BorderStyle	Parent

BorderWidth	Tag

DrawMode	Visible

Index	X1, X2, Y1, Y2


Methods

Refresh

ZOrder


See Also

Help:

Drawing a Control

Frame Control

Line Method

Picture Box Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 15, "Creating Graphics for Applications"


Shape Control

See Also	Properties	Methods

Description

Shape is a graphical control displayed as a rectangle, square, oval, circle, rounded rectangle, or rounded square.

Remarks

Use shape controls at design time instead of, or in addition to, invoking Circle and Line methods at run time.  You can draw a shape control in a container but it cannot act as a container.  Note that the effect of setting the BorderStyle property depends on the setting of the Borderwidth property.  If BorderWidth is not 1 and BorderStyle is not 0 or 6, BorderStyle is set to 1.


Properties

BackColor	FillColor	Parent

BackStyle	FillStyle	Shape

BorderColor	Height	Tag

BorderStyle	Index	Top

BorderWidth	Left	Visible

DrawMode	Name	Width


Methods

Move

Refresh

ZOrder


See Also

Help:

Circle Method

Drawing a Control

Frame Control

Line Method

Picture Box Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 15, "Creating Graphics for Applications"


MDI Form

See Also	Properties	Events	Methods

Description

An MDI (Multiple-Document Interface) form is a window that acts as the background of an application and is the container for forms that have their MDIChild property set to True.

Remarks

You create an MDI form by choosing New MDI Form from the File menu.

An application can have only one MDI form but many MDI child forms.  If an MDI child form has menus, the child form's menu bar automatically replaces the MDI form's menu bar when the child form is active.  A minimized MDI child form appears as an icon within the MDI form.

MDI forms can contain only menu and picture box controls and custom controls that have an Align property.  To place other controls on an MDI form, you can draw a picture box on the form and then draw other controls inside the picture box.  You can use the Print method to display text in a picture box on an MDI form, but you can't use this method to display text on the MDI form itself.

An MDI form cannot be modal.

Note that MDI child forms are designed independently of the MDI form, but are always contained within the MDI form at run time.


Properties

ActiveForm	Icon	ScaleWidth

ActiveControl	Left	ScrollBars

Caption	LinkMode	Tag

Enabled	LinkTopic	Top

Height	MousePointer	Visible

HelpContextID	Name	Width

hWnd	ScaleHeight	WindowState


Events

Activate	LinkClose	Load

Deactivate	LinkError	QueryUnload

DragDrop	LinkExecute	Resize

DragOver	LinkOpen	Unload


Methods

Arrange	SetFocus

Hide	Show

Move	ZOrder


See Also

Help:

Creating a Menu Bar

Using MDI Features

Forms Collection

Specifying a Startup Form

Using Dynamic Data Exchange (DDE)

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 8, "Objects and Instances"

Chapter 14, "Multiple-Document Interface (MDI) Applications"


Forms Collection

See Also	Properties	Example

Description

A collection whose elements represent each loaded form in an application.  The collection includes the application's MDI form, MDI child forms, and non-MDI forms.  The Forms collection has a single property, Count, that specifies the number of elements in the collection.

Usage

Forms(index)[.control][.property][ = setting ]

Remarks

In the preceding syntax, the range of index is 0 to Forms.Count-1.  The Forms collection is useful for iterating through all loaded forms in an application.  Note that Forms is a keyword, but not a reserved word.  It identifies an intrinsic global variable named Forms.  You can use Forms(index) as an argument to a function with a parameter of type Form.


Properties

Count


See Also

Help:

Controls Collection

Dim Statement

Programmer's Guide:

Chapter 8, "Objects and Instances"


Forms Collection Example

The OBJECTS.MAK file referred to in Chapter 8 of the Programmer's Guide includes the following procedure to fill a list box with the captions of all the currently loaded forms:

Sub Form_Activate ()

Dim I	' Declare variable.

' Refill list (in case an instance was added or removed).

lstForms.Clear	' Clear list box.

For I = 0 To Forms.Count - 1

lstForms.AddItem Forms(I).Caption

Next I

End Sub


Controls Collection

See Also	Properties	Example

Description

A collection whose elements represent each control on a form, including elements of control arrays.  The Controls collection has a single property, Count, that specifies the number of elements in an array.

Usage

[form.]Controls(index)[.property][ = setting ]

form (index)[.property][ = setting ]

Remarks

The Controls collection enumerates loaded controls on a form and is useful for iterating through them.  The index in the syntax is between 0 and Controls.Count-1.  Note that Controls is a keyword but not a reserved word.  It identifies an intrinsic form-level variable named Controls.  If you omit the optional form reference, you must include the Controls keyword.  If you include a form reference, you can omit the Controls keyword.  For example, the following two lines have the same effect:

MyForm.Controls(6).Top = MyForm.Controls(5).Top + increment

MyForm(6).Top = MyForm(5).Top + increment

You can use Controls(index) as an argument to a function with a parameter of type Control.


Properties

Count


See Also

Help:

Forms Collection

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 8, "Objects and Instances"


Controls Collection Example

The OBJECTS.MAK file referred to in Chapter 8 of the Programmer's Guide includes the following procedure to enable all currently loaded controls on a form (except menus).

Sub EnableControlsOn (Frm As Form, State As Integer)

Dim I	' Declare variable.

For I = 0 To Frm.Controls.Count - 1

If TypeOf Frm.Controls(I) Is Not Menu Then

Frm.Controls(I).Enabled = State

End If

Next I

End Sub


Graphical Controls

See Also

Description

The graphical controls [image] image, label, line and shape [image] can improve the performance of your application by using fewer system resources than other controls.

Remarks

The graphical controls can't receive the focus or act as containers for other controls, and they have no hWnd property.  The graphical controls generally have fewer properties, recognize fewer events, and have fewer methods than other controls.  For example, an image control can display a picture but can't be the object of a graphics method (such as the Print, Line and Circle methods) as a picture box control can.

Graphical controls can be transparent.  For example, if you set label.Backstyle = 0 or shape.BackStyle = 0, objects that these controls are covering will become visible.  You can use the line and shape controls to draw lines and shapes at design time instead of using the Line and Circle methods at run time.


See Also

Help:

Image Control

Label Control

Line Control

Shape Control

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 15, "Creating Graphics for Applications"


Grid Control

See Also	Properties	Events	Methods

Description

A grid control displays a series of rows and columns.  The intersection of a row and column is a cell.  You can read and set the contents of each cell programmatically.

Remarks

You can put either text or a picture in any cell of a grid.

The Row and Col properties specify the current cell in a grid.  You can specify the current cell in code, or the user can change it at run time using the mouse or the arrow keys.  The Text property references the contents of the current cell.

If a cell's text is too long to be displayed in the cell, the text wraps to the next line within the same cell.  To display the wrapped text, you must increase the cell's column width (ColWidth property) or row height (RowHeight property).

Use the Cols and Rows properties to determine the number of columns and rows in a grid control.  A grid cannot have more than 2000 rows, or 400 columns.

When a new element of a control array is loaded at run time, the new element does not inherit the original control's run-time properties.

Note	Before you can use a grid control in your application, you must add GRID.VBX to your project using the Add File command on the File menu.  To automatically include GRID.VBX in new projects, put it in an AUTOLOAD.MAK file.  When distributing your application, you should install the GRID.VBX file in the user's Microsoft Windows \SYSTEM subdirectory.


See Also

Programmer's Guide:

Chapter 13, "Using the Grid Control"


Properties

BackColor	FontName	RowHeight

BorderStyle	FontSize	Rows

CellSelected	FontStrikethru	ScrollBars

Clip	FontUnderline	SelEndCol

Col	ForeColor	SelEndRow

ColAlignment	GridLines	SelStartCol

Cols	Height	SelStartRow

ColWidth	HelpContextID	TabIndex

DragIcon	HighLight	TabStop

DragMode	hWnd	Tag

Enabled	Index	Text

FillStyle	Left	Top

FixedAlignment	LeftCol	TopRow

FixedCols	Name	Visible

FixedRows	Parent	Width

FontBold	Picture

FontItalic	Row


Events

Click	KeyDown	MouseMove

DblClick	KeyPress	MouseUp

DragDrop	KeyUp	RowColChange

DragOver	LostFocus	SelChange

GotFocus	MouseDown


Methods

AddItem	RemoveItem

Drag	SetFocus

Move	ZOrder

Refresh


CellSelected Property

See Also	Example

Applies To

Grid.

Description

Determines whether the cell specified by the Col and Row properties (the active cell) is within the grid's selected region.  Not available at design time; read-only at run time.

Usage

[form.]grid.CellSelected

Setting

The CellSelected property settings are:

Setting 	Description

True 	The specified cell is within the selected area.

False	The specified cell is not within the selected area.

Remarks

This property allows you to determine whether the user has selected a specific cell or a specific range of cells.

At run time, the user can select a range of cells by clicking a cell and then dragging the mouse or by pressing the Shift key and using the arrow keys.

Use the SelEndCol, SelStartCol, SelEndRow, SelStartRow properties to determine the selected region.  Use the Col and Row properties to determine the active cell.

Data Type

Integer (Boolean)


See Also

Help:

Col, Row Properties

RowColChange Event

SelChange Event

SelEndCol, SelStartCol, SelEndRow, SelStartRow Properties

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


CellSelected Example

The example selects a cell at random and tells you whether it is selected or not when the grid is clicked.  To try this example, use the Add File command on the File menu to add GRID.VBX to the project, paste the code into the Declarations section of a new form, and then draw a grid and a label.  For the label, set AutoSize to True.  Press F5 to run the program.

Dim TRow As Integer

Dim TCol As Integer

Sub Form_Load ()

Grid1.Rows = 8	' Set rows and columns.

Grid1.Cols = 5

Randomize

' Choose a cell at random.

TRow = Int(Rnd * (Grid1.Rows - 1)) + 1

TCol = Int(Rnd * (Grid1.Cols - 1)) + 1

End Sub

Sub Grid1_Click ()

Grid1.Row = TRow

Grid1.Col = TCol

If Grid1.CellSelected Then

Label1.Caption = "You found it!"

Else

Label1.Caption = "Not yet. Try again."

End If

End Sub


Clip Property

See Also	Example

Applies To

Grid.

Description

Determines the contents of the cells in a grid's selected region.  Not available at design time.

Usage

[form.]grid.Clip[ = stringexpression ]

Remarks

The stringexpression can contain the contents of multiple rows and columns.  In stringexpression, a tab character (ANSI character 9) indicates a new cell in a row, and a carriage return (ANSI character 13) indicates the beginning of a new row.  Use the Chr function to embed these characters in strings.  For example, this line of code puts text into a selected area two rows high and two columns wide:

Grid1.Clip = "1st" & Chr(9) & "a" & Chr(13) & "2nd" & Chr(9) & "b"

When placing data into a grid, only the selected cells are affected. If there are more cells in the selected region than are described in stringexpression, the remaining cells are set to null. If there are more cells described in stringexpression than in the selected region, the unused portion of stringexpression is ignored.

Data Type

String


See Also

Help:

SelEndCol, SelStartCol, SelEndRow, SelStartRow Properties

Text Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Clip Property Example

The example puts the current date and time into the selected area of the grid when the user clicks the form.  To try this example, use the Add File command on the File menu to add GRID.VBX to a project, paste the code into the Declarations section of a new form, and then draw a grid.  Press F5 to run the program.

Sub Form_Load ()

Grid1.Rows = 8	' Set rows and columns.

Grid1.Cols = 5

End Sub

Sub Form_Click ()

Dim Msg As String

Msg = "Date" & Chr(9)	' Create a text string.

Msg = Msg & Format(Now, "Short Date") & Chr(13)

Msg = Msg & "Time" & Chr(9)

Msg = Msg & Format(Now, "Short Time")

Grid1.Clip = Msg	' Paste string into grid.

End Sub


Col, Row Properties

See Also	Example1	Example2

Apply To

Grid.

Description

Determine the active cell in a grid.  Not available at design time.

Usage

[form.]grid.Col[ = column ]

[form.]grid.Row[ = row ]

Remarks

Use these properties to specify a cell in a grid or to find out which row or column contains the active cell in a selected region.  Columns and rows are numbered from zero, beginning at the top for rows and at the left for columns.  Setting these properties at run time does not change which cells are selected.  Use SelEndCol, SelStartCol, SelEndRow, SelStartRow properties to specify a selected region.

Note	The Col, Row properties are not the same as the Cols, Rows properties.

Data Type

Integer


See Also

Help:

Clip Property

Cols, Rows Properties

SelEndCol, SelStartCol, SelEndRow, SelStartRow Properties

Text Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Col, Row Properties Example

The example puts "Here" into the current cell, and then changes the active cell to the third cell in the third row and puts "There" into that cell.  To try this example, use the Add File command on the File menu to add GRID.VBX to the project, and then draw a grid on a new form.  To run the program, press F5 and then click the grid.

Sub Form_Load ()

Grid1.Rows = 8	' Set rows and columns.

Grid1.Cols = 5

End Sub

Sub Grid1_Click ()

' Put text in current cell.

Grid1.Text = "Here"

' Put text in 3rd row, 3rd column.

Grid1.Col = 2

Grid1.Row = 2

Grid1.Text = "There"

End Sub


ColAlignment Property

See Also	Example

Applies To

Grid.

Description

Determines the alignment of data in a column.  Not available at design time.

Usage

[form.]grid.ColAlignment(column)[ = numericexpression ]

Setting

The ColAlignment property settings are:

Setting 	Description

0 	(Default) Left align

1	Right align

2	Center

Remarks

Any column can have an alignment that is different from other columns.  This property does not affect cells in a fixed row.  To set the alignment for a fixed column, use the FixedAlignment property.

Data Type

Integer (Enumerated)


See Also

Help:

Alignment Property

FixedAlignment Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


ColAlignment Property Example

The example fills a grid with the letter "m" and then sets the column alignment to right-aligned for every other column.  To try this example, use the Add File command on the File menu to add GRID.VBX to the project, and then draw a grid on a new form.  To run the program, press F5.

Sub Form_Load ()

Grid1.Cols = 5	' Set Cols and Rows.

Grid1.Rows = 8

' Select all cells

Grid1.SelStartCol = 1

Grid1.SelStartRow = 1

Grid1.SelEndCol = Grid1.Cols - 1

Grid1.SelEndRow = Grid1.Rows - 1

' Fill all cells with a letter

Grid1.FillStyle = 1	' Turn on FillStyle.

Grid1.Text = "m"

' Set ColAlignment for even numbered columns

For I = 2 To 4 Step 2

Grid1.ColAlignment(I) = 1	' Right align.

Next I

Grid1.FillStyle = 0	' Turn off FillStyle.

End Sub


Cols, Rows Properties

See Also	Example

Apply To

Grid.

Description

Determine the total number of columns or rows in a grid.  The minimum is 1.  The maximum number of rows is 2000; the maximum number of columns is 400.

Usage

[form.]grid.Cols[ = numericexpression ]

[form.]grid.Rows[ = numericexpression ]

Remarks

You can use these properties to expand a grid dynamically at run time.  A grid must have at least one non-fixed column and one non-fixed row.

Note	The Cols, Rows properties are not the same as the Col, Row properties.

Data Type

Integer


See Also

Help:

Col, Row Properties

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


ColWidth Property

See Also	Example

Applies To

Grid.

Description

Determines the width of the specified column in twips.  Not available at design time.

Usage

[form.]grid.ColWidth(column)[ = numericexpression ]

Remarks

You can use this property to set the width of any column at run time.  Users can also change the width of a column by positioning the mouse pointer between columns and then clicking and dragging.

Data Type

Long


See Also

Help:

RowHeight Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


ColWidth Property Example

The example allows the user to increase the column width of selected columns with the > key, and decrease the column width with the < key.  To try this example, create a new project, add GRID.VBX using the Add File command on the File menu, and then draw a grid.

Sub Form_Load ()

Grid1.Cols = 6	' Set columns and rows.

Grid1.Rows = 8

End Sub

Sub Grid1_KeyPress (KeyAscii As Integer)
Select Case KeyAscii
Case 62	' > key
' Get index for each selected column.
For I = Grid1.SelStartCol To Grid1.SelEndCol
' Increase column width.
Grid1.ColWidth(I) = Grid1.ColWidth(I) + 50
Next I
Case 60	' < key
'Get index for each selected column.
For I = Grid1.SelStartCol To Grid1.SelEndCol
'Decrease column width.
Grid1.ColWidth(I) = Grid1.ColWidth(I) - 50
Next I
End Select
End Sub


FixedAlignment Property

See Also	Example

Applies To

Grid.

Description

Determines the alignment of data in the fixed cells of a column.  Not available at design time.

Usage

[form.]grid.FixedAlignment(column)[ = numericexpression ]

Setting

The FixedAlignment property settings are:

Setting 	Description

0 	(Default) Left align.

1	Right align.

2	Center.

3	Use the ColAlignment setting for the column specified by the column index.

Remarks

This property operates like the ColAlignment property except that it only affects the alignment of fixed cells.  This is useful when you want to align headings differently from the rest of the columns.

Data Type

Integer (Enumerated)


See Also

Help:

ColAlignment Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


FixedAlignment Example

The example creates a spreadsheet with centered column headings and row numbers.  To try this example, create a new project, add GRID.VBX using the Add File command on the File menu, and then draw a grid.  Press F5 to run the program.

Sub Form_Load ()

Grid1.Cols = 5	' Set rows and columns.

Grid1.Rows = 7

Grid1.Row = 0

Grid1.FixedAlignment(0) = 2	' Set alignment of row numbers.

For I = 1 To Grid1.Cols - 1	' Set column letters & alignment.

Grid1.FixedAlignment(I) = 2

Grid1.Col = I

Grid1.Text = Chr(64 + I)

Next I

Grid1.Col = 0

For I = 1 To Grid1.Rows - 1	' Set row numbers.

Grid1.Row = I

Grid1.Text = I

Next I

End Sub


FixedCols, FixedRows Properties

See Also	Example

Apply To

Grid.

Description

Determine the total number of fixed columns or fixed rows for a grid.  By default, a grid has one fixed column and one fixed row.

Usage

[form.]grid.FixedCols[ = numericexpression ]

[form.]grid.FixedRows[ = numericexpression ]

Remarks

A fixed column is a stationary column on the left side of the grid. A fixed row is a stationary row along the top of the grid. You can have zero or more fixed columns and zero or more fixed rows.  Fixed columns and rows are displayed in gray and do not move when the other columns or rows in the grid are scrolled. You cannot change the color of a fixed column or row.

Fixed columns and rows are typically used in spreadsheet applications to display row numbers and column names or letters.

A grid must have at least one non-fixed column and one non-fixed row.  The maximum number of fixed columns or rows allowed in a grid is one less than the total number of columns or rows.

Data Type

Integer


See Also

Help:

Cols, Rows Properties

FixedAlignment Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


FixedCols, FixedRows Properties Example

The example illustrates a grid with two fixed rows and two fixed columns.  To try this example, create a new project, add GRID.VBX using the Add File command on the File menu, and then draw a grid.  To run the program, press F5.

Sub Form_Load ()

Grid1.Rows = 8	' Set columns and rows.

Grid1.Cols = 6

Grid1.FixedRows = 2	' Set fixed columns and rows.

Grid1.FixedCols = 2

End Sub


GridLines Property

See Also	Example

Applies To

Grid.

Description

Determines whether the lines between cells are visible.

Usage

[form.]grid.Gridlines[ = {True|False}]

Setting

The GridLines property settings are:

Setting 	Description

True 	(Default) Grid lines are visible.

False	Grid lines are not visible.

Data Type

Integer (Boolean)


See Also

Help:

Cols, Rows Properties

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


GridLines Property Example

The example turns the grid lines on and off as you click the form.  To try this example, create a new project, add GRID.VBX using the Add File command on the File menu, and then draw a grid.  Copy the code into the Declarations section and press F5 to run the program.

Sub Form_Load ()

Grid1.Cols = 6	' Set columns and rows.

Grid1.Rows = 7

End Sub

Sub Form_Click ()	' Toggle grid lines on and off.

Grid1.GridLines = Not Grid1.GridLines

End Sub


HighLight Property

See Also	Example

Applies To

Grid.

Description

Determines whether selected cells appear highlighted.

Usage

[form.]grid.Highlight[ = {True|False}]

Setting

The HighLight property settings are:

Setting 	Description

True 	(Default) Selected cells are highlighted.

False	Selected cells are not highlighted.

Remarks

When this property is set to False and the user selects a range of cells, there is no visual cue that shows which cells are currently selected.

Data Type

Integer (Boolean)


See Also

Help:

Col, Row Properties

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


HighLight Property Example

The example turns the highlighting on and off as you click the form.  To try this example, create a new project, add GRID.VBX using the Add File command on the File menu, and then draw a grid.  Copy the code into the Declarations section and press F5 to run the program.

Sub Form_Load ()

Grid1.Cols = 6	' Set columns and rows.

Grid1.Rows = 7

End Sub

Sub Form_Click ()	' Toggle highlighting on and off.

Grid1.HighLight = Not Grid1.HighLight

End Sub


LeftCol Property

See Also	Example

Applies To

Grid.

Description

Determines the leftmost visible column (other than a fixed column) in the grid.  Not available at design time.

Usage

[form.]grid.LeftCol[ = numericexpression ]

Remarks

You can use this property in code to scroll a grid programmatically.  Use the TopRow property to determine the topmost visible row in the grid.

Data Type

Integer


See Also

Help:

Col, Row Properties

TopRow Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


LeftCol Property Example

The example changes the LeftCol property with each click of the form.  To try this example, create a new project, add GRID.VBX using the Add File command on the File menu, and then draw a grid.  Copy the code into the Declarations section and press F5 to run the program.

Sub Form_Load ()

Grid1.Rows = 8	' Set columns and rows.

Grid1.Cols = 9

Grid1.Row = 0

For I = 1 To Grid1.Cols - 1	' Set numbers in column heads.

Grid1.Col = I

Grid1.Text = I

Next I

End Sub

Sub Form_Click ()

On Error GoTo LeftColError

' Scroll the grid by one column.

Grid1.LeftCol = Grid1.LeftCol + 1

On Error GoTo 0

Exit Sub

LeftColError:

Grid1.LeftCol = 1	' Display the first column.

Resume Next

End Sub


RowHeight Property

See Also	Example

Applies To

Grid.

Description

Determines the height of the specified row in twips.  Not available at design time.

Usage

[form.]grid.RowHeight(rownum)[ = numericexpression ]

Remarks

The minimum RowHeight is 1 pixel.  Users can change the RowHeight of any row at run time by placing the mouse pointer on a gridline between rows and then clicking and dragging.

Data Type

Long


See Also

Help:

ColWidth Property

Row Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


RowHeight Property Example

The example sets the height of the current row to 500 twips when you click the form.  To try this example, create a new project, add GRID.VBX using the Add File command on the File menu, and then draw a grid.  Copy the code into the Declarations section, press F5 to run the program, and then select a cell and click the form.

Sub Form_Load ()

Grid1.Rows = 5	' Set columns and rows.

Grid1.Cols = 7

End Sub

Sub Form_Click ()
Grid1.RowHeight(Grid1.Row) = 500
End Sub


SelEndCol, SelStartCol, SelEndRow, SelStartRow Properties

See Also	Example

Apply To

Grid.

Description

Determine the starting or ending row or column for a range of cells.  Not available at design time.

SelEndCol [image] the last selected column on the right.

SelStartCol [image] the first selected column on the left.

SelEndRow [image] the lowest selected row.

SelStartRow [image] the first selected row.

Usage

[form.]grid.SelEndCol[ = numericexpression ]

[form.]grid.SelStartCol[ = numericexpression ]

[form.]grid.SelEndRow[ = numericexpression ]

[form.]grid.SelStartRow[ = numericexpression ]

Remarks

You can use these properties to select a specific region of the grid from code, or to read into code the dimensions of an area that the user selects.

SelStartCol and SelStartRow together specify the cell in the upper-left corner of a selected range.  SelEndCol and SelEndRow specify the cell in the lower-right corner of a selected range.

To specify a cell without moving the current selection, use the Col and Row properties.

Data Type

Integer


See Also

Help:

Col, Row Properties

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


TopRow Property

See Also	Example

Applies To

Grid.

Description

Determines the uppermost row displayed in the grid.  Not available at design time.

Usage

[form.]grid.TopRow[ = numericexpression ]

Remarks

You can use this property in code to programmatically read or set the visible top row of the grid.  Use the LeftCol property to determine the leftmost visible column in the grid.

When setting this property, the largest possible row number is the total number of rows minus the number of rows that can be visible in the grid.  Attempting to set TopRow to a greater row number will generate an error.

Data Type

Integer


See Also

Help:

Col, Row Properties

LeftCol Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


TopRow Property Example

The example changes the TopRow property with each click on the form.  To try this example, create a new project, add GRID.VBX using the Add File command on the File menu, and then draw a grid.  Copy the code into the Declarations section and press F5 to run the program.

Sub Form_Load ()

' Set columns and rows.

Grid1.Cols = 6

Grid1.Rows = 12

' Put numbers in row heads.

Grid1.Col = 0

For I = 1 To Grid1.Rows - 1

Grid1.Row = I

Grid1.Text = I

Next I

End Sub

Sub Form_Click ()

On Error GoTo TopRowError

Grid1.TopRow = Grid1.TopRow + 1

On Error GoTo 0

Exit Sub

TopRowError:

Grid1.TopRow = 1

Resume Next

End Sub


SelChange Event

See Also	Example

Applies To

Grid.

Description

Occurs when the selected range changes to a different cell or range of cells.

Syntax

Sub grid_SelChange ( )

Remarks

The SelChange event occurs whenever the user clicks a cell other than the selected cell and as a user drags to select a new range of cells.  A user can also select a range of cells by pressing the Shift key and using the arrow keys.

You can trigger this event in code by changing the selected region using the SelEndCol, SelStartCol, SelEndRow, SelStartRow properties.

The RowColChange event also occurs when a user clicks a new cell but does not occur while a user drags the selection across the grid, or when you programmatically change the selection without moving the active cell.


See Also

Help:

RowColChange Event

SelEndCol, SelStartCol, SelEndRow, SelStartRow Properties

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


RowColChange Event

See Also	Example

Applies To

Grid.

Description

Occurs when the currently active cell changes to a different cell.

Syntax

Sub grid_RowColChange ( )

Remarks

This event occurs whenever the user clicks a cell other than the selected cell or when you programmatically change the active cell within a selection.

You can trigger this event in code by changing the current cell using the Col and Row properties.

The SelChange event also occurs when a user clicks a new cell, but does not occur when you programmatically change the selected range without changing the active cell.


See Also

Help:

SelChange Event

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


RowColChange, SelChange Events Example
Col, Row; Cols, Rows; SelEndCol, SelEndRow, SelStartCol, SelStartRow Properties Example

The example displays the location of the active cell and the range of the selection as a user selects cells or ranges.  Notice that when selecting a range, the active cell does not change.  Select a range and then click the form to move the active cell around the perimeter of the selection.  Notice that the selected range does not change.

To try this example, create a new project, add GRID.VBX using the Add File command on the File menu, and then draw a grid and two labels.  Copy the code into the Declarations section and press F5 to run the program.

Sub Form_Load ()

Grid1.Cols = 6	' Set columns and rows.

Grid1.Rows = 7

End Sub

Sub Grid1_RowColChange ()

Msg = "Active Cell: " & Chr(64 + Grid1.Col)

Mst = Msg & Grid1.Row

Label1.Caption = Msg

End Sub

Sub Grid1_SelChange ()

Msg = "Selection: " & Chr(64 + Grid1.SelStartCol)

Msg = Msg & Grid1.SelStartRow

Msg = Msg & ":" & Chr(64 + Grid1.SelEndCol)

Msg = Msg & Grid1.SelEndRow

Label2.Caption = Msg

End Sub

Sub Form_Click ()

' This procedure moves the active cell around

' the perimeter of the current selected range

' of cells with each click on the form.

Dim GR, GC As Integer

If Grid1.Row = Grid1.SelStartRow Then

If Grid1.Col = Grid1.SelEndCol Then

GR = 1: GC = 0

Else

GR = 0: GC = 1

End If

ElseIf Grid1.Row = Grid1.SelEndRow Then

If Grid1.Col = Grid1.SelStartCol Then

GR = -1: GC = 0

Else

GR = 0: GC = -1

End If

Else

If Grid1.Col = Grid1.SelStartCol Then

GR = -1: GC = 0

Else

GR = 1: GC = 0

End If

End If

Grid1.Row = Grid1.Row + GR

Grid1.Col = Grid1.Col + GC

End Sub


Microsoft Product Support Services

Microsoft offers a variety of support options to help you get the most from Visual Basic. This section summarizes these options.

If you have a question about your Microsoft product, first look in the printed product documentation, or consult Help. If you cannot find the answer, contact Microsoft Product Support.

Outside the United States, contact Microsoft Product Support Services at the Microsoft subsidiary office that serves your area.

Services Within the United States

Product Support Worldwide

Knowledge Base Articles on Visual Basic


See Also

Services Within the United States

Product Support Worldwide

Knowledge Base Articles on Visual Basic


Microsoft Product Support Services Within the United States

See Also

You can obtain product support in several ways, and locate additional training and consultation services in your area. You have the following means of obtaining product support:

Use the Microsoft Forum on CompuServe

Call Microsoft Product Support Services

Getting Product Training and Consultation Services

Microsoft TT (Text Telephone) Support

Use Microsoft Fee-Based Support Options

Use the Microsoft Download Service


Use the Microsoft Forum on CompuServe

See Also

Microsoft Product Support Services is available on several CompuServe forums. For an introductory CompuServe membership kit specifically for Microsoft users, dial (800) 848-8199 and ask for operator 230. If you are already a CompuServe member, type GO MSBASIC at any ! prompt.


Call Microsoft Product Support Services

See Also

You can reach Microsoft Product Support Services between 6:00 A.M. and 6:00 P.M. Pacific time, Monday through Friday, excluding holidays.

For setup and installation assistance with Microsoft Visual Basic, dial (206) 646 - 5105. This service is designed to get you up and running quickly with Visual Basic.

For how-to assistance and in-depth support for advanced programming issues, call Microsoft OnCall for Visual Basic at (900) 896 - 9876. The rate is $2 per minute. You can also obtain support by calling our credit card line for Visual Basic at the rate of $20 per call. To use this service, call (206) 646 - 5106. Please have your Visa, MasterCard, or American Express card ready.

When you call, you should be at your computer and have the appropriate product documentation at hand. Be prepared to give the following information:

The version number of the Microsoft product you are using

The type of hardware you are using

The exact wording of any messages that appeared on your screen

What happened and what you were doing when the problem occurred

How you tried to solve the problem


Use the Microsoft Download Service

See Also

Access technical notes and supplementary files covering common Visual Basic product support issues via modem on the Microsoft Download Service at (206) 646-5107.  This service is available 24 hours a day, seven days a week.


MS Text Telephone (TT/TDD) Support

See Also

Microsoft Product Support Services is available for the deaf and hard of hearing. Using a special TT modem, dial (206) 635-4948. Call between 6:00 A.M. and 6:00 P.M. Pacific time, Monday through Friday, excluding holidays.

Microsofts support services are subject to Microsoft prices, terms, and conditions in place at the time the service is used.


Use Microsoft Fee-Based Support Options

See Also

Microsoft offers a number of other comprehensive fee-based technical support options for Visual Basic users. For more information, call (800) 227 - 4679.

Note	Microsoft support services are subject to Microsoft prices, terms, and conditions in place at the time the service is used.


Getting Product Training and Consultation Services

See Also

The Microsoft Solution Providers program comprises strategic independent vendors who specialize in software development and customization, systems integration, consulting, and training. The program offers a new way for value-added resellers, systems integrators, trainers, and consultants to use Microsoft technology to deliver support, training, information, and educational opportunities. For more information about the program or the Microsoft Solution Provider nearest to you, please call (800) 227-4679 from 6:30 A.M. to 5:30 P.M. (Pacific time).


Microsoft Product Support Services Worldwide

See Also

When you call, you should be at your computer with Microsoft Visual Basic running and the product documentation at hand. Have your file open and be prepared to give the following information:

The version of Microsoft Visual Basic you are using.

The type of hardware you are using, including network hardware, if applicable.

The operating system you are using.

The exact wording of any messages that appeared on your screen.

A description of what happened and what you were trying to do when the problem occurred.

A description of how you tried to solve the problem.

See Microsoft Subsidiary Offices for listings of the offices and the countries they serve.

If there is no Microsoft office in your country, please contact the establishment from which you purchased your Microsoft product.


Microsoft Subsidiary Offices

Select a country for more information.

A

Argentina

Australia

Austria

B

Baltic States

Belgium

Bermuda

Bolivia

Brazil

C

Canada

Caribbean Countries

Central America

Chile

Colombia

D

Denmark

E

Ecuador

England

F

Finland

France

French Polynesia

G

Germany

Greece

H

Hong Kong

I

Ireland

Israel

Italy

J

Japan

K

Korea

L

Liechtenstein

Luxembourg

M

México

N

Netherlands

New Zealand

Northern Ireland

Norway

P

Papua New Guinea

Paraguay

Peru

Portugal

Puerto Rico

R

Republic of China

Republic of Ireland

S

Scotland

Spain

Sweden

Switzerland

U

Uruguay

V

Venezuela

W

Wales


Microsoft Product Support for Argentina, Bolivia, Paraguay, Uruguay
Argentina, Bolivia, Paraguay, Uruguay

Microsoft de Argentina S.A.
Phone: (54) (1) 814-0356
Fax: (54) (1) 814-0372


Microsoft Product Support for Australia, Papua New Guinea
Australia, Papua New Guinea

Microsoft Pty. Ltd.
Phone: (61) (02) 870-2200
Fax: (02) 805-1108
Bulletin Board Service: (61) (02) 870-2348
Technical Support: (61) (02) 870-2131
Sales Information Centre: (02) 870-2100


Microsoft Product Support for Austria
Austria

Microsoft Ges.m.b.H.
Phone: 0222 - 68 76 07
Fax: 0222 - 68 16 2710
Information: 0660 - 6520
Prices, updates, etc.: 0660 - 6520
CompuServe: GO MSEURO (Microsoft Central Europe)
Technical support:
COBOL PDS, Basic PDS, QuickBASIC, Visual Basic:
0660 - 6516
Windows, Windows for Workgroups, Microsoft Mail, Sound System, SoundBits:
0660 - 6510
Microsoft Excel for Windows, Microsoft Excel for OS/2, PowerPoint for Windows, Microsoft Cinemania, Microsoft Beethoven:
0660 - 6511
Word for MS-DOS, Windows Write, Microsoft Bookshelf:
0660 - 6512
Word for Windows, Word for OS/2, Microsoft Bookshelf:
0660 - 6513
Works for MS-DOS, Works for Windows, Publisher, WorksCalc, WorksText:
0660 - 6514
C PDS, FORTRAN PDS, Pascal, Macro Assembler PDS, QuickC, QuickC for Windows, QuickPascal, QuickAssembler, Profiler:
0660 - 6515
MS-DOS, MS-DOS Lernprogramm:
0660 - 6517
Microsoft Software für den Apple Macintosh:
0660 - 6518
Project for Windows, Money, Project for MS-DOS, Multiplan, Mouse, Flight Simulator, Paintbrush, Chart:
0660 - 6738
FoxPro, Access:
0660 - 6761


Microsoft Product Support for Belgium
Belgium

Microsoft NV
Phone:  02 - 7322590
Fax:  02 - 7351609
Technical Support Bulletin Board Service:  02 - 7350045
(1200/2400/9600 baud, 8 bits, no parity, 1 stop bit, ANSI terminal emulation)
(Dutch-speaking) Technical Support:  02 - 5133274
(English-speaking) Technical Support:  02 - 5023432
(French-speaking) Technical Support:  02 - 5132268
Technical Support Fax:  (31) 2503 - 24304


Microsoft Product Support for Brazil
Brazil

Microsoft Informatica Ltda.
Phone: (55) (11) 530-4455
Fax: (55) (11) 240-2205
Technical Support Phone: (55) (11) 533-2922
Technical Support Fax: (55) (11) 241-1157
Technical Support Bulletin Board Service: (55) (11) 543-9257


Microsoft Product Support for Canada
Canada

Microsoft Canada Inc.
Phone: 1 (416) 568-0434
Fax: 1 (416) 568-4689
Technical Support Phone: 1 (416) 568-3503
Technical Support Facsimile: 1 (416) 568-4689
Technical Support Bulletin Board Service: 1 (416) 507-3022

Text Telephone (TT/TDD): 1 (416) 568-9641


Microsoft Product Support for Chile
Chile

Microsoft Chile S.A.
Tel: 56 2 218 5771
Fax: 56 2 218 5747


Microsoft Product Support for Columbia
Columbia

Microsoft Colombia
Tel: (571) 618 2245 Soporte Tecnico: (571) 618 2255
Fax:(571) 618 2269


Microsoft Product Support for Denmark
Denmark

Microsoft Denmark AS
Phone: (45) (44) 89 01 00
Fax: (45) (44) 68 55 10


Microsoft Product Support for England, Ireland, Northern Ireland, Scotland
England, Ireland, Northern Ireland, Scotland

Microsoft Limited
Phone: (44) (734) 270000
Fax: (44) (734) 270002
Upgrades: (44) (81) 614-8000
Technical Support:

Main Line (All Products): (44) (734) 271000

Database Direct Support Line: (44) (734) 271126

MS-DOS Warranty Support: (44) (734) 271900

MS-DOS Fee Support Line: (44) (891) 315500

Bulletin Board Service: (44) (734) 270065 (2400 Baud)

Fax Information Service: (44) (734) 270080


Microsoft Product Support for Finland
Finland

Microsoft OY
Phone: (358) (0) 525 501
Fax: (358) (0) 522 955


Microsoft Product Support for France, French Polynesia
France, French Polynesia

Microsoft France
Phone: (33) (1) 69-86-46-46
Telex: MSPARIS 604322F
Fax: (33) (1) 64-46-06-60
Technical Support Phone: (33) (1) 69-86-10-20
Technical Support Fax: (33) (1) 69-28-00-28


Microsoft Product Support for Germany, Baltic States
Germany, Baltic States

Microsoft GmbH
Phone: 089 - 3176-0
Telex: (17) 89 83 28 MS GMBH D
Fax: 089 - 3176-1000
Information: 089 - 3176 1199
Prices, updates, etc.: 089 - 3176 1199
Bulletin board, device drivers, tech notes : Btx: microsoft# or *610808000#
CompuServe: GO MSEURO (Microsoft Central Europe)
Technical support:

Windows, Windows for Workgroups, Microsoft Mail, Sound System, SoundBits:
089 - 3176 - 1110
Microsoft Excel for Windows, Microsoft Excel for OS/2, PowerPoint for Windows, Microsoft Cinemania, Microsoft Beethoven:
089 - 3176 - 1120
Word for MS-DOS, Windows Write, Microsoft Bookshelf:
089 - 3176 - 1130
Word for Windows, Word for OS/2, Microsoft Bookshelf:
089 - 3176 - 1131
Works for MS-DOS, Works for Windows, Publisher, WorksCalc, WorksText:
089 - 3176 - 1140
C PDS, FORTRAN PDS, Pascal, Macro Assembler PDS, QuickC, QuickC for Windows, QuickPascal, QuickAssembler, Profiler:
089 - 3176 - 1150
COBOL PDS, Basic PDS, QuickBASIC, Visual Basic:
089 - 3176 - 1151
MS-DOS, MS-DOS Lernprogramm:
089 - 3176 - 1152
Microsoft Software für den Apple Macintosh:
089 - 3176 - 1160
Project for Windows, Money, Project for MS-DOS, Multiplan, Mouse, Flight Simulator, Paintbrush, Chart:
089 - 3176 - 1170
FoxPro, Access:
089 - 3176 - 1180


Microsoft Product Support for Greece
Greece

Microsoft Hellas, S.A.
Phone: (30) (1) 6896 663
Fax: (30) (1) 6896 662


Microsoft Product Support for Hong Kong
Hong Kong

Microsoft Hong Kong Limited
Technical Support: (852) 804-4222

Fax: (852) 560-2217


Microsoft Product Support for Israel
Israel

Microsoft Israel Ltd.

Phone: 972-3-575-7034
Fax: 972-3-575-7065


Microsoft Product Support for Italy
Italy

Microsoft SpA
Phone: (39) (2) 269121
Telex: 340321 I
Fax: (39) (2) 21072020
Customer Service (Prices, new products info, products literature): (39) (2) 26901359
Bulletin Board: (39) (2) 21072051
Technical Support:

Excel  Project:
(39) (2) 26901361
Word, Works:
(39) (2) 26901362
Windows, PowerPoint, Publisher, Windows for Workgroups, MS-DOS Update:
(39) (2) 26901363
Basic, COBOL, Visual Basic, Access, Fox Products:
(39) (2) 26901364
C, FORTRAN, Pascal, Macro Assembler (MASM), and SDKs:
(39) (2) 26901354
LAN Manager, SQL Server, Microsoft Mail, Microsoft Mail Gateways:
(39) (2) 26901356


Microsoft Product Support for Japan
Japan

Microsoft Company Ltd.

Tokyo Japan

Phone: (81) (3) 5454-8025
Fax: (81) (3) 5454-7972
Apps product:

Multiplan: (81) (3) 5454-2310
Works: (81) (3) 5454-2311
Chart: (81) (3) 5454 2312
Excel for Windows: (81) (3) 5454-2320
Word for Windows: (81) (3) 5454-2321

Windows:

MS Windows: (81) (3) 5454 2330

Macintosh Excel: (81) (3) 5454-2340
Word for Mac: (81) (3) 5454-2341
Mail for Mac: (81) (3) 5454 2342
Quick Basic for Mac: (81) (3) 5454-2343
Other Mac Products: (81) (3) 5454-2349

Languages:

Basic: (81) (3) 5454-2350
Quick Basic: (81) (3) 5454 2351
Visual Basic: (81) (3) 5454 2352
Fortran: (81) (3) 5454 2353
Masm: (81) (3) 5454 2360
C: (81) (3) 5454 2361
Quick C: (81) (3) 5454 2362

PSS Technical Support Fax: (81) (3) 5454-7955

Customer Service Phone (Version upgrade/Registration)
Phone: (81) (3) 5454 2305 Fax: (81) (3) 5454-7952
Channel Marketing (Pre-sales Product Support) Information Center Phone: (81) (3) 5454-2300
Fax: (81) (3) 5454 7951


Microsoft Product Support for Korea
Korea

Microsoft CH
Phone: (82) (2) 552-9505
Fax: (82) (2) 555-1724
Technical Support: (82) (2) 563-9230


Microsoft Product Support for Luxemburg
Luxembourg

Microsoft NV
Phone: (32) 2-7322590
Fax: (32) 2-7351609
Technical Support Bulletin Board Service: (31) 2503-34221 (1200/2400/9600 baud,
8 bits, No parity, 1 stop bit, ANSI terminal emulation)
(Dutch speaking) Technical Support: (31) 2503-77877
(English speaking) Technical Support: (31) 2503-77853
(French speaking) Technical Support: (32) 2-5132268
Technical Support Fax: (31) 2503-24304


Microsoft Product Support for México
México

Microsoft México, S.A. de C.V.
Phone: (52) (5) 325-0910
Fax: (52) (5) 280-7940
Technical Support: (52) (5) 325-0912
Sales: (52) (5) 325-0911


Microsoft Product Support for Netherlands
Netherlands

Microsoft BV
Phone: 02503-13181
Fax: 02503-37761
Technical Support Bulletin Board Service: 02503-34221 (1200/2400/9600 baud, 8 bits,
No parity, 1 stop bit, ANSI terminal emulation)
(Dutch speaking) Technical Support: 02503-77877
(English speaking) Technical Support: 02503-77853
Technical Support Fax: 02503-24304


Microsoft Product Support for New Zealand
New Zealand

Technology Link Centre
Phone: 64 (9) 358-3724
Fax: 64 (9) 358-3726
Technical Support Applications: 64 (9) 357-5575


Microsoft Product Support for Norway
Norway

Microsoft Norway AS
Phone: (47) (2) 95 06 65
Fax: (47) (2) 95 06 64
Technical Support: (47) (2) 18 35 00


Microsoft Product Support for Portugal
Portugal

MSFT, Lda.
Phone: (351) 1 4412205
Fax: (351) 1 4412101


Microsoft Product Support for Republic of China
Republic of China

Microsoft Taiwan Corp.
Phone: (886) (2) 504-3122
Fax: (886) (2) 504-3121

Technical Support : (886) (2) 504-3188


Microsoft Product Support for Spain
Spain

Microsoft Iberica SRL
Phone: (34) (1) 804-0000
Fax: (34) (1) 803-8310
Technical Support: (34) (1) 803-9960


Microsoft Product Support for Sweden
Sweden

Microsoft AB
Phone: (46) (8) 752 56 00
Fax: (46) (8) 750 51 58
Technical Support:
Applications: (46) (8) 752 68 50
Development and Network products: (46) (8) 752 60 50
MS-DOS: (46) (071) 21 05 15 (SEK 4.55/min)
Sales Support: (46) (8) 752 56 30
Bulletin Board Service: (46) (8) 750 47 42
Fax Information Service: (46) (8) 752 29 00


Microsoft Product Support for Leichtenstein, Switzerland
Leichtenstein, Switzerland

(German-speaking)
Microsoft AG
Phone: 01 - 839 61 11
Fax: 01 - 831 08 69
Written Information: Phone: 155 59 00 Fax: 064 - 224294, Microsoft Info-Service, Postfach, 8099 Zürich
Prices, updates, etc.: 01/839 61 11
CompuServe: GO MSEURO(Microsoft Central Europe)
Technical support: (German speaking)
Windows, Windows for Workgroups, Microsoft Mail, Sound System, SoundBits:
01 - 342 - 4085
Microsoft Excel for Windows, Microsoft Excel for OS/2, PowerPoint for Windows, Microsoft Cinemania, Microsoft Beethoven:
01 - 342 - 4082
Word for MS-DOS, Windows Write, Microsoft Bookshelf:
01 - 342 - 4083
Word for Windows, Word for OS/2, Microsoft Bookshelf:
01 - 342 - 4087
Works for MS-DOS, Works for Windows, Publisher, WorksCalc, WorksText:
01 - 342 - 4084
C PDS, FORTRAN PDS, Pascal, Macro Assembler PDS, QuickC, QuickC for Windows, QuickPascal, QuickAssembler, Profiler:
01 - 342 - 4036
COBOL PDS, Basic PDS, QuickBASIC, Visual Basic:
01 - 342 - 4086
MS-DOS, MS-DOS Lernprogramm:
01 - 342 - 2152
Microsoft Software für den Apple Macintosh:
01 - 342 - 4081
Project for Windows, Money, Project for MS-DOS, Multiplan, Mouse, Flight Simulator, Paintbrush, Chart:
01 - 342 - 0322
FoxPro, Access:
01 / 342 - 4121

Technical support: (French speaking) 022 - 738 96 88


Microsoft Product Support for Bermuda, Caribbean Countries, Central America, Colombia, Ecuador, Peru, Puerto Rico, Venezuela
Bermuda, Caribbean Countries, Central America, Ecuador, Peru, Puerto Rico, Venezuela

Corporation MS 90 de Venezuela S.A.
Phone: 0058.2.914739
Fax: 0058.2.923835


Archive, Hidden, Normal, System Properties

See Also

Apply To

File list box.

Description

Determine whether a file list box contains files with Archive, Hidden, Normal, or System attributes.

Usage

[form.]filelistbox.Archive[ = boolean ]

[form.]filelistbox.Hidden[ = boolean ]

[form.]filelistbox.Normal[ = boolean ]

[form.]filelistbox.System[ = boolean ]

Setting

The property settings are:

Setting	Description

True	(Default for Archive, and Normal) Displays files with the property's attribute in the file list box.

False	(Default for Hidden and System) Does not display files with the property's attribute in the file list box.

Remarks

Use these properties to specify which kinds of files to display in a file list box, based on standard file attributes used in the operating environment. Setting any of these properties with code at run time resets the list to display only those files with the corresponding attributes.

For example, in a search-and-replace operation you might want to display only System files by setting the System property to True, and the other properties to False.  Or, as part of a file backup procedure, you might set the Archive property to True to list only those files modified since the previous backup.

Data Type

Integer (Boolean)


See Also

Help:

Path Property

Pattern Property

ReadOnly Property

Programmer's Guide:

Chapter 18, "Using the File-System Controls"

Chapter 19, "Processing Files"


Checked Property

See Also	Example

Applies To

Menu.

Description

Determines whether a check mark is displayed next to a menu command.

Usage

menuitem.Checked[ = boolean ]

Setting

The Checked property settings are:

Setting	Description

True	Places a check mark next to a menu command.

False	(Default) Removes a check mark from a menu command.

Remarks

You can use code to set the Checked property at run time [image] for example, as part of a Click event procedure attached to a menu control.  You might also set the value of this property in a startup procedure or in a form's Load event procedure.

Data Type

Integer (Boolean)


See Also

Help:

Creating a Menu Bar

Enabled Property

Visible Property

Programmer's Guide:

Chapter 4, "Menus and Dialogs"


Checked Property Example

The example displays and removes a check mark next to a menu item.  To try this example, create a form with a menu having one command (set both Caption and Name = "MyMenuItem"). Then Press F5 and choose the menu item.

Sub MyMenuItem_Click ()
' Turn check mark on menu command on and off.
MyMenuItem.Checked = Not MyMenuItem.Checked
End Sub


ControlBox Property

See Also

Applies To

Form.

Description

Specifies whether a Control-menu box appears on a form at run time; read-only at run time.

Usage

[form.]ControlBox

Setting

The ControlBox property settings are:

Setting	Description

True	(Default) Displays the Control-menu box.

False	Removes the Control-menu box.

Remarks

To display a Control-menu box, you must also set the form's BorderStyle property to 1 (Fixed Single), 2 (Sizable), or 3 (Fixed Double).

Both modal and modeless windows can include a Control-menu box.  The commands available at run time depend on the settings for related properties [image] for example, setting MaxButton and MinButton to False disables the Maximize and Minimize commands on the Control menu, but the Move and Close commands remain available.

In Microsoft Windows version 3.0, an MDI child form appears with a Control-menu box regardless of the ControlBox setting.  However, if ControlBox is False, the menu appears without Close or Next commands.

Note	Settings you specify for ControlBox, BorderStyle, MaxButton, and MinButton are not reflected in the form's appearance until run time.

Data Type

Integer (Boolean)


See Also

Help:

BorderStyle Property

MaxButton Property

MinButton Property

Programmer's Guide:

Chapter 4, "Menus and Dialogs"


DragIcon Property

See Also	Example

Applies To

Check box, combo box, command button, data control, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, list box, OLE control, option button, picture box, text box, vertical scroll bar.

Description

Determines the icon to be displayed as the pointer in a drag-and-drop operation.

Usage

[form.]control.DragIcon[ = icon ]

Where icon is any code that returns a valid icon, such as a reference to a form's icon (Form1.Icon), a reference to another control's DragIcon property (Text1.DragIcon), or the LoadPicture function.

Setting

The DragIcon property settings are:

Setting	Description

(none)	(Default) An arrow pointer inside a rectangle.

Icon	A custom mouse pointer.  You specify the icon by loading it using the Properties window at design time.  You can also use the LoadPicture function at run time.  The file you load must have the .ICO file-name extension and format.

Remarks

DragIcon is useful for providing visual feedback during a dragging operation [image] for example, to indicate that the source control is over an appropriate target.  DragIcon takes effect when the user initiates dragging.  Typically, you set DragIcon as part of a MouseDown or DragOver event procedure.

Note	At run time, the DragIcon property can be set to any object's DragIcon or Icon property, or you can assign it an icon returned by the LoadPicture function.

Data Type

Integer


See Also

Help:

Drag Method

DragDrop Event

DragMode Property

LoadPicture Function

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"

Appendix B, "Icon Library"


DragIcon Property Example

The example changes the drag icon each time you drag a picture control.  To try this example, paste the code into the Declarations section of a form that contains a picture control.  Set DragMode = 1. Then press F5 and click and drag the picture control.

Sub Form_DragDrop (Source As Control, X As Single, Y As Single)
Dim Pic	' Declare variable.
Source.Move X, Y	' Set position of control.
Pic = "icons\office\crdfle01.ico"	' Get name of icon file.
If Source.DragIcon = False Then	' If no picture loaded.
Source.DragIcon = LoadPicture(Pic)' Load picture.
Else
Source.DragIcon = LoadPicture()	' Unload picture.
End If

End Sub


DragMode Property

See Also	Example

Applies To

Check box, combo box, command button, data control, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, list box, OLE control, option button, picture box, text box, vertical scroll bar.

Description

Determines manual or automatic dragging mode for a drag-and-drop operation.

Usage

[form.]control.DragMode[ = mode ]

Setting

The DragMode property settings are:

Setting	Description

0	(Default) Manual; requires using the Drag method to initiate dragging on the source control.

1	Automatic; clicking the source control automatically initiates dragging.

Remarks

When DragMode is set to 1 (Automatic), the control does not respond as usual to mouse input messages.  Use the 0 (Manual) setting to determine when dragging begins or ends; this is useful for initiating dragging in response to a keyboard or menu command, or for allowing a source control to recognize a MouseDown event prior to dragging.

Clicking while the mouse pointer is over a target control or form during a drag operation generates a DragDrop event for the target object.  This ends the drag operation.  Dragging may also generate a DragOver event.

Note	While a control is being dragged, it cannot recognize other user-initiated mouse or keyboard events (KeyDown, KeyPress or KeyUp, MouseDown, MouseMove, or MouseUp).  However, the control can receive events initiated by code or by a DDE link.

Data Type

Integer (Enumerated)


See Also

Help:

DragDrop Event

DragIcon Property

DragOver Event

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"


DragMode Property Example

This example enables and disables the ability to drag a command button each time a form is clicked.  To try this example, paste the code into the Declarations section of a form that contains a command button.  Then press F5 and click the form.

Sub Form_Click ()

If Command1.DragMode = 0 Then	' Check DragMode.
Command1.DragMode = 1	' Turn it on.
Else
Command1.DragMode = 0	' Or turn if off.
End If
End Sub


DrawMode Property

See Also	Example

Applies To

Form, line, picture box, Printer object, shape.

Description

Determines the appearance of output from graphics methods, or the appearance of a shape or line control.

Usage

{[form.][control.]|Printer.}DrawMode[ = mode ]

Setting

The DrawMode property settings are:

Setting	Description

1	Black Pen.

2	Inverse of setting 15 (Merge Pen) [image] NotMergePen.

3	Combination of the colors common to the background color and the inverse of the pen [image] Mask Not Pen.

4	Inverse of setting 13 (Copy Pen) [image] NotCopyPen.

5	Combination of the colors common to both the pen and the inverse of the display [image] MaskPenNot.

6	Inverse of the display color [image] Invert.

7	Combination of the colors in the pen and in the display color, but not in both [image] XorPen.

8	Inverse of setting 9 (Mask Pen) [image] NotMaskPen.

9	Combination of the colors common to both the pen and the display [image] MaskPen.

10	Inverse of setting 7 (Xor Pen) [image] NotXorPen.

11	No operation [image] output remains unchanged.  In effect, this setting turns drawing off [image] Nop.

12	Combination of the display color and the inverse of the pen color [image] MergeNotPen.

13	(Default) Color specified by the ForeColor property [image] CopyPen.

14	Combination of the pen color and the inverse of the display color [image] MergePenNot.

15	Combination of the pen color and the display color [image] MergePen.

16	White Pen.

Remarks

Use this property to produce visual effects with shape or line controls or when drawing with the graphics methods.  Visual Basic compares each pixel in the draw pattern to the corresponding pixel in the existing background, and then it applies bit-wise operations.  For example, setting 7 (Xor Pen) uses the Xor operator to combine a draw pattern pixel with a background pixel.

The exact effect of a DrawMode setting depends on the way the color of a line drawn at run time combines with colors already on the screen.  Settings 1, 6, 7, 11, 13, and 16 yield perhaps the most predictable results.

Data Type

Integer (Enumerated)


See Also

Help:

DrawStyle Property

DrawWidth Property

FillColor Property

FillStyle Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


DrawMode Property Example

The example enables drawing on a form by dragging the mouse pointer.  Each mouse click sets a different draw mode.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Load
DrawWidth = 10	' Set DrawWidth.
End Sub

Sub Form_Click ()
Static M As Integer	' Current DrawMode setting.
ForeColor = QBColor(Int(Rnd * 15))	' Choose a color.
M = ((M + 1) Mod 16) + 1	' Keep DrawMode 16 or less.
DrawMode = M	' Set DrawMode.
End Sub

Sub Form_MouseMove (Button As Integer, Shift As Integer, X As Single, Y As Single)
If Button Then	' While the button is pressed,
PSet (X, Y)	' draw a big point.
End If
End Sub


DrawStyle Property

See Also	Example

Applies To

Form, picture box, Printer object.

Description

Determines the line style for output from graphics methods.

Usage

{[form.][picturebox.]|Printer.}DrawStyle[ = style ]

Setting

The DrawStyle property settings are:

Setting	Description

0	(Default) Solid

1	Dash

2	Dot

3	Dash-Dot

4	Dash-Dot-Dot

5	Transparent

6	Inside Solid

Remarks

If DrawWidth is set to a value greater than 1, then DrawStyles 1 through 4 produce a solid line (the DrawStyle property value is not changed).  If DrawWidth is set to 1, DrawStyle produces the effect described above for each setting.

Data Type

Integer (Enumerated)


See Also

Help:

Circle Method

DrawMode Property

FillColor Property

FillStyle Property

ForeColor Property

Line Method

PSet Method

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


DrawStyle Property Example

The example draws seven lines across a form, with each line displaying a different DrawStyle.  (If you set AutoRedraw = True, the form accumulates a new set of lines each time you resize it and then click it.)  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()
Dim I	' Declare variable.
ScaleHeight = 8	' Divide height by 8.
For I = 0 To 6
DrawStyle = I	' Change style.
Line (0, I + 1) - (ScaleWidth, I + 1)	' Draw new line.
Next I
End Sub


DrawWidth Property

See Also	Example

Applies To

Form, picture box, Printer object.

Description

Determines the line width for output from graphics methods.

Usage

{[form.][picturebox.]|Printer.}DrawWidth[ = size ]

Setting

You can set DrawWidth to a value of 1 through 32,767.  This value represents the width of the line in pixels.  The default is 1, or 1 pixel wide.

Remarks

Increase the value of this property to increase the width of the line.  If DrawWidth is greater than 1, DrawStyle property settings 1 through 4 produce a solid line (the DrawStyle property value isn't changed).  Setting DrawWidth to 1 allows DrawStyle to produce the results shown in the DrawStyle property table.

Data Type

Integer


See Also

Help:

Circle Method

DrawMode Property

DrawStyle Property

FillColor Property

FillStyle Property

ForeColor Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


DrawWidth Property Example

The example draws a gradually thickening line across a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()
Dim I	' Declare variable.
DrawWidth = 1	' Set starting pen width.
PSet (0, ScaleHeight / 2)	' Set starting point.
ForeColor = QBColor(5)	' Set pen color.
For I = 1 To 100 Step 10	' Set up loop.
DrawWidth = I	' Reset pen width.
Line - Step(ScaleWidth / 10, 0)	' Draw a line.
Next I
End Sub


Drive Property

See Also	Example

Applies To

Drive list box.

Description

Determines the selected drive at run time; not available at design time.

Usage

drivelistbox.Drive[ = drivespec]

Remarks

The valid range for the Drive property includes all drives present in or connected to the system when the control is created or refreshed at run time.  The Drive property defaults to the current drive.

When reading this property, the selected drive is returned in one of the following formats:

Floppy disks [image] "a:" or "b:", and so on.

Fixed media [image] "c: [volume id]"

Network connections [image] "x: \\server\share"

When setting this property:

Only the first character of the string is significant (the string is not case-sensitive).

Changing the setting for Drive causes a Change event.

Selecting a drive that is not present causes an error.

Setting this property also regenerates the drive list, providing a way in code to track network connections added since the control was created.

If the FileName property is set to a qualified network path without a drive designation, the value of the Drive property is an empty string (""), no drive is selected, and the ListIndex property is -1.

Note	The Drive property returns a different value from the ListIndex, which returns the list box selection.

Data Type

String


See Also

Help:

FileName Property

Path Property

PathChange Event

Pattern Property

PatternChange Event

Programmer's Guide:

Chapter 18, "Using the File-System Controls"

Chapter 19, "Processing Files"


Drive Property Example

The example displays a list of files for the current drive and directory.  To try this example, paste the code into the Declarations section of a form that contains a drive list box, a directory list box and a file list box..  Then press F5.  Use the mouse to change the drive or directory.

Sub Drive1_Change ()
Dir1.Path = Drive1.Drive	' When Drive changes, set Dir path.
End Sub
Sub Dir1_Change ()
File1.Path = Dir1.Path	' When Dir changes, set File path.
End Sub


Enabled Property

See Also	Example

Applies To

Form, MDI form, check box, combo box, command button, data control, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, list box, menu, option button, picture box, text box, timer, vertical scroll bar.

Description

Determines whether the form or control can respond to user-generated events.

Usage

[form.][control.]Enabled[ = boolean ]

Setting

The Enabled property settings are:

Setting	Description

True	(Default) Allows the object to respond to events.

False	Prevents the object from responding to events.

Remarks

This property allows forms and controls to be enabled or disabled at run time.  For example, you can disable objects that don't apply to the current state of the application.  You can also disable a control used purely for display purposes, such as a text box that provides read-only information.

Disabling a timer by setting Enabled to False suspends the countdown set up by the control's Interval property.

Data Type

Integer (Boolean)


See Also

Help:

Interval Property

Visible Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Enabled Property Example

The example enables a command button whenever the text box contains text.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and type something into the text box.

Sub Form_Load ()
Text1.Text = ""	' Clear the text box.
Command1.Caption = "Save"	' Put caption on button.
End Sub

Sub Text1_Change ()
If Text1.Text = "" Then	' See if textbox is empty.
Command1.Enabled = False	' Disable button.
Else
Command1.Enabled = True	' Enable button.
End If
End Sub


FileName Property

See Also	Example

Applies To

Common dialog, file list box.

Description

Determines the path and file name of a selected file.  Not available at design time.

Usage

[form.] {commondialog | filelistbox}.FileName[ = filename ]

Remarks

The FileName property is set to a null string (""), meaning no currently selected file, when the control is created at run time.

In the common dialog control, you can set the FileName property before opening the dialog in order to set an initial file name.

Reading this property returns the currently selected file name from the list.  The path is retrieved separately, using the Path property.  The value is functionally equivalent to List(ListIndex).  If no file is selected, FileName returns a null string ("").

When setting this property:

Including a drive, path, or pattern in the string changes the Drive, Path, and Pattern properties accordingly.

Including the name of an existing file (without wildcard characters) in the string selects the file.

Changing the value of this property may also cause one or more of these events:  PathChange (if you change the path); PatternChange (if you change the pattern); or DblClick (if you've assigned an existing file name).

This property can be a qualified network path and filename using this syntax: \\servername\sharename\filename.

Data Type

String


See Also

Help:

Drive Property

List Property

ListIndex Property

Path Property

PathChange Event

Pattern Property

PatternChange Event

Programmer's Guide:

Chapter 18, "Using the File-System Controls"

Chapter 19, "Processing Files"


FileName Property Example

The example displays a message in a label when a file name in a file list box is double-clicked.  To try this example, paste the code into the Declarations section of a form that contains a label, a directory list box, and a file list box..  Then press F5 and double-click any file name in the file list box.

Sub Dir1_Change ()
File1.Path = Dir1.Path	' Set File1 path.
End Sub
Sub File1_PathChange ()
Dir1.Path = File1.Path	' Set Dir1 path.
End Sub
Sub File1_DblClick ()
' Display the selected file name when DblClicked.
Label1.Caption = "Your selection: " + UCase(File1.FileName)
End Sub


FillColor Property

See Also	Example

Applies To

Form, picture box, Printer object, shape.

Description

Determines the color used to fill in shapes; also used to fill in circles and boxes created with the Circle and Line graphics methods.

Usage

{[form.][control.]|Printer.}FillColor[ = color ]

Setting

The FillColor property settings are:

Setting	Description

Normal RGB colors	Colors set with the RGB or QBColor functions in code.

System default colors	Colors specified with the system color constants from CONSTANT.TXT, a Visual Basic file that you can load into a module.  The Windows environment substitutes the user's choices, as specified through the user's Control Panel settings.

By default, FillColor is set to 0 (black).

Remarks

When the FillStyle property is set to its default, 1 (Transparent), the FillColor setting is ignored.

Data Type

Long


See Also

Help:

BackColor, ForeColor Properties

FillStyle Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


FillColor Property Example

The example constructs a circle on your form with random FillColors and FillStyles as you click your mouse button.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)
FillColor = QBColor(Int(Rnd * 15))	' Choose random FillColor.
FillStyle = Int(Rnd * 8)	' Choose random FillStyle.
Circle (X, Y), 250	' Draw a circle.
End Sub


FontCount Property

See Also	Example

Applies To

Printer object, Screen object.

Description

Specifies the number of fonts available for the current display device or currently active printer; not available at design time and read-only at run time.

Usage

{Printer|Screen}.FontCount

Remarks

Use this property with the Fonts property to see a list of available screen or printer fonts.  Fonts available in Visual Basic vary according to your system configuration, display devices, and printing devices.

Data Type

Integer


See Also

Help:

FontName Property

Fonts Property

Programmer's Guide:

Chapter 16, "Displaying and Printing Information"


FontCount Property Example

The example prints a list of the printer fonts in a list box.  To try this example, paste the code into the Declarations section of a form that has a list box control named List1.  Then Press F5  and click the form.

Sub Form_Click ()
Dim I	' Declare variable.
For I = 0 To Printer.FontCount -1	' Determine number of fonts.
List1.AddItem Printer.Fonts (I)	' Put each font into list box.
Next I
End Sub


hDC Property

See Also	Example

Applies To

Form, common dialog, picture box, Printer object.

Description

Specifies a handle provided by the Windows environment  to the device context of an object; not available at design time and read-only at run time.

Usage

{[form.] [commondialog. | picturebox. ] | Printer.}hDC

Remarks

This property is a Microsoft Windows environment device context handle.  The Windows environment manages the system display by assigning a device context for the Printer object and for each form and picture box in your application.  You can refer to the handle for an object's device context with the hDC property, which provides a value to pass to Windows API calls.

With a common dialog control, this property returns a device context for the printer selected in the Print dialog box when the PD_RETURNDC flag is set, or an information context when the PD_RETURNIC flag is set.

Note	The value of the hDC property can change while a program is running.  Therefore, you should not store the value in a variable; instead, use the hDC property each time you need it.

The AutoRedraw property can cause hDC to change.  If AutoRedraw for a form or picture box is set to True, hDC acts as a handle to the device context of the persistent bitmap (equivalent to the Image property).  When AutoRedraw is False, hDC is the actual hDC value of the Form window and the picture box window.  Note that hDC may change while the program is running regardless of the AutoRedraw setting.

Data Type

Integer


See Also

Help:

hWnd Property

Icon Property

Programmer's Guide:

Chapter 22, "Calling Procedures in DLLs"


hDC Property Example

The example draws a triangle, and then uses a Windows function to fill it with color.  Be sure that the declaration appears on one line with no break or wordwrap in the form module.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

' Declaration of Windows routine.
Declare Sub FloodFill Lib "GDI" (ByVal hDC As Integer, ByVal X As Integer, ByVal Y As Integer, ByVal Color As Long)
Sub Form_Click ()
ScaleMode = 3	' Windows draws in pixels.
ForeColor = 0	' Set draw line to black.
Line (100, 50)-(300, 50)	' Draw a triangle.
Line -(200, 200)
Line -(100, 50)
FillStyle = 0	' Set FillStyle to solid.
FillColor = RGB(128, 128, 255)	' Set FillColor.
FloodFill hDC, 200, 100, ForeColor	' Call Windows API to fill.
End Sub


Icon Property

See Also	Example

Applies To

Form, MDI form.

Description

Determines the icon displayed for a form at run time when the form is minimized.

Usage

[form.]Icon

Remarks

Use this property to specify a custom icon for any form that the user can minimize at run time.  For example, you can assign a unique icon to a form to indicate the form's function.  Specify the icon by loading it using the Properties window at design time.  The file you load must have the .ICO file-name extension and format.  If you don't specify a custom icon, the Visual Basic default icon for forms will be used.

You can use Visual Basic's Icon Library (in the ICONS subdirectory) as a source for icons.  When you create an executable file, you can assign an icon to the application by using the Icon property of any form in that application.

Note	To see a form's icon, the form must be minimized.  The BorderStyle property must be set to either 1 (Fixed Single) or 2 (Sizable).  The MinButton property must be set to True.

At run time, you can assign an object's Icon property to another object's DragIcon or Icon property.  You can also assign an icon returned by the LoadPicture function.  Using LoadPicture with no argument assigns an empty (null) icon to the form, which enables you to draw on the icon at run time.

Data Type

Integer


See Also

Help:

Assigning an Icon to a Form

LoadPicture Function

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"

Appendix B, "Icon Library"


Icon Property Example

The example creates a blank icon for a form and draws colored dots on the icon as long as the form is minimized.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and minimize the form.

Sub Form_Resize ()
Dim X, Y	' Declare variables.
If Form1.WindowState = 1 Then
Form1.Icon = LoadPicture()	' Load a blank icon.
Do While Form1.WindowState = 1	' While form is minimized.
Form1.DrawWidth = 10	' Set size of dot.
' Choose random color for dot
Form1.ForeColor = QBColor(Int(Rnd * 15))
' Set random location on icon
X = Form1.Width * Rnd
Y = Form1.Height * Rnd
PSet (X, Y)	' Draw dot on icon.
DoEvents	' Allow other events.
Loop
End If
End Sub


Interval Property

See Also	Example

Applies To

Timer.

Description

Determines the number of milliseconds between calls to a timer control's Timer event.

Usage

[form.]timer.Interval[ = milliseconds ]

Setting

The Interval property settings are:

Setting	Description

0	(Default) Disables a timer.

1 to 65,535 	Sets an interval (in milliseconds) that takes effect when a timer control's Enabled property is set to True.  Specify a long integer in this range.  For example, a value of 10,000 milliseconds equals 10 seconds.  The maximum, 65,535 milliseconds, is equivalent to just over one minute.

Remarks

You can set a timer control's Interval property at design time or run time.  When using the Interval property, remember:

The timer control's Enabled property determines whether the timer control responds to the passage of time.  Set Enabled to False to turn the timer off, and to True to turn it on.  When a timer is enabled, its countdown always starts from the value of its Interval property setting.

Write a Timer event procedure to tell Visual Basic what to do each time the Interval has passed.

Note	There are a limited number of timers available (16 in the Windows environment).  Trying to start a timer if none is available causes a run-time error.

Data Type

Long


See Also

Programmer's Guide:

Chapter 17, "Interacting with the Environment"


Interval Property Example

The example allows you to adjust the speed at which a form switches colors.  To try this example, paste the code into the Declarations section of a form that contains a timer, a horizontal scroll bar, and a picture box.  Then press F5 and click the scroll bar.

Sub Form_Load ()
Timer1.Interval = 900	' Set interval.
HScroll1.Min = 100	' Set minimum.
HScroll1.Max = 900	' Set maximum.
End Sub
Sub HScroll1_Change ()
' Set interval according to scroll bar value.
Timer1.Interval = 1000 - HScroll1.Value
End Sub
Sub Timer1_Timer ()
' Switch BackColor between Red and Blue.

If Picture1.BackColor = RGB(255, 0, 0) Then
Picture1.BackColor = RGB(0, 0, 255)
Else
Picture1.BackColor = RGB(255, 0, 0)
End If
End Sub


LargeChange, SmallChange Properties

See Also	Example

Apply To

Horizontal scroll bar, vertical scroll bar.

Description

LargeChange [image] determines the amount of change to the Value property in a scroll bar control when the user clicks the area between the scroll box and scroll arrow.

SmallChange [image] determines the amount of change to the Value property in a scroll bar control when the user clicks a scroll arrow.

Usage

[form.]{hscrollbar|vscrollbar}.LargeChange[ = change ]

[form.]{hscrollbar|vscrollbar}.SmallChange[ = change ]

Remarks

For both properties, you can specify an integer between 1 and 32,767, inclusive.  By default, each property is set to 1.

The Windows environment automatically sets proportional scrolling increments for scroll bars on form windows, combo boxes, and list boxes based on the amount of data in the control.  For a scroll bar control, however, you must specify these increments.  Use LargeChange and SmallChange to set scrolling increments appropriate to how the scroll bar is being used.

Typically, you set LargeChange and SmallChange at design time.  You can also reset them in code at run time when the scrolling increment must change dynamically.

Note	You set the maximum and minimum ranges of a scroll bar control with the Max and Min properties.

Data Type

Integer


See Also

Help:

Change Event

Value Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


LargeChange, SmallChange, Max, Min Properties Example

The example uses a scroll bar to move a picture box control across the form.  To try this example, paste the code into the Declarations section of a form that contains a small picture box and a horizontal scroll bar.  Then press F5 and click the scroll bar.

Sub Form_Load ()
HScroll1.Max = 100	' Set maximum value.
HScroll1.LargeChange = 20	' Cross in 5 clicks.
HScroll1.SmallChange = 5	' Cross in 20 clicks.
Picture1.Left = 0	' Start picture at left.
Picture1.BackColor = QBColor(3)	' Set color of picture box.
End Sub
Sub HScroll1_Change ()
' Move picture according to scroll bar.
Picture1.Left = (HScroll1.Value / 100) * ScaleWidth
End Sub


Left, Top Properties

See Also	Example

Apply To

Form, MDI form, check box, combo box, command button, common dialog, data control, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, list box, OLE control, option button, picture box, shape, text box, timer, vertical scroll bar.

Description

Left [image] determines the distance between the internal left edge of an object and the left edge of its container.

Top [image] determines the distance between the internal top edge of an object and the top edge of its container.

For a form, the Left and Top properties are always expressed in twips; for a control, they are measured in units according to the coordinate system of its container.  The values for these properties change as the object is moved by the user or by code.  For a timer, these properties are not available at run time.

Usage

[form.][control.]Left[ = x ]

[form.][control.]Top[ = y ]

Remarks

For both properties, you can specify a single-precision number.

Use Left and Top, and the Height and Width properties, for operations based on an object's external dimensions, such as moving or resizing.  Use the ScaleLeft, ScaleTop, ScaleHeight, and ScaleWidth properties for operations based on an object's internal dimensions, such as drawing or moving objects that are contained within the object.  The scale-related properties apply only to forms, picture boxes, and the Printer object.

Data Type

Single


See Also

Help:

Left Function

Move Method

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

ScaleMode Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Left, Top Properties Example

The example sets the size of a form to 75% of screen size, and centers the form when it is loaded.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()
Width = Screen.Width * .75	' Set height of form.
Height = Screen.Height * .75	' Set width of form.
Left = (Screen.Width - Width) / 2	' Center form horizontally.
Top = (Screen.Height - Height) / 2	' Center form vertically.
End Sub


List Property

See Also	Example

Applies To

Combo box, directory list box, drive list box, file list box, list box.

Description

Determines the items contained in a control's list portion.  The list is a string array in which each element is a list item.  Not available at design-time; read-only at run time for a directory list box, drive list box, and file list box; read/write at run time for a combo box and list box.

Usage

[form.]control.List(index)[ = stringexpression ]

Remarks

Use this property to access list items.

For all controls except the directory list box, the index of the first item is 0 and the index of the last item is ListCount - 1.

For a directory list box, the index number sequence is based on the directories and subdirectories present when the control is created at run time.  The currently expanded directory is represented using the index -1.  Directories above the currently expanded directory are represented by negative indexes with higher absolute values.  For example, -2 is the parent directory of the currently expanded directory and -3 is the directory above that.  Directories below the currently expanded directory range from 0 to ListCount -1.

Initially, combo boxes and list boxes contain an empty list.  For the file-system controls, the list is based on conditions that exist when the control is created at run time:

Directory list box [image] contains a list of all directories, using the range -n to ListCount - 1.

Drive list box [image] contains the list of drive connections in effect.

File list box [image] contains the list of files in the currently expanded directory that match the Pattern property.  The path is not included.

The List property works in conjunction with the ListCount and ListIndex properties.

For all applicable controls except a directory list box, enumerating a list from 0 to ListCount -1 returns all items in the list.  For a directory list box, enumerating the list from -n to ListCount -1 returns a list containing all directories and subdirectories visible from the currently expanded directory.  In this case n is the number of directory levels above the currently expanded directory.

Note	To specify items you want to display in a combo box or list box, use the AddItem method.  To remove items, use the RemoveItem method.  To keep items in alphabetical order, set the control's Sorted property to True before adding items to the list.

Using an Option Base = 1 statement in the Declarations section does not affect the enumeration of elements in Visual Basic controls.  The first element is always 0.

When the List index is outside the range of actual entries in the list box, an empty string is returned.  For example, List(-1) returns an empty string for a combo box or list box.

Data Type

String array


See Also

Help:

ListCount Property

ListIndex Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


List Property Example

The example loads a combo box with a list of sandwich names and displays the first item in the list.  To try this example, paste the code into the Declarations section of a form that contains a combo box.  Then press F5.

Sub Form_Load ()
Combo1.AddItem "Denver Sandwich"	' Add each item to list.
Combo1.AddItem "Reuben Sandwich"
Combo1.AddItem "Turkey Sandwich"
Combo1.Text = Combo1.List(0)	' Display first item.
End Sub


ListCount Property

See Also	Example

Applies To

Combo box, directory list box, drive list box, file list box, list box.

Description

Specifies the number of items in the list portion of a control; not available at design time and read-only at run time.

Usage

[form.]control.ListCount

Remarks

ListCount provides specific information for each control:

Combo box and list box [image] the number of items in the list.

Directory list box [image] the number of subdirectories in the current directory.

Drive list box [image] the number of drive connections.

File list box [image] the number of files in the current directory that match the Pattern property.

If no item is selected, the ListIndex property value is -1.  The first item in the list is ListIndex 0, and ListCount is always one more than the largest ListIndex value.

Data Type

Integer


See Also

Help:

AddItem Method

List Property

ListIndex Property

RemoveItem Method

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


ListCount Property Example

The example loads a list of your printer fonts into a combo box, displays the first item in the list, and prints the total number of fonts.  Each click of the button changes all items in the list to uppercase or lowercase.  To try this example, paste the code into the Declarations section of a form that contains a combo box (Style = 2) and a command button.  Then press F5 and click the command button.

Sub Form_Load ()
Dim I	' Declare variable.
AutoRedraw = True	' Set AutoRedraw.
For I = 0 To Printer.FontCount - 1	' Put font names in list.
Combo1.AddItem Printer.Fonts(I)
Next I
Combo1.ListIndex = 0	' Set text to first item.
' Print ListCount info on form.
Print "Number of Printer fonts: "; Combo1.ListCount
End Sub
Sub Command1_Click ()
Static UpperCase
Dim I	' Declare variable
For I = 0 To Combo1.ListCount - 1	' Loop through list.
If UpperCase Then
Combo1.List(I) = UCase(Combo1.List(I))
Else
Combo1.List(I) = LCase(Combo1.List(I))
End If
Next I
UpperCase = Not UpperCase	' Change case.
End Sub


ListIndex Property

See Also	Example

Applies To

Combo box, directory list box, drive list box, file list box, list box.

Description

Determines the index of the currently selected item in the control.  Not available at design time.

Usage

[form.]control.ListIndex[ = index ]

Setting

The ListIndex property settings are:

Setting	Description

-1	(Default for combo box, directory list box, and drive list box) Indicates no item is currently selected.  For a combo box, indicates the user has entered new text into the text box portion of the combo box.  For a directory list box, indicates the index of the current path.  For a drive list box, indicates the index of the current drive when the control is created at run time.

n	(Default for file list box and list box) A number indicating the index of the currently selected item.

Remarks

The expression List(List1.ListIndex) returns the string for the currently selected item.

The first item in the list is ListIndex 0, and ListCount is always one more than the largest ListIndex value.

Data Type

Integer


See Also:

Help:

AddItem Method

Drive Property

List Property

ListCount Property

Path Property

RemoveItem Method

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


ListIndex Property Example

The example displays the names of three players in a list box and the corresponding salary of the selected player in a label.  To try this example, paste the code into the Declarations section of a form that contains a combo box and a label.  Then press F5 and choose a name from the combo box.

' General declarations
Dim Player(0 To 2)	' Dimension two arrays.
Dim Salary(0 To 2)
Sub Form_Load ()
Dim I	' Declare variable.
AutoSize = True
Player(0) = "Miggey McMoo"	' Enter data into arrays.
Player(1) = "Alf Hinshaw"
Player(2) = "Woofer Dean"
Salary(0) = "$234,500"
Salary(1) = "$158,900"
Salary(2) = "$1,030,500"
For I = 0 To 2	' Add names to list.
Combo1.AddItem Player(I)
Next I
Combo1.ListIndex = 0	' Display first item in list.
End Sub
Sub Combo1_Click ()
' Display corresponding salary for name.
Label1.Caption = Salary(Combo1.ListIndex)
End Sub


Max, Min Properties (Scroll Bars)

See Also	Example

Apply To

Horizontal scroll bar, vertical scroll bar.

Description

Max [image] determines a scroll bar position's maximum Value property setting when the scroll box is in its bottommost position (vertical scroll bar) or rightmost position (horizontal scroll bar).

Min [image] determines a scroll bar position's minimum Value property setting when the scroll box is in its topmost position (vertical scroll bar) or leftmost position (horizontal scroll bar).

Usage

[form.]{hscrollbar|vscrollbar}.Max[ = limit ]

[form.]{hscrollbar|vscrollbar}.Min[ = limit ]

Setting

For each property, you can specify an integer between -32,768 to 32,767, inclusive.  The default settings are:

Max [image] 32,767.

Min [image] 0.

Remarks

The Windows environment automatically sets ranges for scroll bars proportional to the contents of forms, combo boxes, and list boxes.  For a scroll bar control, however, you must specify these ranges.  Use Max and Min to set a range appropriate to how the scroll bar control is used [image] for example, as an input device or as an indicator of speed or quantity.

Typically, you set Max and Min at design time.  You can also set them in code at run time if the scrolling range must change dynamically [image] for example, when adding records to a database that can be browsed with a scroll bar.  You set the maximum and minimum scrolling increments for a scroll bar control with the LargeChange and SmallChange properties.

Note	If Max is set to less than Min, the maximum value is then set at the leftmost or topmost position of a horizontal or vertical scroll bar, respectively.

Data Type

Integer


See Also

Help:

LargeChange, SmallChange Properties

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


MaxButton Property

See Also

Applies To

Form.

Description

Specifies whether a form has a Maximize button; read-only at run time.

Usage

[form.]MaxButton

Setting

The MaxButton property settings are:

Setting	Description

True	(Default) The form has a Maximize button.

False	The form does not have a Maximize button.

Remarks

A Maximize button enables users to enlarge a form window to full-screen size.  To display a Maximize button, you must also set the form's BorderStyle property to either 1 (Fixed Single) or 2 (Sizable).

A Maximize button automatically becomes a Restore button when a window is maximized.  Minimizing or restoring a window automatically changes the Restore button back to a Maximize button.

The settings you specify for MaxButton, MinButton, BorderStyle, and ControlBox are not reflected in the form's appearance until run time.

In Microsoft Windows version 3.0, an MDI child form appears with a Maximize button regardless of the MaxButton setting.  However, if MaxButton is False, the Maximize button does not respond to mouse clicks and the Maximize command is not on the form's Control-menu box.

Note	Maximizing a form at run time generates a Resize event.  The WindowState property reflects the current state of the window.  If you set the WindowState property to 2 (Maximized), the form is maximized independently of whatever settings are in effect for the MaxButton and BorderStyle properties.

Data Type

Integer (Boolean)


See Also

Help:

ControlBox Property

MinButton Property


MinButton Property

See Also

Applies To

Form.

Description

Specifies whether a form has a Minimize button; read-only at run time.

Usage

[form.]MinButton

Setting

The MinButton property settings are:

Setting	Description

True	(Default) The form has a Minimize button.

False	The form does not have a Minimize button.

Remarks

A Minimize button enables users to shrink a form window to an icon.  To display a Minimize button, you must also set the form's BorderStyle property to either 1 (Fixed Single) or 2 (Sizable).

The settings you specify for MaxButton, MinButton, BorderStyle, and ControlBox are not reflected in the form's appearance until run time.

In Microsoft Windows version 3.0, an MDI child form appears with a Minimize button regardless of the MinButton setting.  However, if MinButton is False, it does not respond to mouse clicks and the Minimize command is not on the form's Control-menu box.

Note	Shrinking a form to an icon at run time generates a Resize event.  The WindowState property reflects the current state of the window.  If you set the WindowState property to 2 (Maximized), the form is maximized independently of whatever settings are in effect for the MaxButton and BorderStyle properties.

Data Type

Integer (Boolean)


See Also

Help:

Assigning an Icon to a Form

ControlBox Property

MaxButton Property


Page Property

See Also	Example

Applies To

Printer object.

Description

Specifies the current page number.  Not available at design time and read-only at run time.

Usage

Printer.Page

Remarks

Visual Basic keeps a count of pages that have been printed since your application started or since the last Printer.EndDoc statement was executed.  This count starts at one and increases by one if:

You use the NewPage method.

You use the Print method and the text you wish to print does not fit on the current page.

Note	Graphics methods output that does not fit on the page does not generate a new page.  The output is clipped to fit the page's printable area.

Data Type

Integer


See Also

Help:

EndDoc Method

NewPage Method

Print Method

Programmer's Guide:

Chapter 16, "Displaying and Printing Information"


Page Property Example

The example prints three pages of text with the current page number at the top.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()
Dim Header, I, Y	' Declare variables.
Print "Now printing..."	' Put notice on form.
Header = "Printing Demo - Page "	' Set header string.
For I = 1 To 3
Printer.Print Header;	' Print header.
Printer.Print Printer.Page	' Print page number.
Y = Printer.CurrentY + 10	' Set position for line.
' Draw a line across page.
Printer.Line (0, Y) - (Printer.ScaleWidth, Y)	' Draw line.
For K = 1 To 50
Printer.Print String(K, " ");	' Print string of spaces.
Printer.Print "Visual Basic ";	' Print text.
Printer.Print Printer.Page	' Print page number.
Next
Printer.NewPage
Next I
Printer.EndDoc
End
End Sub


Path Property

See Also	Example

Applies To

App object, directory list box, file list box.

Description

Determines the current absolute path, including the drive name.  Not available at design time.  For the App object, read-only at run time.

Usage

[form.]{dirlistbox|filelistbox}.Path[ = spec ]

App.Path

Setting

The value of the Path property is a string indicating a path, such as "C:\VB" or "C:\WINDOWS\SYSTEM."  For a directory list box or a file list box, the default is the current path when the control is created at run time.  For the App object, Path specifies the absolute path of the project when running the application from the development environment, and the absolute path of the .EXE file when running the application as an executable file.

Remarks

Use this property when building an application's file-browsing and manipulation capabilities.  Setting the Path property has effects on the control similar to the MS-DOS chdir command [image] relative paths are allowed with or without a drive.  Setting only a drive (with colon) selects the current directory on that drive.

This property can also be set to a qualified network path without a drive connection using the following syntax:

\\servername\sharename\path

which changes the Drive property to an empty string ("").

Changing the value of Path has these effects:

For a directory list box, generates a Change event.

For a file list box, generates a PathChange event.

Note	For a directory list box, the return value of Path is different from that of List(ListIndex), which returns only the selection.

Data Type

String


See Also

Help:

Archive, Hidden, Normal, System Properties

Drive Property

FileName Property

List Property

ListCount Property

ListIndex Property

PathChange Event

Pattern Property

PatternChange Event

ReadOnly Property

Programmer's Guide:

Chapter 18, "Using the File-System Controls"

Chapter 19, "Processing Files"


Path Property Example

The example displays a list of files for the selected drive and directory.  To try this example, paste the code into the Declarations section of a form that contains a drive list box, a directory list box, and a file list box.  Then press F5.  Use the mouse to change the drive or directory.

Sub Drive1_Change ()
Dir1.Path = Drive1.Drive	' Set Dir path.
End Sub
Sub Dir1_Change ()
File1.Path = Dir1.Path	' Set File path.
End Sub


Pattern Property

See Also	Example

Applies To

File list box.

Description

Determines which file names are displayed in a file list box at run time.

Usage

[form.]filelistbox.Pattern[ = display ]

Setting

The value of the Pattern property is a string indicating a file specification, such as "*.*" or "*.FRM".  The default is "*.*", which returns a list of all files.  In addition to using wildcard characters, you can also use multiple patterns separated by semicolons.  For example, "*.EXE; *.BAT" would return a list of all executable files and all MS-DOS batch files.

Remarks

The Pattern property plays a key role in designing an application's file-browsing and manipulation capabilities.  Use Pattern in combination with other file-control properties to provide the user with ways to explore files or groups of similar files.  For example, in an application dedicated to launching other programs, you might designate that only .EXE files be displayed in the file list box (*.EXE).  Other key file-control properties include Drive, FileName, and Path.

Changing the value of Pattern generates a PatternChange event.

Data Type

String


See Also

Help:

Archive, Hidden, Normal, System Properties

Path Property

PathChange Event

PatternChange Event

ReadOnly Property

Programmer's Guide:

Chapter 18, "Using the File-System Controls"

Chapter 19, "Processing Files"


Pattern Property Example

The example updates a text box with the new pattern selected in a file list box.  The controls are set up so that when the user enters a pattern in the text box, such as *.TXT, it is reflected in the file list box, much like the interaction you see in a typical File Open dialog box in an application for Microsoft Windows.  If a full path such as C:\BIN\*.EXE is entered into the text box, the text is automatically parsed into path and pattern components by the file list box.  To try this example, paste the code into the Declarations section of a form that contains a directory list box, a file list box, a text box, and a command button.  Then press F5 and type a valid file pattern into the text box.

Sub Form_Load ()
Command1.Default = True	' Set Default property.
End Sub
Sub Command1_Click ()
' Text is parsed into path and pattern components.
File1.Filename = Text1.Text
Dir1.Path = File1.Path	' Set directory path.
End Sub
Sub File1_PatternChange ()
Text1.Text = File1.Pattern	' Set text to new pattern.
End Sub
Sub Dir1_Change
File1.Path = Dir1.Path	' Set file list box path.
End Sub


SelLength, SelStart, SelText Properties

See Also	Example1	Example2

Apply To

Combo box, text box.

Description

SelLength [image] determines the number of characters selected.

SelStart [image] determines the starting point of text selected; indicates the position of the insertion point if no text is selected.

SelText [image] determines the string containing the currently selected text; consists of an empty string ("") if no characters are selected.

These properties are not available at design time.

Usage

[form.]{combobox|textbox}.SelLength[ = length ]

[form.]{combobox|textbox}.SelStart[ = index ]

[form.]{combobox|textbox}.SelText[ = stringexpression ]

Setting

For SelLength and SelStart, the valid range of settings is 0 to text length [image] the total number of characters in the edit area of a combo box or text box.

Remarks

Use these properties for tasks such as setting the insertion point, establishing an insertion range, selecting substrings in a control, or clearing text.  Used in conjunction with the Clipboard object, these properties are useful for copy, cut, and paste operations.

When working with these properties:

Setting SelLength less than 0 causes a run-time error.

Setting SelStart greater than the text length sets the property to the existing text length; changing SelStart changes the selection to an insertion point and sets SelLength to 0.

Setting SelText to a new value sets SelLength to 0 and replaces the selected text with the new string.

Data Type

SelLength, SelStart [image] Long

SelText [image] String


See Also

Help:

ActiveControl Property

ActiveForm Property

Text Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


SelLength, SelStart, SelText Properties Example 1

This example lets the user specify some text to search for, and then searches the text and selects it, if found.  To try this example, paste the code into the Declarations section of a form that contains a wide text box.  Then press F5 and click the form.

Sub Form_Load ()
Text1.Text = "Two of the peak human experiences"
Text1.Text = Text1.Text & " are good food and classical music."
End Sub

Sub Form_Click ()
Dim Search, Where	' Declare variables.
' Get search string from user.
Search = InputBox("Enter text to be found:")
Where = InStr(Text1.Text, Search)	' Find string in text.
If Where Then	' If found...
Text1.SelStart = Where - 1	' Set selection start.
Text1.SelLength = Len(Search)	' Set selection length.
Else
MsgBox "String not found."	' Notify user
End If
End Sub


SelLength, SelStart, SelText Properties Example 2

This example shows how the Clipboard is used in cut, copy, paste, and delete operations.  To try this example, create a form with a text box and use the Menu Design window to create an Edit menu (for each of the commands, set Caption = Cut, Copy, Paste, and Delete; and set Name = EditCut, EditCopy, EditPaste, and EditDelete, respectively).

Sub EditCut_Click ()
' Copy selected text to Clipboard.
ClipBoard.SetText Screen.ActiveControl.SelText
' Delete selected text.
Screen.ActiveControl.SelText = ""
End Sub
Sub EditCopy_Click ()
' Copy selected text to Clipboard.
ClipBoard.SetText Screen.ActiveControl.SelText
End Sub
Sub EditPaste_Click ()
' Place text from Clipboard into active control.
Screen.ActiveControl.SelText = ClipBoard.GetText ()
End Sub

Sub EditDelete_Click ()
' Delete selected text.
Screen.ActiveControl.SelText = ""
End Sub


Alignment Property

See Also

Applies To

Check box, label, option button, text box.

Description

Determines the alignment of a check box, option button, or text in a control.  Read-only at run time for check box, option button, and text box.

Usage

[form.]control.Alignment[ = numericexpression ]

Setting

For a check box and option button, the Alignment property settings are:

Setting	Description

0	(Default) Control aligns to the left with text on the right.

1	Control aligns to the right with text on the left.

For a label and text box, the Alignment property settings are:

Setting	Description

0	(Default) Text aligns to the left.

1	Text aligns to the right.

2	Text aligns to the center (in Microsoft Windows version 3.0, aligns to the left).

Remarks

You can have text appear to the right or left of option buttons and check boxes, as in the following illustration.  Notice that text always aligns to the left.

If the MuliLine property of a text box is False, the Alignment property is ignored.

Data Type

Integer (Enumerated)


See Also

Help:

Align Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


BackColor, ForeColor Properties

See Also	Example

Apply To

Form, check box, combo box, command button (BackColor only), data control, directory list box, drive list box, file list box, frame, grid, label, list box, OLE control, option button, picture box, Printer object (ForeColor only), shape (BackColor only), text box.

Description

BackColor [image] determines the background color of an object.

ForeColor [image] determines the foreground color used to display text and graphics in an object.

Usage

[form.][control.]BackColor[ = color ]

[form.][control.]ForeColor[ = color ]

Remarks

Visual Basic uses the Microsoft Windows environment RGB scheme for colors.  Each property has the following ranges of settings:

Range of settings	Description

Normal RGB colors	Colors specified by using the Color palette, or by using the RGB or QBColor functions in code.

System default colors	Colors specified with system color constants from CONSTANT.TXT, a Visual Basic file that specifies system defaults.  The Windows environment substitutes the user's choices as specified in the user's Control Panel settings.

For all forms and controls, the default settings at design time are:

BackColor [image] set to the WINDOW_BACKGROUND system default color as specified in CONSTANT.TXT.

ForeColor [image] set to the WINDOW_TEXT system color as specified in CONSTANT.TXT.

In labels and shapes, the BackColor property is ignored if the BackStyle property is 0 (Transparent).

If you set the BackColor property on forms or picture boxes, all graphics and print output, including the persistent bitmap, are erased.  Setting the ForeColor property does not affect graphics or print output already drawn.  On all other controls, the screen color changes immediately.

The valid range for a normal RGB color is 0 to 16,777,215 (&HFFFFFF).  The high byte of a number in this range equals 0; the lower three bytes, from least to most significant byte, determine the amount of red, green, and blue, respectively.  The red, green, and blue components are each represented by a number between 0 and 255 (&HFF).  If the high byte is not 0, Visual Basic uses the system colors, as defined in the user's Control Panel and enumerated in CONSTANT.TXT.

To display text in the Windows environment, both the text and background colors must be solid.  If the text or background colors you've selected are not displayed, one of the selected colors may be dithered [image] that is, comprised of up to three different-colored pixels.  If you choose a dithered color for either the text or background, the nearest solid color will be substituted.


See Also

Help

Creating Custom Colors

FillColor Property

FillStyle Property

Setting Colors

Programmer's Guide

Chapter 15, "Creating Graphics for Applications"


BackColor, ForeColor Properties Example

The example resets background colors randomly twice each second for a form and picture box.  To try this example, paste the code into the Declarations section of a form that contains a picture box control and a timer control.  Then press F5.

Sub Form_Load ()

Timer1.Interval = 500

End Sub

Sub Timer1_Timer ()

BackColor = QBColor(Rnd * 15)

Picture1.BackColor = QBColor(Rnd * 15)

End Sub


BorderColor Property

See Also

Applies To

Line, shape.

Description

Determines the color of a control's border.

Usage

[form.]{line|shape}.BorderColor[ = color ]

Setting

Visual Basic uses the Microsoft Windows environment RGB scheme for colors.  The BorderColor property has the following range of settings:

Range of settings	Description

Normal RGB colors	Colors specified by using the Color palette, or by using the RGB or QBColor functions in code.

System default colors	Colors specified with system color constants from CONSTANT.TXT, a Visual Basic file that specifies system defaults.  The Windows environment substitutes the user's choices, as specified in the user's Control Panel settings.

The default setting for BorderColor is the WINDOW_TEXT system default color, as specified in CONSTANT.TXT.

Remarks

The valid range for a normal RGB color is 0 to 16,777,215 (&HFFFFFF).  The high byte of a number in this range equals 0; the lower three bytes, from least to most significant byte, determine the amount of red, green, and blue, respectively.  The red, green, and blue components are each represented by a number between 0 and 255 (&HFF).  If the high byte is not 0, Visual Basic uses the system colors, as defined in the user's Control Panel and enumerated in CONSTANT.TXT.

Data Type

Long


See Also

Help:

BackColor, ForeColor Properties

DrawWidth Property

Programmer's Guide

Chapter 15, "Creating Graphics for Applications"


BorderWidth Property

See Also	Example

Applies To

Line, shape.

Description

Determines the width of a control's border.

Usage

[form.]{line|shape}.BorderWidth[ = numericexpression ]

Remarks

The BorderWidth property settings can range from 1 to 8192, inclusive.

Use the BorderWidth and BorderStyle properties to specify the kind of border you want for a line and shape control.  The following table shows the effect of BorderStyle settings on the BorderWidth property:

BorderStyle	Effect on BorderWidth

0	BorderWidth setting is ignored.

1 to 5	The border width expands from the center of the border; the height and width of the control are measured from the center of the border.

6	The border width expands inward on the control from the outside of the border; the height and width of the control are measured from the outside of the border.

If BorderWidth is greater than 1, the only effective settings of BorderStyle are 1 (Solid), and 6 (Inside Solid).

Data Type

Integer


See Also

Help:

BorderStyle Property

DrawWidth Property

Height, Width Properties

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


BorderWidth Property Example

The example uses two combo boxes to select different widths and styles for the borders of a shape control.  To try this example, paste the code into the Declarations section of a form that contains a shape control and one combo box.  For the combo box, set Style = 2 and Index = 0 (to create a control array).  Then press F5 and click the form.

Sub Form_Load ()

Combo1(0).Width = 1440 * 1.5

Load Combo1(1)

Combo1(1).Top = Combo1(0).Top + Combo1(0).Height * 1.5

Combo1(1).Visible = True

For I = 0 To 6

Combo1(0).AddItem "BorderStyle = " & I

Next I

For I = 1 To 10

Combo1(1).AddItem "BorderWidth = " & I

Next I

Combo1(0).ListIndex = 1

Combo1(1).ListIndex = 0

End Sub

Sub Combo1_Click (Index As Integer)

If Index = 0 Then

Shape1.BorderStyle = Combo1(0).ListIndex

Else

Shape1.BorderWidth = Combo1(1).ListIndex + 1

End If

End Sub


ClipControls Property

See Also	Example

Applies To

Form, frame, picture box.

Description

Determines whether graphics methods in Paint events repaint the entire object or only newly exposed areas.  Also determines whether the Windows environment creates a clipping region that excludes non-graphic controls contained by the object.

Usage

[form.][frame.|picturebox.]ClipControls

Setting

The ClipControls property settings are:

Setting	Description

True	(Default) Graphics methods in Paint events repaint the entire object.  A clipping region is created around non-graphical controls on the form before a Paint event.

False	Graphics methods in Paint events repaint only newly exposed areas.  A clipping region is not created around non-graphical controls before a Paint event.  Complex forms usually load and repaint faster.

Remarks

Clipping is the process of determining which parts of a form or container, such as a frame or picture box, are painted when the form is displayed.  An outline of the form and controls is created in memory.  The Windows environment uses this outline to paint some parts, such as the background, without affecting other parts, such as the contents of a text box.  Since the clipping region is created in memory, setting this property to False can reduce the time needed to paint or repaint a form.

The clipping region includes most controls, but does not clip around the image, label, line, or shape controls.

Data Type

Integer (Boolean)


See Also

Help:

AutoRedraw Property

Circle Method

Line Method

Paint Event

Print Method

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


ClipControls Property Example

The example shows how the ClipControls property affects the repainting of a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5.  Notice that the color of the entire form changes each time you resize it or cover part of it with another form or application.  End the program and change ClipControls to False and then run the program again.  Notice that only newly exposed parts of the form are repainted.

Sub Form_Paint ()

' Select a random color for the background.

BackColor = &HFFFFFF * Rnd

End Sub


CurrentX, CurrentY Properties

See Also

Apply To

Form, picture box, Printer object.

Description

Determine the horizontal (CurrentX) and vertical (CurrentY) coordinates for the next printing or drawing method.  Not available at design time.

Usage

{[form.][picturebox.]|Printer.}CurrentX[ = x ]

{[form.][picturebox.]|Printer.}CurrentY[ = y ]

Remarks

Coordinates are measured from the upper-left corner of an object.  CurrentX is 0 at an object's left edge and CurrentY is 0 at its top edge.  Coordinates are expressed in twips, or the current scale defined by the ScaleHeight, ScaleWidth, ScaleLeft, ScaleTop, and ScaleMode. properties.

When you use the following graphics methods, the CurrentX and CurrentY settings are changed as indicated:

This method	Sets CurrentX, CurrentY to

Circle	The center of the object.

Cls	0, 0

EndDoc	0, 0

Line	The end point of the line.

NewPage	0, 0

Print	The next print position.

PSet	The point drawn.

Data Type

Single


See Also

Help:

Circle Method

Cls Method

DrawMode Property

DrawStyle Property

Left, Top Properties

Line Method

PSet Method

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

ScaleMode Properties

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


EXEName Property

See Also

Applies To

App object.

Description

Specifies the root name of the executable file (without the extension) that is currently running.  If running in the development environment, specifies the name of the project.  Read-only at run time.

Usage

App.EXEName

Remarks

Use this property to identify your application in calls to the Windows API.

If you have a Save As command on a menu in your application, you can use the EXEName property to make sure a user doesn't accidentally try to save a file with the same name as your application.

The value of this property is set when you create an executable file with the Make EXE command on the File menu.


See Also

Help:

Using Dynamic Data Exchange (DDE)

Make EXE File Command (File Menu)

Programmer's Guide:

Chapter 17, "Interacting with the Environment"

Chapter 21, "Object Linking and Embedding (OLE)"


FillStyle Property

See Also	Example

Applies To

Form, grid, picture box, Printer object, shape.

Description

Grid [image] Determines whether setting the Text property of a grid causes the value to appear in all selected cells.

All other controls [image] Determines the pattern used to fill shape controls as well as circles and boxes created with the Circle and Line graphics methods.

Usage

{[form.][control.]|Printer.}FillStyle[ = style ]

Setting

The FillStyle settings for a grid control are:

Setting	Description

0	Single-Changing the Text property only affects the active cell.

1	Repeat-Changing the Text property affects all selected cells.

The FillStyle settings for other controls are:

Setting	Description

0	Solid

1	(Default) Transparent

2	Horizontal Line

3	Vertical Line

4	Upward Diagonal

5	Downward Diagonal

6	Cross

7	Diagonal Cross

Remarks

When FillStyle is 1 (Transparent), the FillColor property is ignored.

Data Type

Integer (Enumerated)


See Also

Help:

BorderStyle Property

Paint Event

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


FillStyle Property Example

The example displays a circle on a form with random FillColors and FillStyles as you click the mouse button.  To try this example, paste the code into the Declarations section and then press F5 to run the program.

Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)

FillColor = QBColor(Rnd * 15)	' Choose random FillColor.

FillStyle = Int(Rnd * 8)	' Choose random FillStyle.

Circle (X, Y), 250	' Draw a circle.

End Sub


hWnd Property

See Also	Example1	Example2

Applies To

Form, MDI form, check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, list box, OLE control, option button, picture box, scroll bar, text box.

Description

Specifies a handle to a form or control.  Not available at design time; read-only at run time.

Usage

[form.][control.]hWnd

Remarks

The Windows environment identifies each form and control in an application by assigning it a handle, or hWnd.  The hWnd is used with Windows API calls.  Many Windows environment functions require the hWnd of the current window as an argument.

Note	Because the value of this property can change while a program is running, never store the hWnd value in a variable.

Data Type

Integer


See Also

Help:

Declare Statement

hDC Property

Icon Property

Programmer's Guide:

Chapter 22, "Calling Procedures in DLLs"


hWnd Property Example 1

The example forces a form to always remain on top.  To try this example, create a form (not an MDI child form) and set its Caption property to "Always on top."  Then give the form a menu containing a menu item named "mnuTopmost."  Make sure the Declare statement is all on one line.  Paste the code into the Declarations section of the form and press F5.  (This example requires Microsoft Windows version 3.1.)

' Declare the Windows 3.1 API routine.

Declare Sub SetWindowPos Lib "User" (ByVal h1 As Integer, ByVal h2 As Integer, ByVal x As Integer, ByVal y As Integer, ByVal cx As Integer, ByVal cy As Integer, ByVal f As Long)

' Set some constant values (from WINAPI.TXT).

Const HWND_TOPMOST = -1

Const HWND_NOTOPMOST = -2

Const SWP_NOACTIVATE = &H10

Const SWP_SHOWWINDOW = &H40

Sub mnuTopmost_Click ()

' Add or remove the checkmark from the menu.

mnuTopmost.Checked = Not mnuTopmost.Checked

If mnuTopmost.Checked Then

' Turn on the TopMost attribute.

SetWindowPos hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE Or SWP_SHOWWINDOW

Else

' Turn off the TopMost attribute.

SetWindowPos hWnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE Or SWP_SHOWWINDOW

End If

End Sub


hWnd Property Example 2

The example automatically drops down the list portion of a combo box whenever the combo box gets the focus.  To try this example, create a new form containing a combo box and option button (the option button is used only to receive the focus).  Make sure the Declare statement is all on one line.  Paste the code into the Declarations section of the form and press F5.  Use the Tab key to move the focus to and from the combo box.

Declare Function SendMessage Lib "User" (ByVal hWnd As Integer, ByVal Msg As Integer, ByVal Wp As Integer, Lp As Any) As Long

Const WM_USER = &H400

Sub Combo1_GotFocus ()

Const CB_SHOWDROPDOWN = WM_USER + 15

Dim Tmp

Tmp = SendMessage(Combo1.hWnd, CB_SHOWDROPDOWN, 1, ByVal 0&)

End Sub


PrevInstance Property

See Also

Applies To

App object.

Description

Specifies whether a previous instance of an application is already running.  Not available at design time; read-only at run time.

Usage

App.PrevInstance

Remarks

You can use this property in a Form_Load procedure to specify whether a user is already running an instance of an application.  Depending on the application, you might want only one instance running in the Windows environment at a time.

Data Type

Integer (Boolean)


See Also

Programmer's Guide:

Chapter 8, "Objects and Instances"


ScaleHeight, ScaleWidth Properties

See Also	Example

Apply To

Form, MDI form, picture box, Printer object.

Description

Determine the number of units for the internal horizontal (ScaleWidth) and vertical (ScaleHeight) measurement of an object when using graphics methods or when positioning controls.  For MDI forms, not available at design time and read-only at run time.

Usage

{[form.][picturebox.]|Printer.}ScaleHeight[ = numericexpression ]

{[form.][picturebox.]|Printer.}ScaleWidth[ = numericexpression ]

Remarks

You can use these properties to create a custom coordinate scale for drawing or printing.  For example, the statement ScaleHeight = 100 defines the internal height of a section as 100 units, or one vertical unit as 1/100 of the height.

Use the ScaleMode property to define a scale based on a standard unit of measurement, such as twips, points, pixels, characters, inches, millimeters, or centimeters.

Setting these properties to positive values makes coordinates increase from top to bottom and left to right.  Setting them to negative values makes coordinates increase from bottom to top and right to left.

Using these properties and the related ScaleLeft and ScaleTop properties, you can set up a full coordinate system with both positive and negative coordinates.  All four of these scale properties interact with the ScaleMode property in the following ways:

Setting any other scale property to any value automatically sets ScaleMode to 0.

Setting ScaleMode to a number greater than 0 changes ScaleHeight and ScaleWidth to the new unit of measurement and sets ScaleLeft and ScaleTop to 0.  In addition, the CurrentX and CurrentY settings will change to reflect the new coordinates of the current point.

You can also use the Scale method to set the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties in one statement.

Note	The ScaleHeight and ScaleWidth properties aren't the same as the Height and Width properties.

For MDI forms, ScaleHeight and ScaleWidth refer only to the area not covered by picture boxes in the form.  Avoid using these properties to size a picture box in the Resize event of an MDI form.

Data Type

Single


See Also

Help:

CurrentX, CurrentY Properties

DrawMode Property

DrawStyle Property

FillColor Property

ForeColor Property

Scale Method

ScaleLeft, ScaleTop Properties

ScaleMode Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


ScaleHeight, ScaleWidth Properties Example

The example uses the ScaleHeight and ScaleWidth properties to change the vertical and horizontal units of measurement for a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5.  To see the effect, click the form, resize it, then click it again.

Sub Form_Click ()

Dim Radius As Integer	' Declare variable.

ScaleHeight = 100	' Set height units.

ScaleWidth = 100	' Set width units.

For Radius = 5 to 50 Step 5

FillStyle = 1

Circle (50, 50), Radius	' Draw  circle.

Next Radius

End Sub


ScaleLeft, ScaleTop Properties

See Also	Example

Apply To

Form, picture box, Printer object.

Description

Determine the horizontal (ScaleLeft) and vertical (ScaleTop) coordinates for the left and top edges of an object when using graphics methods or when positioning controls.  The default for both properties is 0.

Usage

{[form.][picturebox.]|Printer.}ScaleLeft[ = numericexpression ]

{[form.][picturebox.]|Printer.}ScaleTop[ = numericexpression ]

Remarks

Using these properties and the related ScaleHeight and ScaleWidth properties, you can set up a full coordinate system with both positive and negative coordinates.  These four scale properties interact with the ScaleMode property in the following ways:

Setting any other scale property to any value automatically sets ScaleMode to 0.

Setting ScaleMode to a number greater than 0 changes ScaleHeight and ScaleWidth to the new unit of measurement and sets ScaleLeft and ScaleTop to 0.  The CurrentX and CurrentY property settings will change to reflect the new coordinates of the current point.

You can also use the Scale method to set the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties in one statement.

Note	The ScaleLeft and ScaleTop properties aren't the same as the Left and Top properties.

Data Type

Single


See Also

Help:

DrawMode Property

DrawStyle Property

FillColor Property

ForeColor Property

Left, Top Properties

Scale Method

ScaleHeight, ScaleWidth Properties

ScaleMode Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


ScaleLeft, ScaleTop Properties Example

The example creates a grid in a picture box and sets coordinates for the upper-left corner to -1, -1 instead of 0, 0.  Every quarter second, dots are randomly plotted from the upper-left corner to the lower-right corner.  To try this example, paste the code into the Declarations section of a form that contains a large picture box and a timer control.  Then press F5 and click the form.

Sub Form_Load ()

Timer1.Interval = 250	' Set timer interval.

Picture1.ScaleTop = -1	' Set scale for top of grid.

Picture1.ScaleLeft = -1	' Set scale for left of grid.

Picture1.ScaleWidth = 2	' Set scale (-1 to 1).

Picture1.ScaleHeight = 2

Picture1.Line (-1, 0)-(1, 0)	' Draw horizontal line.

Picture1.Line (0, -1)-(0, 1)	' Draw vertical line.

End Sub

Sub Timer1_Timer ()

Dim I	' Declare variable.

' Plot dots randomly within a range.

For I = -1 To 1 Step .05

Picture1.PSet (I * Rnd, I * Rnd)	' Draw a point.

Next I

End Sub


ScaleMode Property

See Also	Example

Applies To

Form, picture box, Printer object.

Description

Determines the unit of measurement for coordinates of an object when using graphics methods or when positioning controls.

Usage

{[form.][picturebox.]|Printer.}ScaleMode[ = mode ]

Setting

The ScaleMode property settings are:

Setting	Description

0	Indicates that one or more of the ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties are set to custom values.

1	(Default) Twip (1440 twips per logical inch; 567 twips per logical centimeter).

2	Point (72 points per logical inch).

3	Pixel (smallest unit of monitor or printer resolution).

4	Character (horizontal = 120 twips per unit; vertical = 240 twips per unit).

5	Inch.

6	Millimeter.

7	Centimeter.

Remarks

Using the related ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties, you can create a custom coordinate system with both positive and negative coordinates.  These four scale properties interact with the ScaleMode property in the following ways:

Setting the value of any other scale property to any value automatically sets ScaleMode to 0.

Setting ScaleMode to a number greater than 0 changes ScaleHeight and ScaleWidth to the new unit of measurement and sets ScaleLeft and ScaleTop to 0.  The CurrentX and CurrentY property settings will change to reflect the new coordinates of the current point.

Data Type

Integer (Enumerated)


See Also

Help:

DrawMode Property

DrawStyle Property

FillColor Property

ForeColor Property

Scale Method

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"

Chapter 16, "Displaying and Printing Information"


ScaleMode Property Example

The example shows how different ScaleMode property settings change the size of a circle.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.   When you click the form, the unit of measurement changes to the next ScaleMode setting and a circle is drawn on the form.

Sub Form_Click ()

' Cycle through each of 7 ScaleModes.

ScaleMode = ((ScaleMode + 1) Mod 7) + 1

' Draw a circle with radius of 2 in center of form.

Circle (ScaleWidth / 2, ScaleHeight / 2), 2

End Sub


Stretch Property

See Also	Example

Applies To

Image

Description

Determines whether a picture stretches to fit the size of an image control.

Usage

[form.]image.Stretch[ = {True|False}]

Setting

The Stretch property settings are:

Setting	Description

True	The picture resizes to fit the control.

False	(Default) The control resizes to fit the picture.

Remarks

If Stretch is True, resizing the control also resizes the picture it contains.

Data Type

Integer (Boolean)


See Also

Help:

Image Property

Picture Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Stretch Property Example

The example loads an arrow icon from your icons directory into an image control.  The arrow crawls across the form when Stretch is True, and hops across the form when Stretch is False.  To try this example, paste the code into the Declarations section of a form that contains an image control, a check box and a timer control.  Then press F5 and click the form.  Be sure to check the path to your icons directory and change it if necessary.  To see the effects of the Stretch property, click the check box and then click the form again.

Dim ImgW	' Declare variable.

Sub Form_Load ()

' Load an icon into the image control.

Image1.Picture = LoadPicture("icons\arrows\arw02rt.ico")

Image1.Left = 0	' Move image to left edge.

ImgW = Image1.Width	' Save width of image.

Timer1.Interval = 300

Timer1.Enabled = False	' Turn off timer.

Check1.Caption = "Stretch Property"

End Sub

Sub Form_Click ()

Timer1.Enabled = True	' Turn on the timer.

End Sub

Sub Timer1_Timer ()

Static MoveIcon As Integer	' Flag for moving the icon.

If Not MoveIcon Then

Image1.Move Image1.Left + ImgW, Image1.Top, ImgW * 2

Else

' Move the image and return it to original width.

Image1.Move Image1.Left + ImgW, Image1.Top, ImgW

End If

' If image is off edge of form, start over.

If Image1.Left > ScaleWidth Then

Image1.Left = 0

Timer1.Enabled = False

End If

MoveIcon = Not MoveIcon	' Reset flag.

End Sub

Sub Check1_Click ()

Image1.Stretch = Check1.Value

End Sub


TwipsPerPixelX, TwipsPerPixelY Properties

See Also

Apply To

Screen object, Printer object.

Description

Specify the number of twips per pixel for the object measured horizontally (TwipsPerPixelX) or vertically (TwipsPerPixelY).  Not available at design time; read-only at run time.

Usage

{Screen|Printer}.TwipsPerPixelX

{Screen|Printer}.TwipsPerPixelY

Remarks

Windows API routines generally require measurements in pixels.  You can use these properties to convert measurements quickly without changing an object's ScaleMode setting.

Data Type

Integer


See Also

Help:

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

ScaleMode Properties

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


ScrollBars Property

See Also

Applies To

MDI form, grid, text box.

Description

Specifies whether an object has horizontal or vertical scroll bars; read-only at run time.

Usage

{mdiform|grid|textbox}.ScrollBars

Setting

For an MDI form, the ScrollBars property settings are:

Setting	Description

True	(Default) The form has a horizontal or vertical scroll bar, or both.

False	The form has no scroll bars.

For a grid and text box, the ScrollBars property settings are:

Setting	Description

0	(Default) None

1	Horizontal

2	Vertical

3	Both

Remarks

For a text box with settings 1 (Horizontal), 2 (Vertical), or 3 (Both), you must set the MultiLine property to True.

At run time, the Windows environment automatically implements a standard keyboard interface to allow navigation in text box controls with the arrow keys, the Home and End keys, and so on.

Scroll bars appear on an object only if its contents extend beyond the object's borders.  For example, in an MDI form, if part of a child form is hidden behind the border of the parent MDI form, a horizontal scroll bar appears.  Similarly, a vertical scroll bar appears on a grid control when it can't display all of its rows; a vertical scroll bar appears on a text box when it can't display all of its lines of text.  If ScrollBars is set to False, the object will not have scroll bars, regardless of its contents.

If no horizontal scroll bar is specified for a text box and MultiLine is True, the text will automatically wrap even if the WordWrap property is False.

Data Type

Integer (Enumerated or Boolean)


See Also

Help:

MultiLine Property

WordWrap Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Parent Property

See Also	Example

Applies To

Check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, line, list box, menu, OLE control, option button, picture box, shape, text box, timer, vertical scroll bar.

Description

Specifies the form on which a control is located; not available at design time and read-only at run time.

Usage

[form.]control.Parent

Remarks

Use the Parent property to access the properties, methods, or controls of a control's parent form [image] for example, MyButton.Parent.MousePointer = 4.

The Parent property is useful in an application in which you pass controls as arguments.  For example, you might pass a control variable to a general procedure in a module, and use the Parent property to access its parent form.

Note	There is no relationship between the Parent property and the MDIChild property.  There is, however, a parent-child relationship between an MDI form and any forms in your project that have the MDIChild property set to True.

Data Type

Form


See Also

Help:

ActiveControl Property

ActiveForm Property

Programmer's Guide:

Chapter 8, "Objects and Instances"


Parent Property Example

The example passes a control from a form that doesn't have the focus to a procedure in a module, and then prints the state of the control on the parent form.  To try this example, create three forms: Form1, containing a command button; and Form2 and Form3, each containing a check box. You must also create a new module (choose the New Module command from the File menu).  Paste the code into the Declarations sections of the respective forms or module and then press F5 to run the program.

' Enter into Form1:

Sub Form_Load ()

Form2.Show	' Display all forms.

Form3.Show

Form2.AutoRedraw = True

Form3.AutoRedraw = True

End Sub

Sub Command1_Click ()

CheckCheck Form2.Check1	' Call procedure in other module.

CheckCheck Form3.Check1	' And send control as argument.

End Sub

' Enter into Module1:

Sub CheckCheck (Source As Control)

If Source.Value Then

Source.Parent.Cls	' Clear parent form.

Source.Parent.Print "CheckBox is ON"	' Print on parent form.

Else

Source.Parent.Cls	' Clear parent form.

Source.Parent.Print "CheckBox is OFF"	' Print on parent form.

End If

End Sub


Sorted Property

See Also

Applies To

Combo box, list box.

Description

Specifies whether the elements of a combo box or list box are automatically sorted alphabetically; read-only at run time.

Usage

[form.]{combobox | listbox}.Sorted

Setting

The Sorted property settings are:

Setting	Description

True	List items are sorted alphabetically (case-insensitive).

False	(Default) List items are not sorted alphabetically.

Remarks

When set to True, Visual Basic handles almost all necessary string processing to maintain alphabetical order, including changing the index numbers for items as required by the addition or removal of items.

Note	Using the AddItem method to add an element to a specific location in the list may violate the sort order, and subsequent additions may not be correctly sorted.

Data Type

Integer (Boolean)


See Also

Help:

AddItem Method

List Property

ListCount Property

ListIndex Property

RemoveItem Method

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Style Property

See Also

Applies To

Combo box.

Description

Specifies the type of combo box and the behavior of its list box portion; read-only at run time.

Usage

[form.]combobox.Style

Setting

The Style property settings are:

Setting	Description

0	(Default) Dropdown Combo.  Includes a drop-down list and an edit area.  The user can select from the list or type in the edit area.

1	Simple Combo.  Includes an edit area and a list that is always displayed.  The user can select from the list or type in the edit area.  The size of a Simple Combo box includes both the edit and list portions.  By default, a Simple Combo box is sized so that none of the list shows.  Increase the Height property to show more of the list.

2	Dropdown List.  This style only allows selection from the drop-down list.

Remarks

Follow these guidelines in deciding which setting to choose:

Use setting 0 (Dropdown Combo) or setting 1 (Simple Combo) to give the user a list of choices.  Either style enables the user to enter a choice in the edit area.  Style 0 saves space on the form because the list portion closes when the user makes a selection.

Use setting 2 (Dropdown List) to display a fixed list of choices from which the user can select one.  The list portion closes when the user selects an item.

Data Type

Integer (Enumerated)


See Also

Help:

Change Event

Click Event

DblClick Event

DropDown Event

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


TabIndex Property

See Also	Example

Applies To

Check box, combo box, command button, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, label, list box, option button, picture box, text box, vertical scroll bar.

Description

Determines the tab order of a control within its parent form.

Usage

[form.]control.TabIndex[ = index ]

Setting

The valid range is any integer from 0 to (n-1), where n is the number of controls on the form that have a TabIndex property.  Assigning a TabIndex value of less than 0 generates an error.

Remarks

By default, Visual Basic assigns a tab order to controls as you draw them on a form.  Each new control is placed last in the tab order.  If you change the value of a control's TabIndex property to adjust the default tab order, Visual Basic automatically renumbers the TabIndex of other controls to reflect insertions and deletions.  You can make changes at design time using the Properties window or at run time in code.

All controls except menus and timers are included in the tab order.  At run time, invisible or disabled controls and controls that cannot receive the focus (frames and labels) remain in the tab order but are skipped during tabbing.

The TabIndex property is not affected by the ZOrder method.

Note	A control's tab order does not affect its associated access key.  If you press the access key for a frame or label, the focus moves to the next control in the Tab order that can receive the focus.

When loading forms saved as ASCII text, controls with a TabIndex property that aren't listed in the form description are automatically assigned a TabIndex value.  In subsequently loaded controls, if existing TabIndex values conflict with earlier assigned values, the controls are automatically assigned new values.

Data Type

Integer


See Also

Help:

Specifying Access Keys

TabStop Property

ZOrder Method

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


TabIndex Property Example

The example reverses the tab order of a group of buttons by changing the TabIndex property on a command button array.  To try this example, paste the code into the Declarations section of a form that contains four command buttons.  Set the Name property to CommandX for each button to create the control array.  Then press F5 and click the form to reverse the tab order of the buttons.

Sub Form_Click ()

Dim I, X	' Declare variables.

' Reverse tab order by setting start value of X.

If CommandX(0).TabIndex = 0 Then X = 4 Else X = 1

For I = 0 To 3

CommandX(I).Caption = X	' Set caption.

CommandX(I).TabIndex = X - 1	' Set tab order.

If CommandX(0).TabIndex = 3 Then

X = X - 1	' Decrement X.

Else

X = X + 1	' Increment X.

End If

Next I

End Sub


TabStop Property

See Also

Applies To

Check box, combo box, command button, directory list box, drive list box, file list box, grid, horizontal scroll bar, list box, option button, picture box, text box, vertical scroll bar.

Description

Determines whether a user can use the Tab key to set the focus to a control.

Usage

[form.]control.TabStop[ = boolean ]

Setting

The TabStop property settings are:

Setting	Description

True	(Default) Designates the control as a tab stop.

False	Bypasses the control when the user is tabbing, although the control still holds its place in the actual tab order, as determined by the TabIndex property.

Remarks

This property allows you to add or remove a control from the tab order on a form.  For example, instead of moving through each button in an option button group, you can treat the whole group as one tab location.  To do this, set TabStop to True for the first option button in the group and set TabStop to False for the other option buttons in the group.

Data Type

Integer (Boolean)


See Also

Help:

Specifying Access Keys

TabIndex Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Tag Property

See Also	Example

Applies To

Form, MDI form, check box, combo box, command button, common dialog, data control, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, line, list box, menu, OLE control, option button, picture box, shape, text box, timer, vertical scroll bar.

Description

Stores any extra data needed for your program.  Unlike other properties, the value of the Tag property is not used by Visual Basic; you can use this property to identify objects.

Usage

[form.][control.]Tag[ = expression ]

Remarks

By default, the Tag property is set to an empty string ("").

You can use this property to assign an identification string to an object without affecting any of its other property settings or causing side effects.  The Tag property is useful when you need to check the identity of a control or MDI form that is passed as a variable to a procedure.

Tip	At the time you create a new instance of a form, assign a unique value to the Tag property.

Data Type

String


See Also

Help:

Name Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Tag Property Example

The example displays a unique icon for each control being dragged.  To try this example, paste the code into the Declarations section of a form that contains three picture boxes.  Set the DragMode property for Picture1 and Picture2 to 1.  Then press F5. Use the mouse to drag Picure1 or Picture2 over Picture3 controls.

Sub Form_Load ()

Picture1.Tag = "Pic1"

Picture2.Tag = "Pic2"

End Sub

Sub Picture3_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

Const ENTER = 0, LEAVE = 1, OVER = 2

If State = ENTER Then

' Select based on Tag. Name is not available at run time.

Select Case Source.Tag

Case "Pic1"

' Load icon for Picture1.

Source.DragIcon = LoadPicture ("icons\arrows\point03.ico")

Case "Pic2"

' Load icon for Picture 2.

Source.DragIcon = LoadPicture ("icons\arrows\point04.ico")

End Select

ElseIf State = LEAVE Then

' When source is not over Picture3.

Source.DragIcon = LoadPicture ()	'Unload icon.

End If

End Sub


Text Property

See Also	Example

Applies To

Combo box, list box, text box.

Description

Combo box (Style property set to 0 (Dropdown Combo) or to 1 (Simple Combo)) and text box [image] determines the text contained in the edit area.

Combo box (Style property set to 2 (Dropdown List)) and list box [image] determines the selected item in the list box; the value returned is always equivalent to the value returned by the expression List(listindex).  Read-only at design time; read-only at run time.

Usage

[form.]{combobox|listbox|textbox}.Text[ = stringexpression ]

Remarks

At design time only, the defaults for the Text property are:

Combo box and text box [image] the control's Name property.

List box [image] an empty string ("").

For a combo box with Style property set to 0 (Dropdown Combo) or to 1 (Simple Combo), or for a text box, this property is useful for reading the actual string contained in the edit area of the control.  For a setting 2 (Dropdown List) combo box or for a list box, you can use the Text property to determine the currently selected item.

The Text setting for a text box is limited to 2048 characters unless the MultiLine property is True, in which case the limit is about 32k.

Data Type

String


See Also

Help:

SelLength, SelStart, SelText Properties

Value Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Text Property Example

The example illustrates the Text property.  To try this example, paste the code into the Declarations section of a form that contains three text boxes and a command button.  Then press F5 and type something into Text1.

Sub Text1_Change ()

Text2.Text = LCase(Text1.Text)' Display text as lowercase.

Text3.Text = UCase(Text1.Text)	' Display text as uppercase.

End Sub

Sub Command1_Click ()	' Delete text.

Text1.Text = ""

End Sub


Visible Property

See Also	Example

Applies To

Form, MDI form, check box, combo box, command button, common dialog, data control, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, line, list box, menu, OLE control, option button, picture box, shape, text box, vertical scroll bar.

Description

Determines whether an object is visible or hidden.

Usage

[form.][control.]Visible[ = boolean ]

Setting

The Visible property settings are:

Setting	Description

True	(Default) Object is visible.

False	Object is hidden.

Remarks

To hide a control at startup, set the Visible property to False at design time.  Setting this property in code allows you to hide and later redisplay a control at run time in response to a particular event.

Note	Using the Show or Hide method on a form is the same as setting the form's Visible property in code to True or False, respectively.

An MDI child form cannot be hidden.

Data Type

Integer (Boolean)


See Also

Help:

Hide Method

Load Statement

Show Method

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Visible Property Example

The example creates animation using two picture boxes.  To try this example, paste the code into the Declarations section of a form that contains two icon-sized picture boxes.  Set Name to FileCab for both picture boxes to create an array.  Then press F5 and click the picture control to view the animation.

Sub Form_Load ()

Dim I	' Declare variable.

FileCab(0).BorderStyle = 0	' Set BorderStyle.

FileCab(1).BorderStyle = 0

' Load icons into picture boxes.

FileCab(1).Picture = LoadPicture("icons\office\files03b.ico")

FileCab(0).Picture = LoadPicture("icons\office\files03a.ico")

For I = 0 To 1

FileCab(I).Move 400, 400	' Place pictures at same spot.

Next I

FileCab(1).Visible = False	' Set to invisible.

FileCab(0).Visible = True	' Set to visible.

End Sub

Sub FileCab_Click (Index As Integer)

Dim I	' Declare variable.

For I = 0 To 1

' Switch the visibility for both pictures.

FileCab(I).Visible = Not FileCab(I).Visible

Next I

End Sub


WindowState Property

See Also	Example

Applies To

Form, MDI form.

Description

Determines the visual state of a form window at run time.

Usage

[form.]WindowState[ = state ]

Setting

The WindowState property settings are:

Setting	Description

0	(Default) Normal

1	Minimized (shrunk to an icon)

2	Maximized (enlarged to maximum size)

Remarks

Before a form appears, WindowState is always set to Normal (0), regardless of its initial setting.  This is reflected in the Height, Left, ScaleHeight, ScaleWidth, Top, and Width settings.  If a form is hidden after it's been shown, these properties reflect the previous state until the form is shown again, regardless of any changes made to WindowState in the meantime.

Data Type

Integer (Enumerated)


See Also

Help:

Load Event

Paint Event

Resize Event

Programmer's Guide:

Chapter 17, "Interacting with the Environment"


WindowState Example

The example hides a dialog box (Form2) when the parent form (Form1) is minimized and redisplays the dialog box when the parent form is returned to either a normal or maximized state.  To try this example, paste the code into the Declarations section of Form1 of an application that contains two forms.  Press F5 to start the example.  Move Form1 around so you can see both forms.  Then minimize or maximize the form and observe the action of Form2.

Sub Form_Load ()

Form2.Show	' Show Form2.

End Sub

Sub Form_Resize ()

Const MIN = 1

If Form1.WindowState = MIN Then	' If parent form is minimized,

Form2.Visible = False	' Hide Form2.

Else	' If form is not minimized,

Form2.Visible = True	' Restore Form2.

End If

End Sub


AutoRedraw Property

See Also	Example

Applies To

Form, picture box.

Description

Determines the output from a graphics method to a persistent bitmap.

Usage

[form.][picturebox.]AutoRedraw[ = {True|False}]

Setting

The AutoRedraw property settings are:

Setting	Description

True	Enables automatic repainting of a form or picture box. Graphics and print output are written to the screen and to an image stored in memory. The object does not receive Paint events; it is repainted when necessary, using the memory image.

False	(Default) Disables automatic repainting of an object and writes graphics or print output only to the screen. Visual Basic invokes the object's Paint event when necessary to repaint the object.

Remarks

This property is central to working with the graphics methods [image] Circle, Cls, Line, Point, Print, and PSet.  Setting AutoRedraw to True automatically redraws the output from these methods in a form or picture box when, for example, the object is resized or redisplayed after being hidden by another window.

You can reset AutoRedraw in code at run time to alternate between drawing persistent graphics (such as a background or grid) and temporary graphics. If you disable AutoRedraw, previous output becomes part of the background screen. When AutoRedraw is set to False, background graphics are not deleted if you clear the drawing area with the Cls method. Setting AutoRedraw back to True and then using Cls clears the background graphics.

Note	If you set the BackColor property, all graphics and print output, including the persistent bitmap, are erased.  In general, all graphics should be in a Paint event unless AutoRedraw is set to True.

To retrieve the persistent bitmap created when AutoRedraw is set to True, use the Image property.  To pass the persistent bitmap to a Windows API when AutoRedraw is set to True, use the object's hDC property.

When you minimize a form whose AutoRedraw property is set to False, the ScaleHeight and ScaleWidth properties are set to icon size.  When AutoRedraw is set to True, ScaleHeight and ScaleWidth remain the size of the restored window.

Data Type

Integer (Boolean)


See Also

Help:

Circle Method

Cls Method

Image Property

Line Method

Paint Event

Point Method

Print Method

PSet Method

ScaleHeight, ScaleWidth Properties

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


AutoRedraw Property Example

The example alternately displays two drawings on a picture box control: a persistent filled circle and temporary vertical lines.  Click the picture box to draw or redraw the lines.  Resizing the form requires the temporary drawing to be redrawn.  To try this example, paste the code into the Declarations section of a form that has a picture box control named Picture1.  Press F5 to run the program and click the picture each time you resize the form.

Sub Form_Load ()
Picture1.ScaleHeight = 100	' Set scale to 100.
Picture1.ScaleWidth = 100
Picture1.AutoRedraw = True	' Turn on AutoRedraw.
Picture1.ForeColor = 0	' Set ForeColor.
Picture1.FillColor = QBColor(9)	' Set FillColor.
Picture1.FillStyle = 0	' Set FillStyle.
Picture1.Circle (50, 50), 30	' Draw a circle.
Picture1.AutoRedraw = False	' Turn off AutoRedraw.
End Sub

Sub Picture1_Click ()
Dim I	' Declare variable.
Picture1.ForeColor = Rgb(Rnd * 255, 0, 0)	' Select random color.
For I = 5 To 95 Step 10	' Draw lines.
Picture1.Line (I, 0)-(I, 100)
Next
End Sub


Default Property

See Also

Applies To

Command button.

Description

Determines which command button is the default button on a form.

Usage

[form.]commandbutton.Default[ = {True|False}]

Setting

The Default property settings are:

Setting	Description

True 	The command button is the default button.  Only one button on a form can be the default button.  When Default is set to True for one button, it is automatically set to False for all other buttons on the form.  When the button's Default property is True and its parent form is active, the user can choose the button (invoking its Click event) by pressing the Enter key.  Any other control with the focus does not receive a keyboard event (KeyDown, KeyPress, or KeyUp) for the Enter key unless the user has moved the focus to another command button on the same form.  In this case, pressing Enter chooses that button instead of the default button.

False 	(Default) The command button is not the default button.

Remarks

For a form or dialog box that supports an irreversible action such as a delete operation, make the Cancel button the default button by setting its Default property to True.

Data Type

Integer (Boolean)


See Also

Help:

Cancel Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Fonts Property

See Also	Example

Applies To

Printer object, Screen object.

Description

Specifies all font names available for the current display device or active printer when enumerated from 0 to FontCount - 1.  Not available at design time; read-only at run time.

Usage

{Printer|Screen}.Fonts(index)

Remarks

The Fonts property works in conjunction with the FontCount property, which returns the number of font names available for the object.  Fonts available in Visual Basic vary according to your system configuration, display devices, and printing devices.  Use both the Fonts and the FontCount properties to get information about available screen or printer fonts.

Data Type

String


See Also

Help:

FontBold, FontItalic, FontStrikethru, FontTransparent, FontUnderline Properties

FontName Property

FontSize Property

TextHeight Method

TextWidth Method

Programmer's Guide:

Chapter 16, "Displaying and Printing Information"


Fonts Property Example

The example prints a list of the printer fonts in a list box.  To try this example, paste the code into the Declarations section of a form that has a list box control named List1.  Press F5 to run the program and then click the form.

Sub Form_Click ()
Dim I	' Declare variable.
For I = 0 To Printer.FontCount -1	' Determine number of fonts.
List1.AddItem Printer.Fonts (I)	' Put each font into list box.
Next I
End Sub


Image Property

See Also	Example

Applies To

Form, picture box.

Description

Specifies a handle to a persistent bitmap; the handle is provided by the system.  Not available at design time; read-only at run time.

Usage

[form.][picturebox.]Image

Remarks

This property is a Microsoft Windows environment bitmap handle.

An object's AutoRedraw property determines whether the repainting of an object occurs with a persistent bitmap or through Paint events.  The operating environment identifies an object's persistent bitmap by assigning a handle to it; you can use the Image property to get this handle.

An Image value exists regardless of the setting for AutoRedraw.  If AutoRedraw is True and nothing has been drawn, the image contains only the color set with the BackColor property and the picture.

You can assign the value of Image to the Picture property.  The Image property also provides a value to pass to Windows API calls.

The Image, DragIcon, and Picture properties must be used directly when assigning values to other properties, when saving with the SavePicture statement, or when placing something onto the Clipboard.  You cannot assign these to temporary variables and then use the results.

The AutoRedraw property can cause Image, which is a handle to a bitmap, to change.  When AutoRedraw is True, an object's hDC property becomes a handle to a device context that contains the Image bitmap.

Data Type

Integer


See Also

Help:

AutoRedraw Property

BackColor Property

DragIcon Property

Paint Event

Picture Property

SavePicture Statement

Programmer's Guide:

Chapter 16, "Displaying and Printing Information"


Image Property Example

The example draws a circle in the first picture box each time you click it.  When you click the second picture box, the picture from the first picture box is copied into it.  To try this example, paste the code into the Declarations section of a form that has two large, equal-sized picture box controls.  Press F5 to run the program and then click the picture box controls.

Form_Load ()
Picture1.AutoReDraw = True	' Set AutoRedraw True.
End Sub

Sub Picture1_Click ()
Dim PW, PH	' Declare variables.
Picture1.FillStyle = 0	' Set FillStyle to solid.
Picture1.FillColor = QBColor(Int(Rnd * 15))	' Choose random color.
PW = Picture1.ScaleWidth	' Set ScaleWidth.
PH = Picture1.ScaleHeight	' Set ScaleHeight.
' Draw a circle in random location.
Picture1.Circle (Int(Rnd * PW), Int(Rnd * PH)), 250
End Sub

Sub Picture2_Click ()
Picture2.Picture = Picture1.Image	' Copy Image to Picture2.
End Sub


MousePointer Property

See Also	Example

Applies To

Form, check box, combo box, command button, data control, directory list box, drive list box, file list box, frame, horizontal scroll bar, image, label, list box, option button, picture box, Screen object, text box, vertical scroll bar.

Description

Determines the type of mouse pointer displayed when the mouse is over a particular part of a form or control at run time.

Usage

{[form.][control.]|Screen.}MousePointer[ = setting ]

Setting

The MousePointer property settings are:

Setting	Description

0	(Default) Shape determined by the control

1	Arrow

2	Cross (cross-hair pointer)

3	I-Beam

4	Icon (small square within a square)

5	Size (four-pointed arrow pointing north, south, east, west)

6	Size NE SW (double arrow pointing northeast and southwest)

7	Size N S (double arrow pointing north and south)

8	Size NW SE (double arrow pointing northwest and southeast)

9	Size W E (double arrow pointing west and east)

10	Up Arrow

11	Hourglass (wait)

12	No Drop

Remarks

The MousePointer property controls the shape of the mouse pointer.  This property is useful when you want to indicate changes in functionality as the mouse pointer passes over controls on a form or dialog box.  The Hourglass setting (11) is useful for indicating that the user should wait for a process or operation to finish.

Note	When set for the Screen object, MousePointer changes across the entire screen; that is, it overrides all MousePointer settings for other objects and other applications.  Setting MousePointer to 0 (default) restores the previous behavior.

Data Type

Integer


See Also

Help:

DragIcon Property

MouseMove Event

Programmer's Guide:

Chapter 12, "Responding to Mouse Events"


MousePointer Property Example

The example changes the pointer to an hourglass while circles are drawn across your screen, and then changes the hourglass back to a pointer at the end of the procedure.  To try this example, paste the code into the Declarations section of a form.  Press F5 to run the program and then click the form.

Sub Form_Click ()
Dim I	' Declare variable.
Screen.MousePointer = 11	' Change pointer to hourglass.
For I = 0 To ScaleWidth Step 50	' Set random color and draw circles on form.
ForeColor = RGB(Rnd * 255, Rnd * 255, Rnd * 255)
Circle (I, ScaleHeight * Rnd), 400
Next
Screen.MousePointer = 0	' Return pointer to normal.
End Sub


MultiLine Property

See Also

Applies To

Text box.

Description

Specifies whether a text box can accept and display multiple lines of text; read-only at run time.

Usage

[form.]textbox.MultiLine

Setting

The MultiLine property settings are:

Setting	Description

True 	Allows multiple lines of text.

False 	(Default) Ignores carriage returns and restricts data to a single line.

Remarks

A multiline text box wraps text as the user types text extending beyond the display area.

You can also add scroll bars to larger text boxes using the ScrollBars property.  If no horizontal scroll bar is specified, the text in a multiline text box automatically wraps.

Note	On a form with no default button, pressing Enter in a multiline text box moves the focus to the next line.  If a default button exists, you must press Ctrl+Enter to move to the next line.

Data Type

Integer (Boolean)


See Also

Help:

Default Property

ScrollBars Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Picture Property

See Also	Example 1	Example 2

Applies To

Form, image, OLE control, picture box.

Description

Determines a graphic to be displayed in a control.  For OLE control: not available at design time and read-only at run time.

Usage

[form.][image. | ole. | picturebox.]Picture[ = picture ]

Setting

The Picture property settings are:

Setting	Description

(none)	(Default) No picture.

(Bitmap, icon, metafile)	Specifies a graphic.  You can load the graphic from the Properties window at design time.  At run time, you can also set this property using the LoadPicture function on a bitmap, icon, or metafile.

Remarks

At design time, you can transfer a graphic with the Clipboard using the Copy, Cut, and Paste commands on the Edit menu.  At run time, you can use Clipboard methods such as GetData, SetData, and GetFormat with the non-text Clipboard formats CF_BITMAP, CF_METAFILE, and CF_DIB, as defined in CONSTANT.TXT, a Visual Basic file that specifies system defaults.

When setting the Picture property at design time, the graphic is saved and loaded with the form.  If you create an executable file, the file contains the image.  When you load a graphic at run time, the graphic is not saved with the application.  Use the SavePicture statement to save a graphic from a form or picture box into a file.

Note 	At run time, the Picture property can be set to any other object's DragIcon, Icon, Image, or Picture property, or you can assign it the graphic returned by the LoadPicture function.

Data Type

Integer


See Also

Help:

AutoRedraw Property

Icon Property

LoadPicture Function

SavePicture Statement

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Picture Property Example 1

The example loads icons from the Visual Basic Icon Library into two of three picture boxes.  When you click the form, the third picture box is used to switch the bitmaps.  You can use any two icons.  Paste the code into the Declarations section of a form that has three small picture boxes (for Picture3, set Visible = False).  Press F5 to run the program and then click the form.

Sub Form_Load ()
' Load the bitmaps.
Picture1.Picture = LoadPicture("icons\computer\trash02a.ico")
Picture2.Picture = LoadPicture("icons\computer\trash02b.ico")
End Sub

Sub Form_Click ()
' Swap the bitmaps.
Picture3.Picture = Picture1.Picture
Picture1.Picture = Picture2.Picture
Picture2.Picture = Picture3.Picture
' Set the picture to none (not necessary if not visible).
Picture3.Picture = LoadPicture()
End Sub


Picture Property Example 2

The example pastes a bitmap from the Clipboard into a picture box. To find the value of the CF_formats, look at the CONSTANT.TXT file or load it into a module.  To try this example, paste the code into the Declarations section of a form that has a picture box.  Press F5 and then in another application, copy a picture onto the Clipboard, switch to Visual Basic, and click the form.

Sub Form_Click ()
Const CF_BITMAP = 2
Picture1.Picture = Clipboard.GetData(CF_BITMAP)
End Sub


ActiveControl Property

See Also	Example1	Example2

Applies To

Form, MDI form, Screen object.

Description

Specifies the control that has the focus; when a form is referenced, as in ChildForm.ActiveControl, specifies the control that would have the focus if the referenced form were active.  Invalid if all controls on the given form are invisible or disabled.  Not available at design time; read-only at run time.

Usage

{form.|mdiform.|Screen.}ActiveControl

Remarks

You can use ActiveControl to access a control's properties or to invoke its methods [image] for example, Screen.ActiveControl.Tag = "0".

When a control has the focus, it is the active control on the screen (Screen.ActiveControl).  In addition, each form can have a control that is the active control on that form (Form.ActiveControl), regardless of whether or not the form is active.  You can, therefore, write code that manipulates the active control on each form in your application, even when the form is not the active form.

This property is especially useful in an MDI application where a button on a toolbar must initiate an action on a control in an MDI child form.  When a user clicks a Copy button on the toolbar, your code can reference the text in the active control on the MDI child form [image] for example, ActiveForm.ActiveControl.SelText.

Note	If you plan to pass Screen.ActiveControl to a procedure, you must declare the argument in that procedure with the generic type (As Control) rather than a specific form type (As TextBox or As ListBox) [image] even if ActiveControl always refers to the same type of control.

Data Type

Control


See Also

Help:

ActiveForm Property

GotFocus Event

LostFocus Event

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 14, "Multiple-Document Interface (MDI) Applications"


ActiveControl Property Example 1

The example displays the text of the active control.  To try this example, paste the code into the Declarations section of a form that contains a text box, a label, and a command button.  Then press F5 and click the form.

Sub Form_Click ()
If TypeOf Screen.ActiveControl Is TextBox Then
Label1.Caption = Screen.ActiveControl.Text
Else
Label1.Caption = "Button: " + Screen.ActiveControl.Caption
End If
End Sub


ActiveForm, ActiveControl Properties Example 2

The example shows how you can use the Clipboard in cut, copy, paste, and delete operations using buttons on a toolbar.  To try this example, draw a text box and a check box on Form1, then create a new MDI form.  On the MDI form, draw a picture box and then draw a command button in the picture box.  Set the Index property on the command button to 0 (this creates a control array).  On Form1, set the MDIChild property to True.

To run the example, copy the code into the Declarations section of the MDI form and press F5.  Notice that if the check box has the focus, the buttons don't work.

Sub MDIForm_Load ()
Dim I	' Declare variable.
Command1(0).Move 0, 0, 700, 300	' Position button on toolbar.
For I = 1 To 3	' Create other buttons.
Load Command1(I)	' Create button.
Command1(I).Move I * 700, 0, 700, 300	' Place and size button.
Command1(I).Visible = True	' Display button.
Next I
Command1(0).Caption = "Cut"	' Set button captions.
Command1(1).Caption = "Copy"
Command1(2).Caption = "Paste"
Command1(3).Caption = "Del"
End Sub

Sub Command1_Click (Index As Integer)
' ActiveForm refers to the active form in the MDI form.
If TypeOf ActiveForm.ActiveControl Is TextBox Then
Select Case Index
Case 0	' Cut.
' Copy selected text to Clipboard.
Clipboard.SetText ActiveForm.ActiveControl.SelText
' Delete selected text.
ActiveForm.ActiveControl.SelText = ""
Case 1	' Copy.
' Copy selected text to Clipboard.
Clipboard.SetText ActiveForm.ActiveControl.SelText
Case 2	' Paste.
' Put Clipboard text in text box.
ActiveForm.ActiveControl.SelText = Clipboard.GetText()
Case 3	' Delete.
' Delete selected text.
ActiveForm.ActiveControl.SelText = ""
End Select
End If
End Sub


ActiveForm Property

See Also	Example1	Example2

Applies To

MDI form, Screen object.

Description

Specifies the form that is the active window,.  If an MDI form is active, or if an MDI form is referenced, specifies the active MDI child form.  Not available at design time; read-only at run time.

Usage

{mdiform|Screen}.ActiveForm

Remarks

Use the ActiveForm property to access a form's properties or to invoke its methods [image] for example, Screen.ActiveForm.Mousepointer = 4.

This property is especially useful in an MDI application where a button on a toolbar must initiate an action on a control in a MDI child form.  When a user clicks a Copy button on the toolbar, your code can reference the text in the active control on the MDI child form [image] for example, ActiveForm.ActiveControl.SelText.

When a control on a form has the focus, that form is the active form on the screen (Screen.ActiveForm).  In addition, an MDI form can have one child form that is the active form within the context of the MDI parent (MDIForm.ActiveForm).  The ActiveForm on the screen is not necessarily the same as the ActiveForm in the MDI form, such as when a dialog form is active.  For this reason, you should specify the MDI form with ActiveForm when there is a chance of a dialog being the ActiveForm.

Note	When an active MDI child form is not maximized, the title bars of both the parent form and the child form appear active.

If you plan to pass Screen.ActiveForm or MDIForm.ActiveForm to a procedure, you must declare the argument in that procedure with the generic type (As Form) rather than a specific form type (As MyForm) [image] even if ActiveForm always refers to the same type of form.

Data Type

Form


See Also

Help:

Activate, Deactivate Events

MDIChild Property

Programmer's Guide:

Chapter 14, "Multiple-Document Interface (MDI) Applications"


ActiveForm Property Example

The example prints the time on the currently active child form in an MDI form.  To try this example, create an MDI form, draw a picture box on it and draw a command button in the picture box.  In Form1, set the MDIChild property to True.  (You can also set AutoRedraw to True to keep text on the form even after covering it with another form.)  Paste the appropriate code into the Declarations section of each form and press F5.

' Copy this code into the MDI form.
Sub MDIForm_Load ()
Dim NewForm As New Form1	' Create new instance of Form1.
NewForm.Show
End Sub

' Copy this code into Form1.
Sub Command1_Click ()
' Print the time on the current form.
ActiveForm.Print "The time is " & Format(Now, "Long Time")
End Sub


Align Property

See Also	Example

Applies To

Picture box.

Description

Determines whether a picture box can appear in any size anywhere on a form, or whether it appears at the top or bottom of the form automatically sized to fit the form's width.

Usage

[form.]picturebox.Align[ = numericexpression ]

Setting

The Align property settings are:

Setting	Description

0	(Default in a non-MDI form) None [image] size and location can be set at design time or in code.  This setting is ignored if the picture box is on an MDI form.

1	(Default in an MDI form) Top [image] picture box is at the top of the form and its width is equal to the form's ScaleWidth property setting.

2	Bottom [image] picture box is at the bottom of the form and its width is equal to the form's ScaleWidth property setting.

Remarks

You can use the Align property to quickly create a toolbar or status bar at the top or bottom of a form.  As users change the size of the form, a picture box with Align set to 1 or 2 automatically resizes to fit the width of the form.

A picture box is the only standard control that can be placed on an MDI form.  The client area of an MDI form is defined by the space not covered by picture boxes.  When an MDI child form is maximized within the parent MDI form, it will not cover any picture boxes.

Data Type

Integer


See Also

Help:

Using MDI Features

ScaleHeight, ScaleWidth Properties

Programmer's Guide:

Chapter 14, "Multiple-Document Interface (MDI) Applications"


Align Property Example

The example uses a picture box as a toolbar on an MDI form, with a command button to move the picture box from the top to the bottom of the form.  To try this example, create a new MDI form and set the MDIChild property of the other form to True.  Draw a picture box and put a command button on the picture box.  Paste the code into the Declarations section of Form1 and then press F5.

Sub Command1_Click ()
If Picture1.Align = 1 Then
Picture1.Align = 2	' Align to bottom of form.
Else
Picture1.Align = 1	' Align to top of form.
End If
End Sub


BackStyle Property

See Also

Applies To

Label, shape.

Description

Determines whether a label or the background of a shape is transparent or opaque.

Usage

[form.]{label|shape}.BackStyle[ = numericexpression ]

Setting

The BackStyle property settings are:

Setting	Description

0	Transparent [image] background color and any graphics are visible behind the control.

1	(Default) Opaque [image] the control's BackColor fills the control and obscures any color or graphics behind it.

Remarks

You can use the BackStyle property to create transparent controls when you are using a background color on a form or picture box, or when you want to place a control over a picture.  Use an opaque control when you want it to stand out on a busy background.

A control's BackColor property is ignored if BackStyle = 0.

Data Type

Integer


See Also

Help:

BackColor, ForeColor Properties

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"

Chapter 16, "Displaying and Printing Information"


Columns Property

See Also	Example

Applies To

List box.

Description

Determines whether a list box scrolls vertically or horizontally.  If it scrolls horizontally, determines how many columns are displayed.

Usage

[form.]listbox.Columns

Setting

The Columns property settings are:

Setting	Description

0	(Default) Items are arranged in a single column and the list box scrolls vertically.

1 to n	Items are arranged in snaking columns, filling the first column, then the second column, and so on.  The list box scrolls horizontally and displays the specified number of columns.

Remarks

For horizontal-scrolling list boxes, the column width is equal to the width of the list box divided by the number of columns.

This property can't be set to zero or changed from zero at run time [image] that is, you can't change a multi-column list box to a single-column list box, or a single-column list box to a multi-column list box, at run time.  However, you can change the number of columns in a multi-column list box at run time.

Data Type

Integer


See Also

Help:

AddItem Method

Grid Control

List Property

ListCount Property

ListIndex Property

RemoveItem Method

TopIndex Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Columns Property Example

The example illustrates how the two different kinds of list boxes work when they contain the same data.  To try this example, paste the code into the Declarations section of a form that contains two list boxes.  .Set  the Columns property to 2 for List2.  Then press F5 and click the form

Sub Form_Load ()
Dim I	' Declare variable.
List1.Move 50, 50, 2000, 1750	' Arrange list boxes.
List2.Move 2500, 50, 3000, 1750
For I = 0 To Screen.FontCount -1	' Fill both boxes with
List1.AddItem Screen.Fonts(I)	' names of screen fonts.
List2.AddItem Screen.Fonts(I)
Next I
End Sub


HelpContextID Property

See Also	Example

Applies To

Form, MDI form, check box, combo box, command button, data control, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, list box, menu, OLE control, option button, picture box, text box, vertical scroll bar.

Description

Determines an associated context number for an object.  Used to provide context-sensitive Help for your application.

Usage

[form.][control.]HelpContextID[ = numericexpression ]

Remarks

For context-sensitive Help on an object in your application, you must assign the same context number to both the object and to the associated Help topic when you compile your Help file.

If you've created a Windows environment Help file for your application and set the application's HelpFile property, when a user presses the F1 key, Visual Basic automatically calls Help and requests the topic identified by the current context number.

The current context number is the value of HelpContextID for the object that has the focus.  If HelpContextID is 0, then Visual Basic looks in the HelpContextID of the object's container, and then that object's container, and so on.  If a non-zero current context number can't be found, the F1 key is ignored.

Note	Building a Help file requires the Microsoft Windows Help Compiler, which is available with the Visual Basic Professional Developer's Edition.

Data Type

Long integer


See Also

Help:

HelpFile Property

Visual Basic Professional Developer's Edition:

Help Compiler Guide


HelpFile Property

See Also	Example

Applies To

App object, common dialog.

Description

Determines the name of the Microsoft Windows Help file for an application.

Usage

{[form.]cmdialog|App}.HelpFile[ = filename]

Remarks

If you've created a Microsoft Windows Help file for your application and set the application's HelpFile property, Visual Basic automatically calls Help when a user presses the F1 key.  If there is a context number in the HelpContextID property for either the active control or the active form, Help displays a topic corresponding to the current Help context; otherwise it displays the main contents screen.

Note	Building a Help file requires the Microsoft Windows Help Compiler, which is available with the Visual Basic Professional Developer's Edition.

Data Type

String


See Also

Help:

HelpContextID Property

Visual Basic Professional Developer's Edition:

Help Compiler Guide


HelpContextID, HelpFile Properties Example

The example uses topics in the Visual Basic Help file and demonstrates how to specify context numbers for Help topics.  To try this example, paste the code into the Declarations section of a form that contains a text box and a frame with an option button inside the frame.  Then press F5.  Once the program is running, move the focus to one of the components and press F1.

' Actual context numbers from the Visual Basic Help file.
Const winColorPalette = 21004	' Define constants.
Const winToolbox = 21001
Const winCodeWindow = 21005

Sub Form_Load ()
App.HelpFile = "vb.hlp"
Frame1.HelpContextID = winColorPalette
Text1.HelpContextID = winToolbox
Form1.HelpContextID = winCodeWindow
End Sub


HideSelection Property

See Also	Example

Applies To

Text box.

Description

Specifies whether selected text appears highlighted when a control loses the focus.  Read-only at run time.

Usage

[form.]textbox.HideSelection

Setting

The HideSelection property settings are:

Setting	Description

True	(Default) Selected text does not appear selected when the control loses the focus.

False	Selected text appears selected when the control loses the focus.

Remarks

You can use this property to indicate which text is selected while another form or a dialog box has the focus [image] for example, in a spell-checking routine.

Data Type

Integer (Boolean)


See Also

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


HideSelection Property Example

The example lets you select text in each form and change the focus between forms by clicking the title bar.  In one form, the selection will remain visible even when the form is not active.  To try the example, create two forms and draw a text box on each.  Set the MultiLine property to True for both text boxes, and set the HideSelection property to False for one of the text boxes.  Paste the code into the Declarations section of both form modules and press F5.

Sub Form_Load ()
Open "constant.txt" For Input As 1	' Load file into text box.
Text1.Text = Input$(LOF(1), 1)
Close 1
Form2.Visible = True	' Load Form2, if not already loaded.
' Position forms side by side.
Form1.Move 0, 1050, Screen.Width / 2, Screen.Height
Form2.Move Screen.Width / 2, 1050, Screen.Width / 2, Screen.Height
' Enlarge text box to fill form.
Text1.Move 0, 0, ScaleWidth, ScaleHeight
End Sub


ItemData Property

See Also	Example

Applies To

Combo box, list box.

Description

This property is an array of long integer values with the same number of items as a control's List property.  Not available at design time.

Usage

[form.]{combobox|listbox}.ItemData(listindex)[ = numericexpression ]

Remarks

Use the ItemData property to associate a specific number with each item in a combo box or list box.  You can then use these numbers in code to identify the items.  For example, you can use an employee's identification number to identify each employee name in a list box.  When you fill the list box, also fill the corresponding elements in the ItemData array with the employee numbers.

A typical use of the ItemData property is for an index into an array of data structures associated with items in a list box.

Note	When you insert an item into a list with the AddItem method, an item is automatically inserted in the ItemData array as well.  However, the value is not reinitialized to zero; it retains the value that was in that position before you added the item to the list.  When you use the ItemData property, be sure to set its value when adding new items to a list.

Data Type

Long integer


See Also

Help:

AddItem Method

List Property

ListIndex Property

NewIndex Property

RemoveItem Method

Selected Property

TopIndex Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


ItemData and NewIndex Properties Example

The example fills a list box with employee names and fills the ItemData array with employee numbers using NewIndex to keep the numbers synchronized with the sorted list.  A label displays the name and number of an item when the user makes a selection.  To try this example, paste the code into the Declarations section of a form that contains a list box and a label.  Set the Sorted property for the list box to True.  Then press F5 and click the list box.

Sub Form_Load ()
' Fill List1 and ItemData array with
' corresponding items in sorted order.
List1.AddItem "Judy Phelps"
List1.ItemData(List1.NewIndex) = 42310
List1.AddItem "Chien Lieu"
List1.ItemData(List1.NewIndex) = 52855
List1.AddItem "Mauro Sorrento"
List1.ItemData(List1.NewIndex) = 64932
List1.AddItem "Cynthia Bennet"
List1.ItemData(List1.NewIndex) = 39227
End Sub

Sub List1_Click ()
' Append the employee number and the employee name.
Msg = List1.ItemData(List1.ListIndex) & " "
Msg = Msg & List1.List(List1.ListIndex)
Label1.Caption = Msg
End Sub


KeyPreview Property

See Also	Example

Applies To

Form.

Description

Determines whether form keyboard events are invoked before control keyboard events.  The keyboard events are KeyDown, KeyUp, and KeyPress.

Usage

[form.]KeyPreview[ = {True|False} ]

Setting

The KeyPreview property settings are:

Setting	Description

True	The form receives keyboard events first, then the active control receives keyboard events.

False	(Default) The active control receives keyboard events; the form does not.

Remarks

You can use this property to create a keyboard-handling procedure for a form.  For example, when an application uses function keys, you'll want to process the keystrokes at the form level rather than writing code for each control that might receive keystroke events.

If a form has no visible and enabled controls, it automatically receives all keyboard events.

To handle keyboard events only at the form level and not allow controls to receive keyboard events, set KeyAscii to 0 in the form's KeyPress event, and set KeyCode to 0 in the form's KeyDown event.

Data Type

Integer (Boolean)


See Also

Help:

KeyDown, KeyUp Events

KeyPress Event

Programmer's Guide:

Chapter 3 "Creating and Using Controls"


KeyPreview Property Example

The example creates a form keyboard handler in the KeyDown event.  Each of the first four function keys presents a different message.  To try this example, paste the code into the Declarations section of a form.  Then press F5.  Once the program is running, press any one of the first four function keys.

' Values from CONSTANT.TXT.
Const KEY_F1 = &H70
Const KEY_F2 = &H71
Const KEY_F3 = &H72
Const KEY_F4 = &H73

Sub Form_Load ()
KeyPreview = True
End Sub

Sub Form_KeyDown (KeyCode As Integer, Shift As Integer)
Select Case KeyCode
Case KEY_F1: MsgBox "F1 is your friend."
Case KEY_F2: MsgBox "F2 could copy text."
Case KEY_F3: MsgBox "F3 could paste text."
Case KEY_F4: MsgBox "F4 could format text."
End Select
End Sub


MaxLength Property

See Also	Example

Applies To

Text box.

Description

Determines whether there is a limit to the length of the Text property.  The default for the MaxLength property is 0, indicating no maximum other than that created by memory constraints on the user's system for single line text boxes, and a maximum of about 32K for multiline text boxes.  Any number larger than 0 indicates the maximum number of characters.

Usage

[form.]textbox.MaxLength[ = numericexpression ]

Remarks

Use the MaxLength property to limit the number of characters a user can enter into a text box.

If text longer than MaxLength is assigned to a text box from code, no error occurs; however, only the maximum number of characters is assigned to the Text property and extra characters are truncated.  Changing this property doesn't affect the current contents of a text box but will affect any subsequent changes to the contents.

Data Type

Integer


See Also

Len Function

MultiLine Property


MaxLength Property Example

The example uses a numerical value in one text box to limit the length of text in the other text box.  To try this example, paste the code into the Declarations section of a form that contains two text boxes.  Make Text1 fairly large.  Then press F5.  Enter a number into Text2 and other text into Text1.

Sub Text1_Change ()
Text1.MaxLength = Text2.Text
End Sub


MDIChild Property

See Also	Example

Applies To

Form.

Description

Specifies whether a form will appear as an MDI child form inside an MDI form.  Read-only at run time.

Usage

form.MDIChild

Setting

The MDIChild property settings are:

Setting	Description

True	The form is an MDI child form and appears inside the parent MDI form.

False	(Default) The form is not an MDI child form.

Remarks

Use this property when creating a Multiple-Document Interface (MDI) application.  At run time, forms with this property set to True appear inside an MDI form.  An MDI child form can be maximized, minimized, and moved, all inside the parent MDI form.

When working with MDI child forms, keep the following in mind:

At run time, when an MDI child form is maximized, its caption is combined with that of the parent MDI form.

At design time, an MDI child form appears like any other form, since the form appears inside the parent form only at run time.  An MDI child form's icon in the Project window is different from icons for other kinds of forms.

MDI child forms can't be hidden and can't be modal.

The initial size and placement of MDI child forms is controlled by the Windows environment unless you specifically set it in the Form_Load procedure.

If an MDI child form is referenced before the parent is loaded, the parent MDI form is automatically loaded.  However, if the parent MDI form is referenced before loading an MDI child form, the child form is not loaded.

Note	When running under the Microsoft Windows 3.0 graphical environment, all MDI child forms have sizable borders, a Control-menu box, and Minimize and Maximize buttons, regardless of the settings of the BorderStyle, ControlBox, MinButton, and MaxButton properties.

Any reference to an MDI form, including reading or setting properties, causes the form to load and become visible.

Data Type

Integer (Boolean)


See Also

Help:

ActiveControl Property

ActiveForm Property

BorderStyle Property

ControlBox Property

MaxButton Property

MinButton Property

WindowList Property

Programmer's Guide:

Chapter 8, "Objects and Instances"

Chapter 14, "Multiple-Document Interface (MDI) Applications"


MDIChild Property Example

The example presents an MDI form with an MDI child form and then creates another instance of the MDI child form.  To try this example, set MDIChild to True on Form1, and create an MDI form with the New MDI Form command on the File menu.  Copy the code into the Declarations section of the MDIForm and press F5 to run the program.

Sub MDIForm_Load ()
Dim NewForm As New Form1	' Declare new form.
NewForm.Show	' Show new form.
End Sub


MultiSelect Property

See Also	Example

Applies To

File list box, list box.

Description

Specifies whether a user can make multiple selections in a file list box or list box and how the multiple selections can be made.  Read-only at run time.

Usage

[form.]{filelistbox|listbox}.MultiSelect

Setting

The MultiSelect property settings are:

Setting	Description

0	(Default) Multiple selection is not allowed.

1	Simple multiple selection.  A click or the Spacebar selects or deselects an item in the list.  (Arrow keys move the pre-select focus.)

2	Extended multiple selection.  Shift+click or Shift+arrow key extends the selection from the previously selected item to the current item.  Ctrl+click selects or deselects an item in the list.

Data Type

Integer


See Also

Help:

AddItem Method

Clear Method

List Property

ListCount Property

NewIndex Property

RemoveItem Method

Selected Property

TopIndex Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


MultiSelect, Selected Properties Example

The example fills a list box with the names of your screen fonts and illustrates how the MultiSelect property affects the behavior of a list box.  To try the example, create two list boxes and a command button on a form.  In the first list box, set MultiSelect to 1 or 2.  At run time, select several items in the first list and then click the command button.  All selected items appear in the second list box.  Run the example several times with different settings of the MultiSelect property.  Copy the code into the Declarations section and press F5 to run the program.

Sub Form_Load ()
Dim I	' Declare variable.
' Fill the list with screen font names.
For I = 0 To Screen.FontCount - 1
List1.AddItem Screen.Fonts(I)
Next I
End Sub

Sub Command1_Click ()
Dim I	' Declare variable.
' Clear all items from the list.
List2.Clear
' If an item is selected, add it to List2.
For I = 0 To List1.ListCount - 1
If List1.Selected(I) Then
List2.AddItem List1.List(I)
End If
Next I
End Sub


NewIndex Property

See Also	Example

Applies To

Combo box, list box.

Description

Specifies the index of the item most recently added to a combo box or list box.  Not available at design time; read-only at run time.

Usage

[form.]{combobox|listbox}.NewIndex

Remarks

This property is useful with sorted lists when you need a list of values that correspond to each item in the ItemData property array.  As you add an item in a sorted list, Visual Basic inserts the item in the list alphabetically.  This property tells you where the item was inserted so that you can insert a corresponding value in the ItemData property at the same index.

NewIndex will return -1 if there are no items in the list or if an item has been deleted since the last item was added.

Data Type

Integer


See Also

Help:

AddItem Method

Clear Method

List Property

ListCount Property

MultiSelect Property

RemoveItem Method

Selected Property

TopIndex Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


PasswordChar Property

See Also	Example

Applies To

Text box.

Description

Determines whether the characters typed by a user or placeholder characters are displayed in a text box; determines the character used as a placeholder.

Usage

[form.]textbox.PasswordChar[ = stringexpression ]

Remarks

Use this property to create a password field in a dialog box.  Although you can use any character, most applications for Windows use the asterisk (*) (Chr$(42)).

This property does not affect the Text property; it contains exactly what the user types or what was set from code.  Set PasswordChar to an empty string ("") or to Chr$(0) to display the actual text.  The default is an empty string.

You can assign any string to this property, but only the first character is significant; all others are ignored.

Data Type

String


See Also

Help:

Text Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


PasswordChar Property Example

The example illustrates how the PasswordChar property affects the way a text box displays text.  To try this example, paste the code into the Declarations section of a form that contains a text box.  Then press F5 and click the form.  Each time you click the form, the text toggles between an asterisk password character and plain text.

Sub Form_Click ()
If Text1.PasswordChar = "" Then
Text1.PasswordChar = "*"
Else
Text1.PasswordChar = ""
End If
End Sub


Selected Property

See Also	Example

Applies To

File list box, list box.

Description

Determines the selection status of an item in a file list box or list box.  This property is an array of Boolean values with the same number of items as the List property.  Not available at design time.

Usage

[form.]{filelistbox|listbox}.Selected(index)[ = {True|False}]

Setting

The Selected property settings are:

Setting	Description

True	The item is selected.

False	(Default) The item is not selected.

Remarks

This property is particularly useful where users can make multiple selections.  You can quickly check which items in a list are selected.  You can also use this property to select or deselect items in a list from code.

If only one item is selected, you can use the ListIndex property to get the index of the selected item.  However, in a multiple selection, the ListIndex property returns the index of the item contained within the focus rectangle, whether or not the item is actually selected.

Data Type

Integer (Boolean)


See Also

Help:

AddItem Method

Clear Method

List Property

ListCount Property

ListIndex Property

MultiSelect Property

NewIndex Property

RemoveItem Method

TopIndex Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Shape Property

See Also	Example

Applies To

Shape.

Description

Determines the appearance of a shape control.

Usage

[form.]shape.Shape[ = numericexpression ]

Setting

The Shape property settings are:

Setting	Description

0	(Default) Rectangle

1	Square

2	Oval

3	Circle

4	Rounded Rectangle

5	Rounded Square

Data Type

Integer (Boolean)


See Also

Help:

BorderStyle Property

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


Shape Property Example

The example illustrates the six possible shapes of the shape control.  To try this example, paste the code into the Declarations section of a form that contains an option button and a shape control.  On the option button, set Index to 0 to create a control array of one element.  Then press F5.  Click each option button to see each shape.

Sub Form_Load ()
Dim I	' Declare variable.
Option1(0).Caption = "Shape #0"
For I = 1 To 5 	' Create 5 instances of Option1.
Load Option1(I)
' Set the location of the new option button.
Option1(I).Top = Option1(I - 1).Top + Option1(0).Height + 40
' Set the option button caption,
Option1(I).Caption = "Shape #" & I
' Display the new option button.
Option1(I).Visible = True
Next I
End Sub

Sub Option1_Click (Index As Integer)
Shape1.Shape = Index
End Sub


Shortcut Property

See Also

Applies To

Menu.

Description

Specifies a shortcut key for a menu control.  Not available at run time.

Remarks

Use this property to provide keyboard shortcuts for menu commands.  You can set this property in the Menu Design window or in the Properties window.  For a list of allowable shortcut keys, see the Shortcut list in the Menu Design window.

Note	In addition to shortcut keys, you can also assign access keys to commands, menus, and controls by using ampersands (&) in the Caption property.

Data Type

String


See Also

Help:

Caption Property

Programmer's Guide:

Chapter 4, "Menus and Dialogs"


Title Property

See Also

Applies To

App object.

Description

Determines the title of the application that appears in the Microsoft Windows Task Manager.  Can be changed at run time, but changes are not saved with the application.  Maximum length: 40 characters.

Usage

App.Title[ = stringexpression ]

Remarks

This property is available at design time in the dialog for the Make .EXE command on the File menu.

Data Type

String


See Also

Help:

Caption Property

Programmer's Guide:

Chapter 5, "Managing Projects"


TopIndex Property

See Also	Example

Applies To

File list box, list box.

Description

Determines which item in a file list box or list box appears in the topmost position.  The default is 0, or the first item in the list.  Not available at design time.

Usage

[form.]{filelistbox|listbox}.TopIndex[ = numericexpression ]

Remarks

Use this property to scroll through a file list box or list box without selecting an item.

If the Columns property is set to 0, the item appears at the topmost position if there are enough items below it to fill the visible portion of the list.

If Columns is greater than 0, the item's column moves to the leftmost position without changing its position within the column.

Data Type

Integer


See Also

Help:

AddItem Method

Clear Method

List Property

ListCount Property

MultiSelect Property

NewIndex Property

RemoveItem Method

Selected Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


TopIndex Property Example

The example fills a list box with names of screen fonts and then scrolls through the list box when you click the form.  To try this example, paste the code into the Declarations section of a form that contains a list box.  Then press F5 and click the form.

Sub Form_Load ()
Dim I	' Declare variable.
For I = 0 To Screen.FontCount -1	' Fill list box with
List1.AddItem Screen.Fonts(I)	' screen font names.
Next I
End Sub

Sub Form_Click ()
Dim X	' Declare variable.
X = List1.TopIndex	' Get current index.
List1.TopIndex = List1.TopIndex + 5	' Reset topmost item.
If List1.TopIndex = X Then List1.TopIndex = 0
End Sub


WindowList Property

See Also	Example

Applies To

Menu.

Description

Specifies whether a menu maintains a list of the current MDI child windows in an MDI form.  Read-only at run time.

Usage

menuname.WindowList

Setting

The WindowList property settings are:

Setting	Description

True	The menu maintains a list of open windows and displays a check mark next to the currently active window.  Users can click a window name to activate that window.

False	(Default) The menu does not maintain a list of open windows.

Remarks

Many Multiple-Document Interface (MDI) applications, such as Microsoft Excel and Microsoft Word for Windows, have a Window menu containing a list of open MDI child windows.  This property enables you to add this functionality to your application.

Only one menu control on a form can have a WindowList.

When you set WindowList to True on a menu control, the WindowList menu structure is appended to the menu items indented below it.

Data Type

Integer (Boolean)


See Also

Help:

Caption Property

Creating a Menu Bar

Menu Design Window

Programmer's Guide:

Chapter 4, "Menus and Dialogs"

Chapter 14, "Multiple-Document Interface (MDI) Applications"


WindowList Property Example

The example creates some menu commands, illustrates the WindowList menu functionality, and shows how to enable your users to add new forms to an MDI application.  To try this example, create an MDI form with the New MDI Form command on the File menu.  On Form1, set the MDIChild property to True and create a menu named "File."  On your Window menu, click the WindowList check box.  On your File menu, create a "New" command, set Name to "FileMenu," and set Index to 0 (to create a control array).  Copy the code into the Declarations section and press F5 to run the program.

Sub Form_Load ()
FileMenu(0).Caption = "&New"	' Set access key in caption.
Load FileMenu(1)	' Create new menu item.
FileMenu(1).Caption = "-"	' Set separator.
Load FileMenu(2)	' Create new menu item.
FileMenu(2).Caption = "E&xit"	' Set caption and access key.
End Sub

Sub FileMenu_Click (Index As Integer)
Select Case Index
Case 0	' New.
Dim NewForm As New Form1	' Create a duplicate of Form1.
' Load NewForm and set a unique caption.
NewForm.Caption = "Untitled" + Forms.Count
Case 2	' Exit.
End	' End the program.
End Select
End Sub


WordWrap Property

See Also	Example

Applies To

Label.

Description

Determines whether a label with its AutoSize property set to True expands vertically or horizontally to fit the text specified in its Caption property.

Usage

[form.]label.WordWrap[ = {True|False} ]

Setting

The WordWrap property settings are:

Setting	Description

True	The text wraps; the label expands or contracts vertically to fit the text and the size of the font.  The horizontal size does not change.

False	(Default) The text does not wrap; the label expands or contracts horizontally to fit the length of the text and vertically to fit the size of the font and the number of lines.

Remarks

Use this property to determine how a label displays its contents.  For example, a graph that changes dynamically might have a label containing text that also changes.  To maintain a constant horizontal size for the label and allow for increasing or decreasing text, you would set the WordWrap and AutoSize properties to True.

If you want a label to expand only horizontally, set WordWrap to False.  If you do not want the label to change size, set AutoSize to False.

Note	If AutoSize is False, the text always wraps, regardless of the size of the label or the setting of the WordWrap property.  This may obscure some text, since the label does not expand in any direction.

Data Type

Integer (Boolean)


See Also

Help:

AutoSize Property

Caption Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


WordWrap Property Example

The example puts text into two labels and uses the WordWrap property to illustrate their different behavior.  To try this example, paste the code into the Declarations section of a form that contains two labels.  Then press F5 and click the form to toggle the WordWrap property.

Sub Form_Load ()
Dim Author1, Author2, Quote1, Quote2	' Declare variables.
Label1.AutoSize = True	' Set AutoSize.
Label2.AutoSize = True
Label1.WordWrap = True	' Set WordWrap.
Quote1 = "I couldn't wait for success, so I went on without it."
Author1 = "  - Jonathan Winters"
Quote2 = "Logic is a system whereby one may go wrong with confidence."
Author2 = "  - Charles Kettering"
Label1.Caption = Quote1 & Chr(10) & Author1
Label2.Caption = Quote2 & Chr(10) & Author2
End Sub

Sub Form_Click ()
Label1.Width = 1440	' Set width to 1 inch in twips.
Label2.Width = 1440
Label1.WordWrap = Not Label1.WordWrap	' Toggle WordWrap property.
Label2.WordWrap = Not Label2.WordWrap
End Sub


X1, Y1, X2, Y2 Properties

See Also	Example

Apply To

Line.

Description

Determine the coordinates of the starting point (X1, Y1) and ending point (X2, Y2) of a line control.  The horizontal coordinates are X1 and X2; the vertical coordinates are Y1 and Y2.

Usage

[form.]line.X1[ = numericexpression ]

[form.]line.Y1[ = numericexpression ]

[form.]line.X2[ = numericexpression ]

[form.]line.Y2[ = numericexpression ]

Remarks

Use these properties to dynamically extend a line from one point to another at run time.  For example, you can show the relationships of items in one list to items in another list, or connect points on a map.

Data Type

Single


See Also

Help:

Left, Top Properties

Line Method

Programmer's Guide:

Chapter 15, "Creating Graphics for Applications"


X1, Y1, X2, Y2 Properties Example

The example is an animated line that walks down the form when you click the form.  To try this example, paste the code into the Declarations section of a form that contains a timer and a line control.  Then press F5 and click the form.

Sub Form_Load ()
Timer1.Interval = 100	' Set Timer interval.
' Position the line near the upper left corner.
Line1.X1 = 100
Line1.Y1 = 100
Line1.X2 = 500
Line1.Y2 = 300
End Sub

Sub Form_Click ()
Timer1.Enabled = True	' Start the timer.
End Sub

Sub Timer1_Timer ()
Static Odd	' Declare variable.
If Odd Then
Line1.X2 = Line1.X2 + 250
Line1.Y2 = Line1.Y2 + 600
Else
Line1.X1 = Line1.X1 + 250
Line1.Y1 = Line1.Y1 + 600
End If
Odd = Not Odd	' Toggle the value.
' If the line is off the form, start over.
If Line1.Y1 > ScaleHeight Then
Timer1.Enabled = False	' Wait for new click.
Line1.X1 = 100
Line1.Y1 = 100
Line1.X2 = 500
Line1.Y2 = 300
Odd = False
End If
End Sub


Code Window

See Also

Use the Code window to write, display and edit code.  You can open as many Code windows as you want, so you can easily view the code in different forms and modules and copy and paste between them.

To open a Code window from the Project window, select a form or module name and choose the View Code button.  Choose the View Form button to see the form.

To open a Code window from a Form window, double-click a control or the form itself, or choose Code (F7) from the View menu.

The Code window includes:

The Object box.  For forms, the Object box lists the current form and all the controls on the current form.

The Procedure box.  If you are editing form code, the Procedure box lists all the events recognized by Visual Basic for the form or control displayed in the Object box.  When you select an event, either the event procedure associated with that event name, or a code template for the event, is displayed in the bottom part of the Code window.

If (general) is displayed in the Object box, the Procedure box lists all of the general procedures that have been created for the form.  If you are editing module code, the Procedure box lists all of the general procedures in the module.  In either case, the procedure you select in the Procedure box is displayed in the bottom part of the Code window.

The Split bar.  The Split bar is located across the window, below the title bar at the top of the vertical scroll bar.  Dragging this bar down splits the Code window into two horizontal panes, each of which scrolls separately.  You can then view different parts of your code at the same time.  The information that appears in the Object box and Procedure box applies to the code in the pane that has the focus.  Dragging the bar to the top of the window closes a pane.

Note	If you need help on syntax for functions, statements, properties, events, or methods while working in the Code window, type the keyword or the property, event, or method name, and press F1.  You can also select an event in the Procedure box and press F1 for information about the selected event.


See Also

Help:

Attaching an Event Procedure to a Form or Control

Entering Declarations in Code

Guidelines for Entering and Editing Code

Learning Visual Basic:

How Visual Basic Works

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"


Color Palette

See Also

Use the Color palette to change the colors of a form or control and set up a custom color scheme.

To open the Color palette, choose Color Palette from the Window menu.

To close the Color palette, double-click the Color palette's Control menu.

The Color palette consists of:

A box that displays the currently selected foreground and background colors for the form or control.

A box that displays the currently selected foreground and background colors for any text in the form or control.

Note	If Microsoft Windows doesn't display the text and background colors that you've selected, it may be because one of the colors you've selected is dithered (a color comprised of up to three different colored pixels).  When displaying text in Microsoft Windows, the text and the area immediately behind it must be solid colors.  If you choose a dithered color for either the text or the background color, the nearest solid color will be used.

A set of colors.  To select a color, click the color box you want.

To change the foreground color, click the inner box on the default color box, then click the color you want.

To change the background color, click the outer box on the default color box, then click the color you want.

Click this button to use the colors specified in the Control Panel.

Click this button to display or set custom colors.

A set of custom colors.  To select a color, click the color box you want.

Click this button to open the Define Color dialog box and define custom colors.

Note	You can also set the colors for forms and controls with the ForeColor or BackColor property.


See Also

Help:

Creating Custom Colors

Setting Colors

Learning Visual Basic:

Using Color and Graphics

Programmer's Guide

Chapter 2, "Your First Visual Basic Application"


Form Window

See Also

Use a Form window to create the windows and dialog boxes in your application.  You draw and view controls in a Form window.

To open a new Form window, choose New Form from the File menu or use the toolbar shortcut:

To open an existing form from the Project window, select the form name and click the View Form button.  Click the View Code button to see the code.

To add a form from another project to the current project, choose the Add File command from the File menu.

While you are designing a form:

The Form window has a Control-menu box, Minimize and Maximize buttons, and a title bar.  You can move and resize a Form window.  The form you design will have the same features at run time and in an executable file unless you specify otherwise in the form's properties.

Use the tools in the Toolbox to draw, size, and position controls.


See Also

Help

Attaching an Event Procedure to a Form or Control

Changing Grid Spacing

Setting Form and Control Properties

Learning Visual Basic:

How Visual Basic Works

Creating an Application

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Debug Window

See Also

Use the Debug window to debug your code.  This window is automatically opened at run time.  In break mode, you can use the Debug window to execute individual lines of code and to test your code.  At run time, although you can't enter statements into the Debug window, you can use it to print internal values without printing them to the actual forms.  You can also use the Debug window to monitor the value of expressions you have selected as watch expressions.

To open the Debug window, choose Debug from the Window menu.

To close the Debug window, double-click the window's Control menu.

The Debug window consists of:

The Watch pane.  Located directly beneath the Debug window title bar, this pane is visible only if you have selected a watch expression to be monitored during code execution.  The displayed information includes the context of the watch expression, the expression itself and its value at the time of the transition to break mode.  If the context of the expression is not in scope when going to break mode, the current value is not displayed.

The Immediate pane.  Located below the title bar or below the Watch pane if it is displayed, the Immediate pane is where you enter code to execute it immediately.  While working in the Immediate pane:

You can execute only one line of code at a time.

You can type or paste a line of code and press Enter to run it.

You cannot save code, but you can copy and paste it into the Code window.

In break mode, a statement in the Debug window is executed in the context displayed in the Debug window title bar.  For example, if you type Print variablename your output is the value of a local variable.  This is the same as if the Print method had actually occurred in the procedure you were executing when the program halted.


See Also

Help:

Using the Debug Window

Debug Object

Learning Visual Basic:

Debugging Your Application

Programmer's Guide:

Chapter 9, "Debugging"


Menu Design Window

See Also

Use the Menu Design window to create custom menus for your application and to define their properties.

To open the Menu Design window, select a form and then choose Menu Design from the Window menu.

The Menu Design window consists of:

A text box in which you enter the menu or command name that will appear on your menu bar or in your menu.

To create a separator bar in your menu, type a single hyphen (-) here.

To give the user keyboard access to the menu item, insert an ampersand (&) before a letter.  At run time, this letter is underlined, and the user can access the menu or command by pressing Alt and the letter.  If you need an ampersand in the menu, put two consecutive ampersands in the caption.

A text box in which you enter a control name for the menu item.  A control name is an identifier used only to access the menu item in code; it does not appear in a menu.

A text box in which you assign a numeric value that will determine the control's position within a control array.  This position is not related to the screen position.

A drop-down list box from which you can select a shortcut key.

A check box you select if you want the menu control to contain a list of open MDI child forms in an MDI application.

A text box where you assign the unique numeric value for the context ID.  This value is used to find the appropriate Help topic in the Help file identified by the HelpFile property.

A check box you select if you want a check mark to appear initially at the left of a menu item.  This is generally used to indicate whether a toggle option is turned on or off.

A check box you select if you want the menu item to respond to events or to be unavailable and appear dimmed.

A check box where you indicate whether you want the menu item to appear on the menu.

A set of outlining keys that enable you to move menu items to a higher or lower level:

  Use these keys to change the level of a menu from a higher level to a lower level.  You can create up to four levels of submenus.

  Use these keys to change the position of a menu item within the same menu level (up or down in the menu list).

A list box that displays a hierarchical list of menu items.  Submenu items are indented to indicate their hierarchical position or level.

The Menu Design window also has the following buttons:

Button	Description

Next	Moves selection to the next line.

Insert	Inserts a line in the list box before the currently selected line.

Delete	Deletes the currently selected line.

OK	Closes the Menu Design window and applies all menu changes to the last form you selected.  The menu is available at design time but no events are generated.

Cancel	Closes the Menu Design window and cancels all changes.


See Also

Help:

Creating a Menu Bar

Menu Design Window Keys

Learning Visual Basic:

Adding Menus

Programmer's Guide:

Chapter 4, "Menus and Dialogs"


Project Window

See Also

The Project window displays a list of all the forms, modules, and custom controls in an application.

To open a new project, choose New Project from the File menu.

To open an existing project, choose Open Project from the File menu or use the toolbar shortcut:

While working in the Project window:

You can open the Form window for an existing form by selecting the form name and clicking the View Form button.

You can open the Code window for an existing form or module by selecting a form or module name and clicking the View Code button.

You can open as many forms and modules within a project as you want, but you can open only one Project window at a time.


See Also

Learning Visual Basic:

How Visual Basic Works

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"


Toolbox

See Also

The Toolbox displays all the standard Visual Basic controls plus any custom controls you have added to your project.  You choose a tool by clicking it.

To open the Toolbox, choose Toolbox from the Window menu.

To close the Toolbox, double-click the Toolbox's Control menu.

There are 21 basic tools in the Toolbox:

 Pointer.  This is the only item in the Toolbox that doesn't draw a control.  Use it to resize or move a control after it's been drawn on a form.

 Picture Box  Use to display graphical images (either decorative or active), as a container that receives output from graphics methods, or as a container for other controls.

 Label  Use for text that you don't want the user to change, such as a caption under a graphic.

 Text Box  Use to hold text that the user can either enter or change.

 Frame  Use to create a graphical or functional grouping for controls.  To group controls, draw the frame first, then draw controls inside the frame.

 Command Button  Use to create a button the user can choose to carry out a command.

 Check Box  Use to create a box that the user can easily choose to indicate if something is true or false, or to display multiple choices when the user can choose more than one.

 Option Button  Use in a group of option buttons to display multiple choices from which the user can choose only one.

 Combo Box  Use to draw a combination list box and text box.  The user can either choose an item from the list or enter a value in the text box.

 List Box  Use to display a list of items from which the user can choose one.  The list can be scrolled if it has more items than can be displayed at one time.

 Horizontal Scroll Bar  Use to provide a graphical tool for quickly navigating through a long list of items or a large amount of information, for indicating the current position on a scale, or as an input device or indicator of speed or quantity.

 Vertical Scroll Bar  Use to provide a graphical tool for quickly navigating through a long list of items or a large amount of information, for indicating the current position on a scale, or as an input device or indicator of speed or quantity.

 Timer  Use to trap timer events at set intervals.  This control is invisible at run time.

 Drive List Box  Use to display the valid drives in a selected drive.

 Directory List Box  Use to display a hierarchical list of directories in the user's system.

 File List Box  Use to display a list of files that the user can open, save, or otherwise manipulate.

 Shape  Use to draw a variety of shapes on your form at design time.  You can choose a rectangle, rounded rectrangle, square, rounded square, oval, or circle.

 Line  Use to draw a variety of line styles on your form at design time.

 Image  Use to display a graphical image from a bitmap, icon, or metafile on your form.  Images displayed in an image control can only be decorative and use fewer resources than a picture box.

 Grid  Use to create a spreadsheet-like grid consisting of columns and rows of data.

 OLE Control  Use to provide object linking and embedding (OLE) from an OLE server into your Visual Basic application.

 Data Control  Use to provide access to data in databases through bound controls on your form.

 Common Dialog  Use to create common types of dialog boxes for opening or saving files, setting fonts or colors.

When you select the pointer, you will be able only to resize or move a control.

When you select any other tool, you can use it only to draw new controls.

Once you draw a control, the pointer is automatically reselected.


See Also

Help:

Attaching an Event Procedure to a Form or Control

Controls

Drawing a Control

Setting Form and Control Properties

Learning Visual Basic:

How Visual Basic Works

Programmer's Guide:

Chapter 3, "Creating and Using Controls"


Properties Window

See Also

The Properties window contains the list of properties for a selected form or control.  These properties can be changed at design time and the Properties window shows each property's current setting.  When you select multiple controls, the Properties window contains a list of the properties common to all the selected controls.

To open the Properties window, choose Properties from the Window menu or press F4.

To close the Properties window, double-click the Property window's Control menu box.

To return to the previous window, press Alt+F6.

The Properties window consists of:

The Object box.  Located beneath the title bar, the Object box identifies the currently selected form or the currently selected control on the form.  Click the arrow at the right side of the Object box to see a list that includes the current form and all the controls on the form.  From the list, choose the current form or a control on the form whose properties you want to change.

The Settings box.  Located beneath the Object box, the Settings box is where you make a change to the selected property.  If the arrow at the right side of the Settings box is dimmed, enter the property value directly by typing it in the Settings box.  If the arrow is not dimmed, click it and choose from the list of predefined settings for the property you have selected.  Click the Enter button to accept the change, or click the Cancel button to cancel the change.

The Property list.  Located at the bottom of the Properties window, this two-column list shows all properties that can be changed at design time and their current settings.  For properties that have predefined settings, double-clicking on the property name in the Property list cycles through the available choices.  For properties with only two choices, double-clicking toggles between the two choices.


See Also

Help:

Setting Colors

Setting Form and Control Properties

Learning Visual Basic:

Working with Forms and Controls

Programmer's Guide:

Chapter 2, "Your First Visual Basic Application"


Menu Bar and Toolbar

Click on the Menu or Toolbar word or picture for more information.

The Visual Basic menu bar includes a title bar, a Minimize button, a Maximize button, a Control menu, and the names of the menus you can use in the active window.  Although the menu bar is initially displayed at the top of the screen, it can be moved to another location and resized.

To open a menu and display its commands, click the menu name or press the access key.

To choose a command once you've opened a menu, click the command name or press the access key.  If there is a shortcut key for a command, it is indicated on the menu next to the command name.

Commands followed by an ellipsis (...) display a dialog box where you provide more information before the command is executed.

Closing the menu bar also closes Visual Basic.

The toolbar contains buttons that are shortcuts to some commonly used menu items and two indicators at the right that display the position and size of a selected form or control.


See Also

Help:

Commands


Setup Toolkit Contents

See Also

The Visual Basic Setup Toolkit provides tools to create setup programs for your Visual Basic applications.

Overview

How to Use the Setup Toolkit

Files You Are Allowed to Distribute

Files You Need to Distribute

Required DLLs for Distributing Visual Basic Applications

Layout of the Distribution Disks

Modifying SETUP.LST

Compressing the Setup Files

Writing Your Setup Program

Where to Install Files on the User's Machine

Creating Your Distribution Disks

Testing Your Distribution Disks

SetupWizard

If you do not need a customized setup program, use the Visual Basic SetupWizard to create your distributions disks.  The SetupWizard:

Creates a setup program (SETUP1.EXE)

Builds your application's executable file.

Compresses all files and assigns them to a disk layout.

Notifies you of the number of blank formatted disks needed.

ODBC Applications

Creating a Setup Disk for ODBC Applications (Professional Edition Only)


See Also

Overview

Compressing the Setup Files

Creating Your Distribution Disks

Distributing OLE Applications

Files You Are Allowed to Distribute

Files You Need to Distribute

Required DLLs for Distributing Visual Basic Applications

How to Use the Setup Kit

Layout of the Distribution Disks

Modifying SETUP.LST

Visual Basic SetupWizard

Testing Your Distribution Disks

Where to Install Files on the User's Machine

Writing Your Setup Program


Setup Toolkit Overview

See Also

You can freely distribute any application that you create with Visual Basic.  If you plan to distribute your application to a number of users or plan to sell it commercially, then you'll want to write a setup program that installs your application on the customer's machine.

The Visual Basic Setup Toolkit provides the tools you need to write setup programs using Visual Basic.  All the tools you need to use the Setup Toolkit are located in the \SETUPKIT subdirectory of the main Visual Basic directory.

The Setup Toolkit allows you to:

Create a customized setup program.

Compress and expand your application's files to fit the available disk space.

Preinstall files that you specify.

Use the version-stamping resources (VER.DLL) in Microsoft Windows to determine whether a file should be copied to the customer's machine.

Install files in the appropriate Microsoft Windows directories (\WINDOWS, \WINDOWS\SYSTEM) regardless of the actual directory names on your customer's system.

Create Microsoft Windows Program Manager groups and icons for your application.

The Setup Toolkit files include utilities, dynamic-link libraries (DLLs), and a sample setup program written in Visual Basic.  The following table describes each file:

File name	Description

SETUP.EXE	The preinstallation program (sometimes referred to as a bootstrap program) that your customer runs to install your application.  SETUP.EXE installs VER.DLL and all the files listed in SETUP.LST.  Your custom setup program (SETUP1.EXE or whatever file name you specify) is copied into the customer's \WINDOWS directory and then invoked to install your application.

SETUP1.EXE	A Visual Basic application that you customize.  This application's source files are located in the \SETUPKIT\SETUP1 subdirectory of the main Visual Basic directory.  Use these source files as a template for creating your own setup program.

SETUP.LST	A text file that lists all the files SETUP.EXE preinstalls on your customer's machine.  The first line of this file must be the name of your setup program (SETUP1.EXE or whatever file name you specify).

SETUP1.BAS	A collection of Visual Basic functions used in SETUP1.MAK to perform the tasks required by the setup program.

VER.DLL	A DLL that contains functions for copying and decompressing files.

VER.DLL can also detect the version of a file that has a Microsoft Windows version stamp.  You cannot compile version information in your Visual Basic .EXE file; however, some files do contain this version stamp.  If a file does not have a Microsoft Windows version stamp, VER.DLL uses the file date and time to determine the file version.

SETUPKIT.DLL	A DLL that contains various functions used in SETUP1.BAS.


How to Use the Setup Toolkit

See Also

You use the Setup Toolkit to create a setup program for your application using the following steps.  When you have finished this procedure, you'll have a set of distribution disks that a customer can use to install your application.

To create distribution disks for your application

1	Determine the files you need to distribute.

2	Modify SETUP.LST to include all the files on your list.

3	Compress the appropriate files.

4	Determine the layout of your distribution disks (which files on which disks).

5	Determine where to install the files on your customer's machine.

6	Write your setup program.

7	Create your distribution disks.

8	Test your distribution disks.


Files You Need to Distribute

See Also

Before creating a setup program, you must determine which files to include on the distribution disks.  A setup program requires the following files:

File name	Description

SETUP.EXE	The preinstallation, or bootstrap, program.

SETUP1.EXE	Your customized setup program.

SETUP.LST	A text file that lists all the files SETUP.EXE preinstalls on your customer's machine.

VBRUN300.DLL	The Visual Basic run-time file required by all Visual Basic applications.

VER.DLL	A DLL that contains functions to locate the customer's \WINDOWS and \WINDOWS\SYSTEM directories and to use Microsoft Windows version-stamping information.

The user will need additional files to run your application [image] for example, data files, custom controls (.VBX), or DLLs.  Possible additional files include the following:

File name	Description

YOURAPP.EXE	Your application's .EXE file.

YOURAPP.DAT (optional)

YOURAPP.TXT (optional)

YOURAPP.INI (optional)	Data files (.DAT), text files (.TXT), or initialization files (.INI).

YOURCC.VBX (optional)	Custom controls that your application requires.

YOURDLL.DLL (optional)	DLLs that your application requires.

Note	Visual Basic does not compile custom controls and DLLs as part of your application's .EXE file.  If your application uses any custom controls or DLLs, you must include the appropriate .VBX and .DLL files on the distribution disks.

Depending on the operations your application performs and the custom controls it uses, you may also need to distribute other DLLs.


Required DLLs for Distributing Visual Basic Applications

See Also

Depending on the operations your application performs and the custom controls it uses, you may also need to distribute the following DLLs:

DLL name	Required by	Description
COMPOBJ.DLL	OLE control OLE Automation	Required by OLE 2.0.
MSOLE2.VBX  MSOLEVBX.DLL	OLE control	Required by the OLE custom control.   Note that applications using the OLE control, or OLE Automation require Microsoft Windows version 3.1 or later.
OLE2.DLL	OLE control OLE Automation	Required by OLE 2.0.
OLE2.REG	OLE control OLE Automation	Used to register OLE 2.0 and OLE Automation in the users REG.DAT file.
OLE2CONV.DLL	OLE control OLE Automation	Required by OLE 2.0.
OLE2DISP.DLL	OLE control OLE Automation	Required when performing OLE Automation tasks or accessing the OLE controls Object property.
OLE2NLS.DLL	OLE control OLE Automation	Facilitates string comparisons based on the users national language.
OLE2PROX.DLL	OLE control OLE Automation	Required by OLE 2.0.
STORAGE.DLL	OLE control OLE Automation	Required by OLE 2.0.
VBOA300.DLL	OLE control OLE Automation	Required by Visual Basic and OLE 2.0.
GRID.VBX	Grid control	The grid custom control.
DDEML.DLL	DDE	Required if your application uses dynamic data exchange (DDE).
CMDIALOG.VBX	Common dialog control	The common dialog custom control.
COMMDLG.DLL	Common dialog control	Required by the common dialog custom control.
MSAFINX.DLL	Financial functions	Required if your application calls any of the Visual Basic financial functions.  For a list of the financial functions, search Help for Financial Functions.
VBDB300.DLL MSAES110.DLL MSAJT110.DLL	Data access	Required if your application uses the data control or  the data access features of the Professional Edition.
BTRV110.DLL	Data access	Required if your application accesses data in Btrieve format.
PDX110.DLL	Data access	Required if your application accesses data in Paradox format.
XBS110.DLL	Data access	Required if your application accesses data in xBase format.
COMMDLG.DLL CTL3D.DLL DBNMP3.DLL OBDC.DLL OBDCADMIN.EXE ODBCINST.DLL ODBCINST.HLP	ODBC	(Professional Edition only) Required if your application uses Open Database Connectivity (ODBC).
SQLSRVR.DLL DBNMP3.DLL INSTCAT.SQL INSTCAT.48 DRVSSRVR.HLP	ODBC	(Professional Edition only) Required if your application uses ODBC to access SQL Server data.
SQORA.DLL ORASETUP.DLL ORA6WIN.DLL DRVORACL.HLP ORACLE.TXT	ODBC	(Professional Edition only) Required if your application uses ODBC to access Oracle data.
CRYSTAL.VBX CRPE.DLL CRXLATE.DLL COMMDLG.DLL	Crystal Reports	Required by the Crystal Reports for Visual Basic custom control.
Caution   If you are developing an application that requires Btrieve, you must have a licensing agreement with Novell to release the Btrieve for Windows driver (WBTRCALL.DLL) with your application. Applications that use Btrieve require both the Btrieve for Windows driver and the Btrieve ISAM dynamic-link library (BTRV110.DLL).


Modifying SETUP.LST

See Also

SETUP.LST is a text file that lists all the files SETUP.EXE preinstalls on your customer's machine.  After SETUP.EXE installs the files specified in SETUP.LST, it invokes your setup program.

The name of your setup program must be the first line in SETUP.LST.  You can give your setup program any name except SETUP.EXE, which is the name of the preinstallation program.  For example, you can name your setup program SETUP1.EXE, SETLOAN.EXE, or MYSETUP.EXE.

If you use SETUP1.MAK as a template for a setup program that doesn't call additional DLLs or use any custom controls, then SETUP.LST should contain only the name of your setup program, VBRUN300.DLL, and SETUPKIT.DLL.  Each file name in SETUP.LST must appear on a separate line.

In some cases, you may want to access DLLs or use custom controls in your setup program that are not already used by SETUP1.MAK.  If so, you must include the names of these files in SETUP.LST.


Compressing Your Setup Files

See Also

If all the files for your application will not fit on a single floppy disk, you can compress the files using the COMPRESS.EXE utility in the \SETUPKIT\KITFILES subdirectory.  Compressing your files might reduce the number of disks required to distribute your application.

COMPRESS.EXE is an MS-DOS-based utility, not a Microsoft Windows-based application.

To compress a file

At the MS-DOS prompt, type:

compress -r filename

The -r switch replaces the last character of the compressed file's file name with an underscore.  For example, to compress the file LOAN.EXE, type:

compress -r loan.exe

The result is a compressed file named LOAN.EX_

Note	The -r switch is required when compressing files that are installed using SETUP.EXE or SETUP1.EXE.

You can compress any file on the distribution disks except SETUP.EXE, SETUP.LST, and VER.DLL.  You can compress as many files as you want.  VER.DLL correctly copies both compressed and noncompressed files to the user's disk if you use version 2.0 of COMPRESS.EXE, which comes with the Setup Toolkit.

Compressed files automatically return to their original name when expanded on the user's disk.For information on COMPRESS.EXE, see the file COMPRESS.TXT in the \SETUPKIT\KITFILES subdirectory of the main Visual Basic directory.


Layout of the Distribution Disks

See Also

You must know the name of each file in your application and which distribution disk it is on before you write your setup program.

The first distribution disk must contain the following files:

SETUP.EXE

SETUP1.EXE (or whatever file name you specify)

SETUP.LST

VER.DLL

SETUPKIT.DLL

VBRUN300.DLL

Any other files listed in SETUP.LST (the files that will be preinstalled)

By calculating the size of the remaining files, you can determine which files each disk should contain.

Note	The Setup Toolkit does not allow you to split a file between disks.


Where to Install Files on the User's Machine

See Also

Each Visual Basic application requires at least two files [image] the .EXE file and the run-time file VBRUN300.DLL.  Your application probably requires additional files.  Before writing your setup program, you must determine where on the user's disk you want to install each file.  The files that your application requires can be divided into several classes:

Program files

Initialization files

Operating-system components

Shared application resources

Program Files

These files are essential for your application and are useful only in the context of your application.  For example, your application's .EXE file and data files are considered program files.  Program files should be installed in the application directory.  The user is prompted for this directory during setup (sample code for this is included in SETUP1.MAK).

Initialization Files

These files control options for the user of an application.  Initialization (.INI) files should be installed in the user's Microsoft Windows directory, which is the directory in which the WIN.INI file is located (usually in the \WINDOWS subdirectory).  You determine the name of this directory on the user's disk by calling the GetWindowsDirectory Windows API function.  The code in SETUP1.MAK shows how to call this function.

Operating-System Components

These files are normally included with Microsoft Windows, but you may want to distribute them with your application to ensure that the user has a particular version of a DLL, such as OLECLIEN.DLL or SHELL.DLL.  You should install such files in the \SYSTEM subdirectory of the user's main Microsoft Windows directory.  You can determine the name of this directory by calling the GetSystemDirectory Windows API function.  The code in SETUP1.MAK shows how to call this function.

Shared Application Resources

Application resources can be shared by more than one application.  For example, several different vendors may ship applications that use the same custom control.  By installing .VBX files in the \WINDOWS\SYSTEM subdirectory, you can ensure that all applications use the most current .VBX file.


Writing Your Setup Program

See Also

You can quickly write your setup program by modifying the source code of the sample setup program, SETUP1.MAK, located in the \SETUPKIT\SETUP1 subdirectory of the main Visual Basic directory.  SETUP1.MAK installs the sample application LOAN.EXE, which is located in the \SAMPLES\GRID subdirectory of the main Visual Basic directory.

LOAN.EXE uses the grid custom control and requires GRID.VBX to be properly installed on the user's system.  This is a typical setup scenario for applications that use custom controls.

To customize SETUP1.MAK so that it installs your application instead of LOAN.EXE, modify only the code in the Declarations section and the Form_Load event procedure of the SETUP1.FRM module.

To customize SETUP1.MAK

1	Modify the appropriate constants in the Declarations section of SETUP1.FRM.

2	In the Form_Load procedure of SETUP1.FRM, modify the arguments to the PromptForNextDisk function call.

3	Call the CopyFile function for each file on the current distribution disk.

4	Repeat steps 2 [image] 3 for each of the distribution disks, creating a new block of PromptForNextDisk and CopyFile calls for each disk.

5	Modify the arguments to the CreateProgManGroup and CreateProgManItem procedure calls.

SETUP1.FRM Constants

Several useful constants are defined in the Declarations section of SETUP1.FRM.  When customizing your setup program, redefine these constants to reflect information about your application.

Constant	Description

APPNAME	The name of your application.  Use this constant to display the name of your application in the captions of forms and in messages in the setup program.

APPDIR	The default directory in which your application is to be installed.

WINSYSNEEDED	The total size, in bytes, of all uncompressed files the setup program will install in the user's \WINDOW and \WINDOWS\SYSTEM subdirectories.  Use this number to determine whether the user has enough space on the disk that contains these subdirectories to install your application.

OTHERNEEDED	The total size, in bytes, of all uncompressed files the setup program will install in the application directory (the directory in which the user installs your application).  Use this number to determine whether the user has enough space to install your application on the disk that contains the application directory.

Example

This example of defining constants is taken from the Declarations section of SETUP1.FRM:

Const APPNAME = "Loan Application"

Const APPDIR = "C:\LOAN"

Const WINSYSNEEDED = 40896

Const OTHERNEEDED = 12555

PromptForNextDisk and CopyFile Functions

Use the PromptForNextDisk function to prompt the user to enter a disk.  If the user enters the correct disk, the function returns True.  Use the CopyFile function to copy a file from the distribution disk to the user's machine.  You must call CopyFile once for each file on the disk.  After copying all the files on a disk, call PromptForNextDisk again to prompt the user to insert the next disk.

Example

This example of the PromptForNextDisk and CopyFile functions is taken from the Form_Load event procedure of SETUP1.FRM:

' -----------

' Copy Files

' -----------

' Disk 1

' -----------

' Test to see if LOAN.EX_ is on the disk; if not, then you know the

' user did not insert the first disk.

If Not PromptForNextDisk(1, SourcePath$ + "LOAN.EX_") Then

GoTo ErrorSetup

End If

' Install LOAN.EXE in the destPath$.

If Not CopyFile(SourcePath$, destPath$, "LOAN.EX_", "LOAN.EXE", 0)

Then

GoTo ErrorSetup

End If

' Install GRID.VBX in the user's \SYSTEM directory.

If Not CopyFile(SourcePath$, winSysDir$, "GRID.VB_", "GRID.VBX", 0)

Then

GoTo ErrorSetup

End If

' -----------

' Disk 2

' -----------

' Test to see if FOO.DA_ is on the disk; if not, then you know the

' user did not insert the second disk.

If Not PromptForNextDisk(2, SourcePath$ + "FOO.DA_") Then

GoTo ErrorSetup

End If

' Install FOO.DAT in the destPath$.

If Not CopyFile(SourcePath$, destPath$, "FOO.DA_", "FOO.DAT", 0)

Then

GoTo ErrorSetup

End If

CreateProgManGroup and CreateProgManItem Functions

These functions create a Microsoft Windows program group and program item for your application.

Example

This example of the CreateProgManGroup and CreateProgManItem functions is taken from the Form_Load event procedure of SETUP1.FRM:

' --------------------------------------

' Create Program Manager group and icon.

' --------------------------------------

CreateProgManGroup Setup1, "Loan Application", "LOAN.GRP"

CreateProgManItem Setup1, destPath$ + "LOAN.EXE", "Loan Application"


Creating Your Distribution Disks

See Also

Before you copy files to the distribution disks, it's a good idea to label the disks.  On the first disk, attach a label that reads:

Disk1: Setup Disk

Insert this disk in drive A

In the Program Manager, choose Run from the File menu

Type a:setup and press Enter

This label provides all the instructions your customer needs to install your application.  You can label the remaining disks similarly.  For example:

Disk2: MyApp

Now you are ready to copy your files to the appropriate distribution disks.

To create distribution disks

1	Rename VER.DLL to VER.DL_.  For example:

rename a:ver.dll a:ver.dl_

You must change the VER.DLL file extension to .DL_ so that Microsoft Windows does not try to use it while the setup disk is in the floppy disk drive.

2	Copy these files onto the first disk:

SETUP.EXE

SETUP.LST

SETUP1.EXE (or whatever you've named your setup program)

SETUPKIT.DLL

VER.DL_

VBRUN300.DLL

If you've compressed any of these files, the last character of the file name will be an underscore (for example, VBRUN300.DL_).

3	Copy the remaining files as specified by your disk layout.


Testing Your Distribution Disks

See Also

You should test your distribution disks after you create them.  Be sure to test your setup program on a machine that does not have Visual Basic or any of the custom controls your application requires.

To test your setup program using the distribution disks

1	Insert the first disk in drive A.

2	From the Microsoft Windows Program Manager, choose Run from the File menu and type:

a:setup

If your application does not install properly, check to make sure the actual layout of the distribution disks matches the code in your setup program.


Files You Are Allowed To Distribute

See Also

You can freely distribute any application that you create with Visual Basic.  In addition to an executable (.EXE) file, your application might require other files such as DLLs, custom controls (.VBX), or bitmaps (.BMP).

Sample application files may be distributed.  Microsoft makes no warranty, express or implied, regarding the merchantability or fitness of these applications, nor does Microsoft assume any obligation or liability for their use.

Standard Edition

You can legally distribute the following files with any Visual Basic application you create:

Any files located in the \ICONS subdirectory of the main Visual Basic directory.

BTRV110.DLL

CMDIALOG.VBX

COMMDLG.DLL

COMPOBJ.DLL

COMPRESS.EXE

DDEML.DLL

EXPAND.EXE

GRID.VBX

MSAES110.DLL

MSAFINX.DLL

MSAJT110.DLL

MSOLE2.VBX

MSOLEVBX.DLL

OLE2.DLL

OLE2.REG

OLE2CONV.DLL

OLE2DISP.DLL

OLE2NLS.DLL

OLE2PROX.DLL

PDX110.DLL

SETUP.EXE (Setup Toolkit)

STORAGE.DLL

VBDB300.DLL

VBOA300.DLL

VBRUN300.DLL

VER.DLL

WINHELP.EXE

XBS110.DLL

Professional Edition

If you have purchased the Professional Edition of Visual Basic, you can also distribute these files with any Visual Basic application you create:

Any files located in the \BITMAPS subdirectory of the main Visual Basic directory.

Any files located in the \METAFILE subdirectory of the main Visual Basic directory.

Any files located in the \ODBC subdirectory of the main Visual Basic directory.

CRPE.DLL

CRXLATE.DLL

CRYSTAL.VBX

CTL3D.DLL

DBNMP3.DLL

DRVORACL.HLP

DRVSSRVR.HLP

GAUGE.VBX

GRAPH.VBX

GSW.EXE

GSWDLL.DLL

INSTCAT.48

INSTCAT.SQL

KEYSTAT.VBX

MCI.VBX

MSAES110.DLL

MSAJT110.DLL

MSCOMM.VBX

MSMAPI.VBX

MSMASKED.VBX

MSOUTLIN.VBX

OBDC.DLL

OBDCADMIN.EXE

ODBCINST.DLL

ODBCINST.HLP

ORA6WIN.DLL

ORACLE.TXT

ORASETUP.DLL

PDBJET.DLL

PDIRJET.DLL

PDSODBC.DLL

PENCTRL.VBX

PICCLIP.VBX

SPIN.VBX

SQLSRVR.DLL

SQORA.DLLANIBUTON.VBX

THREED.VBX

Note	You may also be able to distribute other custom controls and DLLs that you have purchased.  See the licensing agreement supplied by the individual software vendor for details.


Creating a Setup Disk for ODBC Applications (Professional Edition Only)

See Also

If you create an application that uses ODBC and you want to distribute that application, you must create an ODBC Setup Disk.  After you have installed your Visual Basic application on the user's machine (using a setup program you have written), you must install ODBC on the user's machine.

To Create an ODBC Setup Disk:

1.	Copy all the files in \ODBC subdirectory of the main Visual Basic directoryto a floppy disk.

Note  You may choose to not copy the files for ODBC drivers that your application does not use.

2.	After installing your application on the user's disk, run SETUP.EXE on the ODBC setup disk.  Either use the Shell function to run the ODBC SETUP.EXE from your setup program, or label the ODBC setup disk with a title such as "ODBC Setup Diskette.  Please run SETUP.EXE after installing the application.")

Note  To setup ODBC on a user's machine you must use the SETUP provided in the \ODBC directory.  Some of the ODBC files are compressed and you need SETUP to decompress and install them correctly.


Knowledge Base Articles from Microsoft Technical Support
Knowledge Base Articles from Microsoft Product Support

Copying the Current Database Record Into a Record Variable

DDE From Visual Basic to Excel For Windows

Example of Client/Server DDE  Between Visual Basic Applications

How to Create Scrollable Viewports in Visual Basic

How to Determine When a Shelled Process has Terminated

How to Get Windows Master List (Task List) Using Visual Basic

How to Print a Form or Control using StretchDIBits

How to Use Windows BitBlt Function From Visual Basic

How VB  Can Determine If a Specific Windows Program Is Running

Keeping the Current Record the Same After Using Refresh

LSTRCPY API Call to Receive LPSTR Returned From Other APIs

Using a Data Control to Scroll Up and Down in a Recordset


DDE From Visual Basic to Excel For Windows

See Also

This article is reprinted from the Microsoft Knowledge Base.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 2.0 and 3.0.

Summary:

This article describes how to initiate a dynamic data exchange (DDE)

conversation between a Visual Basic destination application and a Microsoft Excel source

application.

This article demonstrates how to:

 - Prepare a Microsoft Excel for Windows document for active DDE.

 - Initiate a manual DDE link (information updated upon request from

   the destination) between Visual Basic (the destination) and Excel

   (the source).

 - Use the LinkRequest method to update information in Visual Basic

   (the destination) based on information contained in Excel (the

   source).

 - Initiate a automatic DDE link (information updated automatically

   from source to destination) between Visual Basic (the destination)

   and Excel (the source).

 - Use the LinkPoke method to send information from Visual Basic (the

   destination) to Excel (the source).

 - Change the LinkMode property between automatic and manual.

More Information:

A destination application sends commands through DDE to the source

application to establish a link. Through DDE, the source provides data

to the destination at the request of the destination or accepts information at the request of the

destination.

The procedure below is as an example of how to establish a DDE

conversation between Visual Basic and Excel for Windows.

First, create the source spreadsheet in Excel:

1. Start Excel, and a document titled "SHEET1" will be created by

   default.

2. From the File menu, choose Save As, and save the document with the

   name SOURCE.XLS

4. Exit Excel. For this example to function properly, Excel must not

   be loaded and running.

Next, create the destination application in Visual Basic:

The destination is the application that performs the link operations. It prompts the source to

send information or informs the source that

information is being sent.

1. Start Visual Basic (VB.EXE), and Form1 will be created by default.

2. Create the following controls with the following properties on

   Form1:

      Default Name	Caption	Name

      ------------	-------	-------

      Text1	(not applicable)	Text1

      Option1	Manual Link	ManualLink

      Option2	Automatic Link	AutomaticLink

      Command1	Poke	Poke

      Command2	Request	Request

3. Add the following code to the general Declaration section of Form1:

      Const AUTOMATIC = 1

      Const MANUAL = 2

      Const NONE = 0

4. Add the following code to the Load event procedure of Form1:

Sub Form_Load ()

    'This procedure will start Excel and load SOURCE.XLS, the

    'spreadsheet that was created earlier.

    z% = Shell("EXCEL SOURCE.XLS", 1)

    z% = DoEvents()	'Process Windows events. This insures

'that Excel will be executed before

'any attempt is made to perform DDE.

    Text1.LinkMode = NONE	'Clears DDE link if it already exists.

    Text1.LinkTopic = "Excel|source.xls"	'Sets up link

'with Excel.

    Text1.LinkItem = "R1C1"	'Set link to first cell on spreadsheet.

    Text1.LinkMode = MANUAL	'Establish a manual DDE link.

    ManualLink.Value = TRUE

End Sub

5. Add the following code to the Click event procedure of the

   Manual Link button:

Sub ManualLink_Click ()

        Request.Visible = TRUE	'Make request button valid.

        Text1.LinkMode = NONE	'Clear DDE Link.

        Text1.LinkMode = MANUAL	'Reestablish new LinkMode.

End Sub

6. Add the following code to the Click event procedure of the

   Automatic Link button:

Sub AutomaticLink_Click ()

        Request.Visible = FALSE	'No need for button with automatic

'link.

        Text1.LinkMode = NONE	'Clear DDE Link.

        Text1.LinkMode = AUTOMATIC	'Reestablish new LinkMode.

End Sub

7. Add the following code to the Click event procedure of the

   Request button:

Sub Request_Click ()

   'With a manual DDE link this button will be visible and when

   'selected it will request an update of information from the source

   'application to the destination application.

    Text1.LinkRequest

End Sub

8. Add the following code to the Click event procedure of the Poke

   button:

Sub Poke_Click ()

    'With any DDE link this button will be visible and when selected

    'it will poke information from the destination application to the

    'source application.

    Text1.LinkPoke

End Sub

You can now run the Visual Basic destination application from the Visual Basic environment (skip

to step 4 below) or you can save the

application and create an .EXE file and run that from Windows (start

from step 1 below):

1. From the Visual Basic File menu, choose Save, and save the Form and

   Project with the name DEST.

2. From the File menu, choose Make EXE File, and name it DEST.EXE.

3. Exit Visual Basic.

4. Run the application (from Windows if an .EXE file or from the Run

   menu if from the Visual Basic environment).

5. Form1 of the destination application will be loaded and Excel will

   automatically be started with the document SOURCE.XLS loaded.

6. Make sure the main title bar in Excel reads "Microsoft Excel," NOT

   "Microsoft Excel - SOURCE.XLS." If the title bar is incorrect, then

   from the Window menu choose Arrange All.

You can now experiment with DDE between Visual Basic and Excel:

1. Try typing some text in R1C1 in the spreadsheet and then select the

   Request button. The text appears in the text box.

   Be sure to press the ENTER key after entering text into an Excel

   cell before clicking the Request button in the Visual Basic

   program, or else a "Timeout while waiting for DDE response" error

   message will be displayed from the TEXT1.LINKREQUEST statement.

   This occurs because while entering text into a cell, Excel is in a

   polling loop for data entry, and no real data is transferred to the

   cell until you press ENTER. Therefore, Visual Basic keeps

   attempting to request the data from the cell, but Excel does not

   pay attention to the request until it exits the polling loop, which

   results in the DDE time-out message.

2. Choose the Automatic Link button and then type some more text in

   R1C1 of the spreadsheet. The text is automatically updated in the

   Visual Basic text box.

3. Type some text in the text box in the Visual Basic application and

   choose the Poke button. The text is sent to R1C1 in the Excel

   spreadsheet.

Note: If you have the Ignore Remote Requests option selected in the

Excel Workspace dialog box, you will not be able to establish DDE from

Visual Basic. Make sure the Ignore Remote Requests option is NOT

selected.


Example of  Client/Server DDE  Between Visual Basic Applications

See Also

This article is reprinted from the Microsoft Knowledge Base.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 2.0 and 3.0.

Summary:

This article outlines the steps necessary to initiate dynamic data

exchange (DDE) between a Microsoft Visual Basic destination application and a Visual Basic source

application.

This article demonstrates how to:

 - Create a Visual Basic application to function as a DDE source.

 - Create a Visual Basic application to function as a DDE destination.

 - Initiate a manual DDE link (information updated upon request from the

   destination) between the destination application and the source

   application.

 - Use LinkRequest to update information in the destination application

   from information in the source application.

 - Initiate a automatic DDE link (information updated automatically from

   source to destination) between the destination application and the

   source application.

 - Use LinkPoke to send information from the destination application to

   the source application.

 - Change the LinkMode property between automatic and manual.

More Information:

A destination application sends commands through DDE to the source

application to establish a link. Through DDE, the source provides data

to the destination at the request of the destination or accepts information at the request of the

destination.

Example

-------

The steps below are an example of how to establish a DDE conversation

between two Visual Basic applications.

First, create the source application in Visual Basic:

1. Start Visual Basic, and Form1 will be created by default.

2. Change the Caption property of Form1 to "Source".

3. Put a Text Box (Text1) on Form1.

4. Save the form and project with the name SOURCE.

5. From the File menu, choose Make EXE File. In the Make EXE File

   dialog box, choose OK to accept SOURCE.EXE as the name of the EXE

   file.

Second, create the destination application in Visual Basic:

1. From the File menu, choose New Project. Form1 will be created by

   default.

2. Change the Caption property of Form1 to "Destination".

3. Create the following controls with the following properties on

   Form1:

     Default Name	Caption	Name

     ------------	-------	-------

     Text1	(Not applicable)	Text1

     Option1	Manual Link	ManualLink

     Option2	Automatic Link	AutomaticLink

     Command1	Poke	Poke

     Command2	Request	Request

4. Add the following code to the General Declaration section of Form1:

      Const AUTOMATIC= 1

      Const MANUAL = 2

      Const NONE = 0

5. Add the following code to the Load event procedure of Form1:

Sub Form_Load ()

    'This procedure will start the VB source application that was

    'created earlier

    z% = Shell("SOURCE", 1)

    z% = DoEvents()	'Causes Windows to finish

'processing the Shell command.

    Text1.LinkMode = NONE	'Clears DDE link if it already

'exists.

    Text1.LinkTopic = "Source|Form1"	'Sets up link with VB source.

    Text1.LinkItem = "Text1"	'Set link to text box on source.

    Text1.LinkMode = MANUAL	'Establish a manual DDE link.

    ManualLink.Value = TRUE	'Sets appropriate option button.

End Sub

6. Add the following code to the Click event procedure of ManualLink:

Sub ManualLink_Click ()

    Request.Visible = TRUE	'Make request button valid.

    Text1.LinkMode = NONE	'Clear DDE Link.

    Text1.LinkMode = MANUAL	'Reestablish new LinkMode.

End Sub

7. Add the following code to the Clink event procedure of AutomaticLink:

Sub AutomaticLink_Click ()

    Request.Visible = FALSE	'No need for button with automatic link.

    Text1.LinkMode = NONE	'Clear DDE Link.

    Text1.LinkMode = AUTOMATIC	'Reestablish new LinkMode.

End Sub

8. Add the following code to the Click event procedure of Request:

Sub Request_Click ()

    'With a manual DDE link, this button will be visible, and when

    'selected it will request an update of information from the source

    'application to the destination application.

    Text1.LinkRequest

End Sub

9. Add the following code to the Click event procedure of Poke:

Sub Poke_Click ()

    'With any DDE link, this button will be visible, and when it's

    'selected, will poke information from the destination application

    'into the source application.

    Text1.LinkPoke

End Sub

You can now run the Visual Basic destination application from the VB.EXE

environment (skip to step 4 below) or you can save the application and

create an .EXE file and run that from Windows (continue to step 1

below).

1. From the File menu, choose Save and save the form and project with

   the name DEST.

2. From the File menu, choose Make EXE File with the name

   DEST.EXE.

3. Exit the Visual Basic environment (VB.EXE).

4. Run the application (from Windows if an .EXE file, or from the Run

   menu if from the VB.EXE environment.)

5. Form1 of the destination application will load and the source

   application will automatically start.

You can now experiment with DDE between Visual Basic applications:

1. Try typing some text into the source's text box and then click the

   Request button. The text appears in the destination's text box.

2. Click the Automatic Link button and then type some more text into the

   source's text box. The text is automatically updated in the

   destination's text box.

3. Type some text into the destination's text box and click the Poke

   button. The text is sent to the source's text box.


How to Create Scrollable Viewports in Visual Basic

See Also

This article is reprinted from the Microsoft Knowledge Base.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 2.0 and 3.0.

Summary:

Scrollable viewports can be created within Visual Basic using standard

Basic calls. The viewports can include bitmaps, graphics, or other

controls.

More Information:

To create a scrollable picture with clipping, you must have two

picture controls. The first picture control is called the stationary

parent picture control. Within the parent picture control, you need to

create a movable child picture control. It is the child picture

control that will be moved within the parent picture control. Moving

the child picture within the parent picture control creates the

clipping effect. During run time when you move the child picture, it

will now be clipped by the boundaries of the parent picture.

To create these two picture controls, do the following:

1. Choose the picture box control from the Toolbox window in Visual

   Basic.

2. Draw a picture on the form. This is the parent picture.

3. Again choose the picture box control from the Toolbox window.

4. Draw the second picture on top of and within the boundaries of

   the first picture control. This is the child picture.

The sample application below shows how to create a scrollable bitmap

within a viewport. Perform the sequence above to create a parent/child

picture control. Add a horizontal scroll bar and a vertical scroll bar

to the form.

Make sure that the path to your bitmap is correct. Several of the

properties are set during run time, which could have been set during

design time as well.

Moving the thumb of the two scroll bars will move the child picture

within the parent picture. The handle (upper-left corner of the

picture) to the child picture will be located either at (0,0) of the

parent picture or to the left and/or right of the parent picture.

Since the clipping region is that of the parent picture, the child

picture will appear to move across the parent picture viewport.

Sub Form_Load ()

   Const PIXEL = 3

   ' Set design properties, included here for simplicity.

   Form1.ScaleMode = PIXEL

   Picture1.ScaleMode = PIXEL

   Picture2.ScaleMode = PIXEL

   ' AutoSize is set to TRUE so that the boundaries of

   ' Picture2 are expanded to the size of the actual bitmap.

   Picture2.AutoSize = TRUE

   ' Get rid of annoying borders.

   Picture1.BorderStyle = NONE

   Picture2.BorderStyle = NONE

   ' Load the picture that you want to display.

   Picture2.Picture = LoadPicture("c:\win\party.bmp")

   ' Initialize location of both pictures.

   Picture1.Move 0, 0, ScaleWidth - VScroll1.Width,_

ScaleHeight - HScroll1.Height

   Picture2.Move 0, 0

   ' Position the horizontal scroll bar.

   HScroll1.Top = Picture1.Height

   HScroll1.Left = 0

   HScroll1.Width = Picture1.Width

   ' Position the vertical scroll bar.

   VScroll1.Top = 0

   VScroll1.Left = Picture1.Width

   VScroll1.Height = Picture1.Height

   ' Set the Max value for the scroll bars.

   HScroll1.Max = Picture2.Width - Picture1.Width

   VScroll1.Max = Picture2.Height - Picture1.Height

   ' Determine if child picture will fill up screen.

   ' If so, then there is no need to use scroll bars.

   VScroll1.Enabled = (Picture1.Height < Picture2.Height)

   HScroll1.Enabled = (Picture1.Width < Picture2.Width)

End Sub

Sub HScroll1_Change ()

  ' Picture2.Left is set to the negative of the value because

  ' as you scroll the scroll bar to the right, the display

  ' should move to the Left, showing more of the right

  ' of the display, and vice-versa when scrolling to the

  ' left.

   Picture2.Left = -HScroll1.Value

End Sub

Sub VScroll1_Change ()

  ' Picture2.Top is set to the negative of the value because

  ' as you scroll the scroll bar down, the display

  ' should move up, showing more of the bottom

  ' of the display, and vice-versa when scrolling up.

   Picture2.Top = -VScroll1.Value

End Sub


How to Get Windows Master List (Task List) Using Visual Basic

See Also

This article is reprinted from the Microsoft Knowledge Base.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 2.0 and 3.0.

Summary:

By calling the Windows API functions GetWindow, GetWindowText, and

GetWindowTextLength, you can get the window titles of all windows

(visible and invisible) loaded under Windows. The list of all of the

window titles under Windows is known as the master list. The Windows

Task Manager contains a list of the window titles for each of the

top-level windows (normally one per application). This list is known

as the task list.

Listed below is a sample program that demonstrates how to AppActivate

an application that is available from a list of top-level windows.

More Information:

The task list is generally a subset of the master list. The Windows

API functions only support methods of getting the master list, not the

task list. However, from the master list you can get a list of all

top-level windows closely resembling the task list. The only

difference is that the list containing the top-level windows may have

more entries than the task list. The reason for this is that it is

possible for an application to remove itself from the task list, but

it will be included as part of the master list.

The example below demonstrates how to get the names of all top-level

windows. The names of child windows can also be obtained by calling

the GetWindow API function with the GW_CHILD constant. Although the

code example only provides an example of using the constants

GW_HWNDFIRST and GW_HWNDNEXT as arguments to GetWindow, the value of

the other constants such as GW_CHILD are provided in the code as well.

Below are the steps necessary to construct a sample program that

demonstrates how to load the task list into a Visual Basic combo

box:

1. Run Visual Basic, or choose New Project from the File menu (ALT, F,

   N) if Visual Basic is already running. Form1 will be created by

   default.

2. Change the caption property of Form1 to AppActivate.

3. Add the following controls to Form1 and change the Names as

   indicated in the chart below:

   Control	Default Name	Name

   -------	------------	-------

   Label Control	Label1	Label1

   Combo Box	Combo1	Combo_ListItem

   Command Button	Command1	Command_Ok

4. Change the Caption properties of the controls as follows:

   Control	CtlName	Caption

   -------	-------	---------

   Label Control	Label1	Application to AppActivate:

   Command Button	Command_OK	OK

5. Add the following code to the general declarations section of

   Form1:

    DefInt A-Z

    '* Windows API function declarations

    Declare Function GetWindow Lib "user" (ByVal hWnd, ByVal wCmd) As

Integer

    Declare Function GetWindowText Lib "user" (ByVal hWnd, ByVal

lpSting$, ByVal nMaxCount) As Integer

    Declare Function GetWindowTextLength Lib "user" (ByVal hWnd)

As Integer

    'Declare constants used by GetWindow

    Const GW_CHILD = 5

    Const GW_HWNDFIRST = 0

    Const GW_HWNDLAST = 1

    Const GW_HWNDNEXT = 2

    Const GW_HWNDPREV = 3

    Const GW_OWNER = 4

6. Add the following code in the Form_Load event procedure of Form1:

     Sub Form_Load ()

       Call LoadTaskList

       'Check to see if any items are in the task list, if

       'not end the program.

       If Combo_ListItem.ListCount > 0 Then

           Combo_ListItem.Text = Combo_ListItem.List(0)

       Else

           MsgBox "Nothing found in task list", 16, "AppActivate"

           Unload Form1

       End If

     End Sub

7. Enter the following code in the Click event procedure of the

   Command_Ok button:

     Sub Command_Ok_Click ()

           'Get the item selected from the text portion of the

           'combo box.

           f$ = Combo_ListItem.Text

           'Simply resume if an "Illegal function call" occurs on

           'the AppActivate statement.

           On Local Error Resume Next

           AppActivate f$

     End Sub

8. Enter the following code under the general declarations section of

   Form1:

     Sub LoadTaskList ()

'Get the hWnd of the first item in the master list

'so we can process the task list entries (top-level only).

CurrWnd = GetWindow(Form1.hWnd, GW_HWNDFIRST)

' Loop while the hWnd returned by GetWindow is valid.

While CurrWnd <> 0

'Get the length of the task name identified by

'CurrWnd in the list.

Length = GetWindowTextLength(CurrWnd)

'Get the task name of the task in the master list.

ListItem$ = Space$(Length + 1)

Length = GetWindowText(CurrWnd, ListItem$, Length + 1)

'If there is an actual task name in the list, add the

'item to the list.

If Length > 0 Then

Combo_ListItem.AddItem ListItem$

End If

'Get the next task list item in the master list.

CurrWnd = GetWindow(CurrWnd, GW_HWNDNEXT)

'Process Windows events.

x = DoEvents()

Wend

End Sub

9. From the Run menu, choose Start (ALT, R, S) to run the program.

From the combo box, select the window title of an application

currently running under Windows. Choose the OK button to activate the

application.


How to Print a Form or Control using StretchDIBits

See Also

This article is reprinted from the Microsoft Knowledge Base.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 2.0 and 3.0.

Summary:

This article demonstrates two Visual Basic procedures: PrintWindow and PrintClient.  Both procedures allow you to print a control or form at a specified location and size on a printed page or to another form or picture control.  The PrintWindow procedure allows you to print the entire control including border, caption and menus.  Whereas, the PrintClient procedure prints everything contained within the form or control excluding the border, caption and menus.  When passed a form, the PrintClient procedure works just like Visual Basic's PrintForm method.  Both procedures will print all child controls contained on the form or control.

The PrintWindow and PrintClient procedures use the StretchDIBits Window API function as well as other Windows API functions to print a form or control.  These functions will print to both Postscript and PCL (printer control language) or HP-type LaserJet

printers.

More Information:

Perform the following steps to create a sample program that demonstrates how to print a form to the printer.

1. Run Visual Basic, or from the File menu select New Project (ALT, F, N) if Visual

   Basic is already running.  Form1 will be created by default.

2. Add two command buttons (Command1 and Command2) to Form1

3. Load the WINLOGO.BMP file (or some other large bitmap) into the Picture property

   of Form1.  WINLOGO.BMP should be located in your Windows directory.

4. From the File menu, select New Module (ALT, F, M).  Module1 will be created.

5. Add the following code to the general declarations section of Module1

DefInt A-Z

Type BITMAPINFOHEADER_Type

    biSize As Long

    biWidth As Long

    biHeight As Long

    biPlanes As Integer

    biBitCount As Integer

    biCompression As Long

    biSizeImage As Long

    biXPelsPerMeter As Long

    biYPelsPerMeter As Long

    biClrUsed As Long

    biClrImportant As Long

End Type

Type BITMAPINFO_Type

    BitmapInfoHeader As BITMAPINFOHEADER_Type

    bmiColors As String * 1024

End Type

Type RectType

    Left As Integer

    Top As Integer

    Right As Integer

    Bottom As Integer

End Type

Type PointType

    x As Integer

    y As Integer

End Type

' DC related API

Declare Function CreateCompatibleDC Lib "gdi" (ByVal hDC)

Declare Function GetWindowDC Lib "user" (ByVal hWnd)

Declare Function GetDC Lib "user" (ByVal hWnd)

Declare Function ReleaseDC Lib "user" (ByVal hWnd, ByVal hDC)

Declare Function DeleteDC Lib "gdi" (ByVal hDC)

' Graphics related API

Declare Function BitBlt Lib "gdi" (ByVal hDC, ByVal x, ByVal y,

ByVal w, ByVal h, ByVal hDC, ByVal x, ByVal y, ByVal o As Long)

Declare Function GetDIBits Lib "gdi" (ByVal hDC, ByVal hBitmap,

ByVal nStartScan, ByVal nNumScans, ByVal lpBits As Long,

BitmapInfo As BITMAPINFO_Type, ByVal wUsage)

Declare Function StretchDIBits Lib "gdi" (ByVal hDC, ByVal DestX,

ByVal DestY, ByVal wDestWidth, ByVal wDestHeight, ByVal SrcX,

ByVal SrcY, ByVal wSrcWidth, ByVal wSrcHeight, ByVal lpBits&,

BitsInfo As BITMAPINFO_Type, ByVal wUsage, ByVal dwRop&)

' General attribute related API

Declare Function GetDeviceCaps Lib "gdi" (ByVal hDC, ByVal nIndex)

Declare Function GetWindowRect Lib "user" (ByVal hWnd, lpRect As

RectType)

Declare Function GetClientRect Lib "user" (ByVal hWnd, lpRect As

RectType)

' Memory allocation related API

Declare Function GlobalAlloc Lib "kernel" (ByVal wFlags, ByVal lMem&)

Declare Function GlobalLock Lib "kernel" (ByVal hMem) As Long

Declare Function GlobalUnlock Lib "kernel" (ByVal hMem)

Declare Function GlobalFree Lib "kernel" (ByVal hMem)

' Graphics object related API

Declare Function CreateCompatibleBitmap Lib "gdi" (ByVal hDC,

ByVal nWidth, ByVal nHeight)

Declare Function DeleteObject Lib "gdi" (ByVal hObject)

Declare Function SelectObject Lib "gdi" (ByVal hDC, ByVal hObject)

Declare Function ClientToScreen Lib "user" (ByVal hWnd,

As PointType)

Declare Function LPToDP Lib "gdi" (ByVal hDC, p As PointType,

ByVal nCount)

Const HORZRES = 8

Const VERTRES = 10

Const SRCCOPY = &HCC0020

Const NEWFRAME = 1

Const BITSPIXEL = 12

Const PLANES = 14

Const BI_RGB = 0

Const BI_RLE8 = 1

Const BI_RLE4 = 2

Const DIB_PAL_COLORS = 1

Const DIB_RGB_COLORS = 0

Const GMEM_MOVEABLE = 2

4. Add the following function, PrintWindow, to Module1

Function PrintWindow (ByVal hDC_Dest, ByVal DestX, ByVal DestY,

ByVal DestDevWidth, ByVal DestDevHeight, ByVal hWnd_SrcWindow)

    Dim Rect As RectType

    Dim BitmapInfo As BITMAPINFO_Type

    cr$ = Chr$(13)

    ' Get the DC for the entire window including the non-client area.

    hDC_Window = GetWindowDC(hWnd_SrcWindow)

    hDC_Mem = CreateCompatibleDC(hDC_Window)

    ' Get the pixel dimensions of the screen.  This is necessary so

    ' that we can determine the relative size of the window compared to

    ' the screen

    ScreenWidth = GetDeviceCaps(hDC_Window, HORZRES)

    ScreenHeight = GetDeviceCaps(hDC_Window, VERTRES)

    ' Get the pixel dimensions of the window to be printed.

    r = GetWindowRect(hWnd_SrcWindow, Rect)

    Window_Width = Abs(Rect.Right - Rect.Left)

    Window_Height = Abs(Rect.Bottom - Rect.Top)

    ' Create a bitmap compatible with the window DC.

    hBmp_Window = CreateCompatibleBitmap(hDC_Window, Window_Width,

                                          Window_Height)

    ' Select the bitmap to hold the window image into the memory DC.

    hPrevBmp = SelectObject(hDC_Mem, hBmp_Window)

    ' Copy the image of the window to the memory DC.

    r1 = BitBlt(hDC_Mem, 0, 0, Window_Width, Window_Height,

                 hDC_Window, 0, 0, SRCCOPY)

    BitsPerPixel = GetDeviceCaps(hDC_Mem, BITSPIXEL)

    ColorPlanes = GetDeviceCaps(hDC_Mem, PLANES)

    BitmapInfo.BitmapInfoHeader.biSize = 40

    BitmapInfo.BitmapInfoHeader.biWidth = Window_Width

    BitmapInfo.BitmapInfoHeader.biHeight = Window_Height

    BitmapInfo.BitmapInfoHeader.biPlanes = 1

    BitmapInfo.BitmapInfoHeader.biBitCount = BitsPerPixel

                                              * ColorPlanes

    BitmapInfo.BitmapInfoHeader.biCompression = BI_RGB

    BitmapInfo.BitmapInfoHeader.biSizeImage = 0

    BitmapInfo.BitmapInfoHeader.biXPelsPerMeter = 0

    BitmapInfo.BitmapInfoHeader.biYPelsPerMeter = 0

    BitmapInfo.BitmapInfoHeader.biClrUsed = 0

    BitmapInfo.BitmapInfoHeader.biClrImportant = 0

    ' Calculate the ratios based on the source and destination

    ' devices. This will help to cause the size of the window image

    ' to be approximately the same proportion on another device

    ' such as a printer.

    WidthRatio! = Window_Width / ScreenWidth

    HeightAspectRatio! = Window_Height / Window_Width

    PrintWidth = WidthRatio! * DestDevWidth

    PrintHeight = HeightAspectRatio! * PrintWidth

    ' Calculate the number of bytes needed to store the image assuming

    ' 8 bits/pixel.

    BytesNeeded& = CLng(Window_Width + 1) * (Window_Height + 1)

    ' Allocate a buffer to hold the bitmap bits.

    hMem = GlobalAlloc(GMEM_MOVEABLE, BytesNeeded&)

    If hDC_Window <> 0 And hBmp_Window <> 0 And hDC_Dest <> 0 And

       hMem <> 0 Then

        lpBits& = GlobalLock(hMem)

        ' Get the bits that make up the image and copy them to the

        ' destination device.

        r2 = GetDIBits(hDC_Mem, hBmp_Window, 0, Window_Height, lpBits&,

                        BitmapInfo, DIB_RGB_COLORS)

        r3 = StretchDIBits(hDC_Dest, DestX, DestY, PrintWidth,

                            PrintHeight, 0, 0, Window_Width,

                            Window_Height, lpBits&, BitmapInfo,

                            DIB_RGB_COLORS, SRCCOPY)

    End If

    ' Reselect in the previous bitmap and select out the source

    ' image bitmap.

    r = SelectObject(hDC_Mem, hPrevBmp)

    ' Release or delete DC's, memory and objects.

    r = GlobalUnlock(hMem)

    r = GlobalFree(hMem)

    r = DeleteDC(hDC_Window)

    r = DeleteObject(hBmp_Window)

    r = ReleaseDC(hWnd_SrcWindow, hDC_Form)

    ' Return true if the window was successfully printed.

    If r2 <> 0 And r3 <> 0 Then

        PrintWindow = True

    Else

        PrintWindow = False

    End If

End Function

6. Add the following function, PrintClient, to Module1

Function PrintClient (ByVal hDC_Dest, ByVal DestX, ByVal DestY,

ByVal DestDevWidth, ByVal DestDevHeight, ByVal hWnd_SrcWindow)

    Dim Rect As RectType, RectClient As RectType

    Dim BitmapInfo As BITMAPINFO_Type

    Dim pWindow As PointType, pClient As PointType, pDiff As PointType

    cr$ = Chr$(13)

    ' Get the DC for the entire window including the non-client area.

    hDC_Window = GetWindowDC(hWnd_SrcWindow)

    hDC_Mem = CreateCompatibleDC(hDC_Window)

    ' Get the pixel dimensions of the screen.

    ScreenWidth = GetDeviceCaps(hDC_Window, HORZRES)

    ScreenHeight = GetDeviceCaps(hDC_Window, VERTRES)

    ' Get the pixel dimensions of the window to be printed.

    r = GetWindowRect(hWnd_SrcWindow, Rect)

    Window_Width = Abs(Rect.Right - Rect.Left)

    Window_Height = Abs(Rect.Bottom - Rect.Top)

    ' Create a bitmap compatible with the window DC.

    hBmp_Window = CreateCompatibleBitmap(hDC_Window, Window_Width,

                                          Window_Height)

    ' Select the bitmap to hold the window image into the memory DC.

    hPrevBmp = SelectObject(hDC_Mem, hBmp_Window)

    ' Copy the image of the window to the memory DC.

    r1 = BitBlt(hDC_Mem, 0, 0, Window_Width, Window_Height,

                hDC_Window, 0, 0, SRCCOPY)

    ' Get the dimensions of the client area.

    r = GetClientRect(hWnd_SrcWindow, RectClient)

    Client_Width = Abs(RectClient.Right - RectClient.Left)

    Client_Height = Abs(RectClient.Bottom - RectClient.Top)

    ' Calculate the pixel difference (x and y) between the upper-left

    ' corner of the non-client area and the upper-left corner of the

    ' client area.

    pClient.x = RectClient.Left

    pClient.y = RectClient.Top

    r = ClientToScreen(hWnd_SrcWindow, pClient)

    xDiff = Abs(pClient.x - Rect.Left)

    yDiff = Abs(pClient.y - Rect.Top)

    ' Create a DC and bitmap to represent the client area of the

    ' window.

    hDC_MemClient = CreateCompatibleDC(hDC_Window)

    hBmp_Client = CreateCompatibleBitmap(hDC_Window, Client_Width,

                                          Client_Height)

    hBmpClientPrev = SelectObject(hDC_MemClient, hBmp_Client)

    ' Bitblt client area of window to memory bitmap representing the

    ' client area.

    r = BitBlt(hDC_MemClient, 0, 0, Client_Width, Client_Height,

                hDC_Mem, xDiff, yDiff, SRCCOPY)

    ' Reselect in the previous bitmap and select out the source

    ' image bitmap.

    r = SelectObject(hDC_Mem, hPrevBmp)

    ' Delete the DC a and bitmap associated with the window.

    r = DeleteDC(hDC_Window)

    r = DeleteObject(hBmp_Window)

    BitsPerPixel = GetDeviceCaps(hDC_MemClient, BITSPIXEL)

    ColorPlanes = GetDeviceCaps(hDC_MemClient, PLANES)

    BitmapInfo.BitmapInfoHeader.biSize = 40

    BitmapInfo.BitmapInfoHeader.biWidth = Client_Width

    BitmapInfo.BitmapInfoHeader.biHeight = Client_Height

    BitmapInfo.BitmapInfoHeader.biPlanes = 1

    BitmapInfo.BitmapInfoHeader.biBitCount = BitsPerPixel

                                              * ColorPlanes

    BitmapInfo.BitmapInfoHeader.biCompression = BI_RGB

    BitmapInfo.BitmapInfoHeader.biSizeImage = 0

    BitmapInfo.BitmapInfoHeader.biXPelsPerMeter = 0

    BitmapInfo.BitmapInfoHeader.biYPelsPerMeter = 0

    BitmapInfo.BitmapInfoHeader.biClrUsed = 0

    BitmapInfo.BitmapInfoHeader.biClrImportant = 0

    ' Calculate the ratios based on the source and destination

    ' devices. This will help to cause the size of the window image to

    ' be approximately the same proportion on another device such as

    ' a printer.

    WidthRatio! = Client_Width / ScreenWidth

    HeightAspectRatio! = Client_Height / Client_Width

    PrintWidth = WidthRatio! * DestDevWidth

    PrintHeight = HeightAspectRatio! * PrintWidth

    ' Calculate the number of bytes needed to store the image assuming

    ' 8 bits/pixel.

    BytesNeeded& = CLng(Window_Width + 1) * (Window_Height + 1)

    ' Allocate a buffer to hold the bitmap bits.

    hMem = GlobalAlloc(GMEM_MOVEABLE, BytesNeeded&)

    If hDC_Window <> 0 And hBmp_Window <> 0 And hDC_Dest <> 0 And

        hMem <> 0 Then

        lpBits& = GlobalLock(hMem)

        ' Get the bits that make up the image and copy them to the

        ' destination device.

        r2 = GetDIBits(hDC_MemClient, hBmp_Client, 0, Client_Height,

                        lpBits&, BitmapInfo, DIB_RGB_COLORS)

        r3 = StretchDIBits(hDC_Dest, DestX, DestY, PrintWidth,

                            PrintHeight, 0, 0, Client_Width,

                            Client_Height, lpBits&, BitmapInfo,

                            DIB_RGB_COLORS, SRCCOPY)

    End If

    ' Select in the previous bitmap.

    r = SelectObject(hDC_MemClient, hBmpClientPrev)

    ' Release or delete DC's, memory and objects.

    r = GlobalUnlock(hMem)

    r = GlobalFree(hMem)

    r = DeleteDC(hDC_MemClient)

    r = DeleteObject(hBmp_Client)

    r = ReleaseDC(hWnd_SrcWindow, hDC_Form)

    ' Return true if the window was successfully printed.

    If r2 <> 0 And r3 <> 0 Then

        PrintClient = True

    Else

        PrintClient = False

    End If

End Function

7. Add DefInt A-Z to the general declarations section of Form1.

8. Add the following code to the Command1_Click event:

Sub Command1_Click ()

    ' The ScaleMode must be set to pixels for the PrintWindow

    ' routine to print correctly.

    Printer.ScaleMode = 3

    ' Change MousePointer to an hourglass.

    Screen.MousePointer = 11

    ' Initialize the printer.

    Printer.Print ""

    ' Copy the image of the form to the printer.

    ' To print Command1 instead, you can substitute Command1.hWnd for Form1.hWnd

    ' as the last argument.

    r = PrintClient(Printer.hDC, 100, 100,

                     Printer.ScaleWidth, Printer.ScaleHeight,

                     Form1.hWnd)

    ' Display an error if the return value from PrintWindow is zero.

    If Not r Then

        MsgBox "Unable to print the form"

    Else

        Printer.EndDoc

    End If

    Screen.MousePointer = 0

End Sub

9. Add the following code to the Command2_Click event:

Sub Command2_Click ()

    ' The ScaleMode must be set to pixels for the PrintWindow

    ' routine to print correctly.

    Printer.ScaleMode = 3

    ' Change MousePointer to an hourglass.

    Screen.MousePointer = 11

    ' Initialize the printer.

    Printer.Print ""

    ' Copy the image of the form to the printer.

    ' To print Command1 instead, you can substitute Command1.hWnd for Form1.hWnd

    ' as the last argument.

    r = PrintWindow(Printer.hDC, 100, 100,

                     Printer.ScaleWidth, Printer.ScaleHeight,

                     Form1.hWnd)

    ' Display an error if the return value from PrintWindow is zero.

    If Not r Then

        MsgBox "Unable to print the form"

    Else

        Printer.EndDoc

    End If

    Screen.MousePointer = 0

End Sub

Run the program. Choosing Command1 prints just the client area of

form1. Choosing Command2 prints the entire area of the form. Note

that you can print any of the forms or controls in a project using

this method and control the size and placement of the forms by

changing the second, third, fourth and fifth parameters of the call

to StretchDIBits.  In the example above, the form or control is sized

in proportion to the size of the screen.


How to Use Windows BitBlt Function From Visual Basic

See Also

This article is reprinted from the Microsoft Knowledge Base.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 2.0 and 3.0.

Summary:

Windows GDI.EXE has a function called BitBlt, which will move the

source device given by the hSrcDC parameter to the destination device

given by the hDestDC parameter. This article explains in detail the

arguments of the Windows BitBlt function call.

More Information:

To use BitBlt within a Visual Basic application, you must Declare the

BitBlt function in  the (declaration) section of any code module or within the (declaration) section of a code

window for the form.  Declare the Function as follows:

Declare Function BitBlt Lib "GDI"	(ByVal hDestDC%,

ByVal X%, ByVal Y%,

ByVal nWidth%,

ByVal nHeight%,

ByVal hSrcDC%,

ByVal XSrc%, ByVal YSrc%,

ByVal dwRop&) As Integer

Note: The above Declare statement must be written on just one line.

The following formal parameters are defined as:

   Formal Parameter	Definition

   ----------------	----------

   hDestDC	Specifies the device context that is to

receive the bitmap.

   X,Y	Specifies the logical x-coordinate and

y-coordinate of the upper-left corner of the

destination rectangle.

   nWidth	Specifies the width (in logical units) of the

destination rectangle and the source bitmap.

   nHeight	Specifies the height (in logical units) of

the destination rectangle and the source

bitmap.

   hSrcDC	Identifies the device context from which the

bitmap will be copied. It must be

NULL(zero) if the dwRop& parameter specifies

a raster operation that does not include a

source.

   XSrc	Specifies the logical x-coordinate and the

y-coordinate of the upper-left corner of the

source bitmap.

  dwRop	Specifies the raster operation to be performed

as defined below.

The following Raster operations are defined using the predefined

constants found in the WINDOWS.H file supplied with the Microsoft

Windows Software Development Kit (SDK). The value

within the "()" is the value to assign to the dwRop& variable.

   Code/Value (hex)	Description

   ----------------	-----------

   BLACKNESS (42)	Turn output black.

   DSINVERT(550009)	Inverts the destination bitmap.

   MERGECOPY(C000CA)	Combines the pattern and the source bitmap

using the Boolean AND operation.

   MERGEPAINT(BB0226)	Combines the inverted source bitmap with the

destination bitmap using the Boolean OR

operator.

   NOTSRCCOPY(330008)	Copies the inverted source bitmap to the

destination.

   NOTSRCERASE(1100A6)	Inverts the result of combining the

destination and source bitmap using the

Boolean OR operator.

   PATCOPY(F00021)	Copies the pattern to the destination bitmap.

   PATINVERT(5A0049)	Combines the destination bitmap with the

pattern using the Boolean XOR operator.

   PATPAINT(FB0A09)	Combines the inverted source bitmap with the

pattern using the Boolean OR operator.

Combines the result of this operation with

the destination bitmap using the Boolean OR

operator.

   SRCAND(8800C6)	Combines pixels of the destination and source

bitmap using the Boolean AND operator.

   SRCCOPY(CC0020)	Copies the source bitmap to the destination

bitmap.

   SRCERASE(4400328)	Inverts the destination bitmap and combines

the results with the source bitmap using the

Boolean AND operator.

   SRCINVERT(660046)	Combines pixels of the destination and source

bitmap using the Boolean XOR operator.

   SRCPAINT(EE0086)	Combines pixels of the destination and source

bitmap using the Boolean OR operator.

   WHITENESS(FF0062)	Turns all output white.

Below is an example of how to copy the contents of a picture control

to the contents of another picture control.

Define a form with two picture controls. Display some graphics on

Picture1 by loading from a picture file or pasting from the clipboard

at design time. You can load a picture from a file as follows: from

the Properties bar, select Picture from the Properties list box and

click the arrow at the right of the Settings box, then select the

desired picture file (such as a .BMP or .ICO file supplied with

Microsoft Windows) from the dialog box.

Add the following code to the Form_Click procedure. Run the program

and click the form. The contents of the first picture will be displayed to

the second picture.

Sub Form_Click ()

   ' Assign information of the destination bitmap. Note that Bitblt

   ' requires coordinates in pixels.

   Const PIXEL = 3

   Picture1.ScaleMode = PIXEL

   Picture2.ScaleMode = PIXEL

   hDestDC% = Picture2.hDC

   X% = 0: Y% = 0

   nWidth% = Picture2.ScaleWidth

   nHeight% = Picture2.ScaleHeight

   ' Assign information of the source bitmap.

   hSrcDC% = Picture1.hDC

   XSrc% = 0: YSrc% = 0

   ' Assign the SRCCOPY constant to the Raster operation.

   dwRop& = &HCC0020

   Suc% = BitBlt(hDestDC%, X%, Y%, nWidth%, nHeight%,_

hSrcDC%, XSrc%, YSrc%, dwRop&)

End Sub


How VB  Can Determine If a Specific Windows Program Is Running

See Also

This article is reprinted from the Microsoft Knowledge Base.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 2.0 and 3.0.

To determine if a specific program is running, call the Windows API

function FindWindow. FindWindow returns the handle of the window whose

class is given by the lpClassname parameter and whose window name, or

caption, is given by the lpCaption parameter. If the returned value is

zero, the application is not running.

More Information:

By calling FindWindow with a combination of a specific program's class

name and/or the title bar caption, your program can determine whether

that specific program is running.

When an application is started from the Program Manager, it registers

the class name of the form. The window class provides information

about the name, attributes, and resources required by your form. All

Visual Basic forms have a class name of "ThunderForm." You can

determine the class name of an application by using SPY.EXE that comes

with the Microsoft Windows Software Development Kit (SDK) version 3.0 or 3.1.

If the window has a caption bar title, you can also use the title to

locate the instance of the running application. This caption text is

valid even when the application is minimized to an icon.

Because another instance of your Visual Basic program will have the

same class name and may have the same title bar caption, you must use

dynamic data exchange (DDE) to determine if another instance of your

Visual Basic program is running. (This DDE technique is not shown in

this article).

The following example shows three ways to determine if the Windows

Calculator is running. To create the program, do the following:

1. Run Visual Basic, or from the File menu, select New Project

   (ALT, F, N) if Visual Basic is already running.  Form1 will be

   created by default.

2. Declare the Windows API function FindWindow in the Global-

   Declarations section of Form1. The variables are declared

   as "Any" because you can pass either a pointer to a string, or a NULL

   (or 0&) value. You are responsible for passing the correct

   variable type. Note that the Declare statement should be entered on

   just one line:

   Declare Function FindWindow% Lib "user" (ByVal lpClassName As Any,

                                            ByVal lpCaption As Any)

3. Add the following code to the form's Click event. This example

   demonstrates how you can find the instance of the application with a

   combination of the class name and/or the window's caption. In this

   example, the application will find an instance of the Windows

   calculator (CALC.EXE).

Sub Form_Click ()

   lpClassName$ = "SciCalc"

   lpCaption$ = "Calculator"

   Print "Handle = ";FindWindow(lpClassName$, 0&)

   Print "Handle = ";FindWindow(0&, lpCaption$)

   Print "Handle = ";FindWindow(lpClassName$,lpCaption$)

End Sub

4. Run this program with CALC.EXE running and without CALC.EXE

   running. If CALC.EXE is running, your application will print an

   arbitrary handle. If CALC.EXE is not running, your application will

   print zero as the handle.

Below are some class names of applications that are shipped with

Windows:

Class Name         Application

-----------        -----------

SciCalc            CALC.EXE

CalWndMain         CALENDAR.EXE

Cardfile           CARDFILE.EXE

Clipboard          CLIPBOARD.EXE

Clock              CLOCK.EXE

CtlPanelClass      CONTROL.EXE

XLMain             EXCEL.EXE

Session            MS-DOS.EXE

Notepad            NOTEPAD.EXE

pbParent           PBRUSH.EXE

Pif                PIFEDIT.EXE

PrintManager       PRINTMAN.EXE

Progman            PROGMAN.EXE   (Windows Program manager)

Recorder           RECORDER.EXE

Reversi            REVERSI.EXE

#32770             SETUP.EXE

Solitaire          SOL.EXE

Terminal           TERMINAL.EXE

WFS_Frame          WINFILE.EXE

MW_WINHELP         WINHELP.EXE

#32770             WINVER.EXE

OpusApp            WINWORD.EXE

MSWRITE_MENU       WRITE.EXE


LSTRCPY API  Call to Receive LPSTR Returned From Other APIs

See Also

This article is reprinted from the Microsoft Knowledge Base.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 2.0 and 3.0.

Summary:

Because Microsoft Visual Basic does not support a pointer data type,

you cannot directly receive a pointer (such as a LPSTR) as the return

value from a Windows API or DLL function. You can work around this

limitation by receiving the return value as a long integer data type

and then using the lstrcpy Windows API function to copy the returned

string into a Visual Basic string.

More Information:

An LPSTR Windows API data type is actually a far pointer to a

null-terminated string of characters. Because an LPSTR is a far

pointer, it can be received as a four byte data type, such as a Visual

Basic long integer. Using the Visual Basic "ByVal" keyword, you can

pass the address stored in a Visual Basic long integer back to the

Windows API lstrcpy routine to copy the characters at that address

into a Visual Basic string variable. Because lstrcpy expects the

target string to be long enough to hold the source string, you should

pad any Visual Basic string passed to lstrcpy to have a size large

enough to hold the source string before passing it to lstrcpy. Failure

to allocate enough space in the Visual Basic string may result in an

Unrecoverable Application Error or General Protection Fault when

you call lstrcpy.

The following is an example program that demonstrates the use of

lstrcpy to retrieve a LPSTR pointer returned from the Windows API

GetDOSEnvironment routine. Note that the capability of the Windows

API GetDOSEnvironment routine is already available through the

Environ function built into Visual Basic; therefore, the following

program mainly serves as an example of using lstrcpy.

'*** General declarations ***

Declare Function GetDosEnvironment Lib "Kernel" () As Long

' The following Declare statement must appear on one line.

Declare Function lstrcpy Lib "Kernel" (ByVal lpString1 As Any, ByVal

lpString2 As Any) As Long

'*** Form Click event code ***

Sub Form_Click()

    Dim lpStrAddress As Long,  DOSEnv$

    ' Allocate space to copy LPSTR into

    DOSEnv$ = Space$(4096)

    ' Get address of returned LPSTR into a long integer

    lpStrAddress = GetDOSEnvironment()

    ' Copy LPSTR into a Visual Basic string

    lpStrAddress = lstrcpy(DOSEnv$, lpStrAddress)

    ' Parse first entry in environment string and print

    DOSEnv$ = RTrim$(LTrim$(DOSEnv$, Len(DOSEnv$) - 1))

    Form1.Print DOSEnv$

End Sub


How to determine when a shelled process has terminated

See Also

This article reprinted from the Microsoft Technical Support

Knowledge Base.  To view

the article, maximize your help window.  This information applies to

Visual Basic

for Windows, versions 2.0 and 3.0.

Summary:

Executing the shell function in a Visual Basic for Windows program,

asynchronously starts another executable program and returns control

back to the Visual Basic application.  The shelled program continues

to run indefinitely until the user closes it, not when your Visual

Basic program terminates.  However, your program can wait until the

shelled program has finished by polling the return value of the

Windows API function GetModuleUsage.  This article describes the

method and provides a code example.

More Information:

Using the Windows API function GetModuleUsage, your program can

monitor the status of a shelled process.  The return value from Shell,

can be used to call GetModuleUsage continuously within a loop to poll

whether or not the shelled program has finished executing.  If the

Shell function is successful, the return value is the instance

handle for the shelled program.  This instance handle can be

passed to GetModuleUsage, to determine the reference count for the

module.  When GetModuleUsage returns a value of 0 or less, the application

has finished its execution.

Regardless of the WindowStyle used to shell the program, this

algorithm works correctly.  Additionally, this method does work under

the following situations:

   - Shelling to Windows programs.

   - Shelling to MS-DOS programs.

   - Shelling to applications that do not display a window.

Below are the steps necessary to build a Visual Basic for Windows

program that uses the Shell function to execute the Windows Notepad

accessory. The program is an example of how to use the Windows API

function GetModuleUsage to wait until a shelled process has terminated

before resuming execution.

Code Example

------------

1. Run Visual Basic for Windows, or from the File menu, choose New

   Project (ALT, F, N) if Visual Basic for Windows is already running.

   Form1 is created by default.

2. Add the following code to the general Declarations section of

Form1:

      Declare Function GetModuleUsage% Lib "Kernel" (ByVal hModule%)

3. Add the following code to the Form_Click event procedure of Form1:

   Sub Form_Click ()

       x% = Shell("notepad.exe") ' Modify path as needed.

       While GetModuleUsage(x%) > 0    ' Has Shelled program finished?

          z% = DoEvents()              ' If not, yield to Windows.

       Wend

       MsgBox "Shelled application just terminated", 64

   End Sub

4. From the Run menu, select Start (ALT, R, S) to run the program.

5. With the mouse click on Form1.  The Notepad application is shelled.

The MsgBox statement following the Shell Function is not executed, as

it would normally would be without the While loop above it.  The

message box does not appear until Notepad is closed by choosing Exit

from its File menu (ALT, F, X).


Keeping the Current Record the Same After Using Refresh

See Also

This article is reprinted from the Microsoft Knowledge Base.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 2.0 and 3.0.

Summary:

In Visual Basic version 3.0 for Windows, when the Refresh method

updates the recordset for a data control, it recreates the

recordset and resets the current record. This invalidates all

existing bookmarks for that recordset. This behavior is by

design. It is not a Visual Basic bug but rather a design feature

of the data control.

However, this behavior may be undesirable if you want to

refresh the recordset and maintain the current record. This

article explains how to restore the current record after

executing the Refresh method.

More Information:

Although there is no simple way to retain the current record after

executing the Refresh method, you can restore the current record.

To do so, store unique field data for the current record. Then

use the stored field data to execute the Refresh method followed

by the FindFirst method. The FindFirst method uses the stored

field data to restore the current record.

The following steps demonstrate how to restore the current record

after executing the Refresh method:

1. Start Visual Basic, or from the File menu, choose New Project

   (ALT, F, N) if Visual Basic is already running. Form1 is

   created by default.

2. Put a data control (Data1) on Form1.

3. Set the DatabaseName property for Data1 to <path name>BIBLIO.MDB

   where <path name> represents the full path to the Visual Basic

   BIBLIO.MDB sample database.

4. Set the RecordSource property of Data1 to Authors, which is the

   name of the table in the BIBLIO.MDB database.

5. Put a Text box (Text1) on Form1

6. Set the DataSource property of Text1 to Data1

7. Set the DataField property of Text1 to Author, which is the name

   of the field (column) in the Authors table.

8. Put a command button (Command1) on Form1

9. Change the Caption property of Command1 to Refresh.

10. Add the following code to the Command1_Click event

    Sub Command1_Click ()

       Dim CurrRec As Variant

       'Hide the text box and emulate it by drawing a border

       text1.Visible = False

       Line (text1.Left, text1.Top)-(text1.Left + text1.Width,

                text1.Top + text1.Height), , B

       'Store the value of a unique field for the current record

       CurrRec = Data1.RecordSet!Au_ID

       'Update the RecordSet

       Data1.Refresh

       'Restore the current record by using the stored field value

       'to find

       Data1.RecordSet.FindFirst "Au_ID = " & CurrRec

       text1.Visible = True

    End Sub

11. From the Run menu, choose Start (ALT, R, S) or press the F5 key

    to run the program.

12. Using the data control, move to the next record. You should see

    "Atre, Shaku" displayed in the text box

13. Using the data control, move further into the file. To do this,

    click the right arrow or click the rightmost button -- the one

    with the arrow and bar -- to move to the end of the file.

14. Click the Refresh button. The name of the first author in the

    recordset is displayed in Text1 for an instant. Then the

    current author is redisplayed.


Copying the Current Database Record Into a Record Variable

See Also

This article is reprinted from the Microsoft Knowledge Base.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 2.0 and 3.0.

Summary:

Although Visual Basic version 3.0 for Windows does not provide a

direct way to assign the current database record to a record variable,

this article gives you a generic routine. Using this generic routine,

you can assign the current record, containing any number of fields,

to a record variable that represents the structure of the current

database record.

This generic routine is useful if you have existing database code that

uses record variables to represent database records. For example, using

this routine, you can use the Visual Basic data access features without

making major changes to how you read and handle records. After you

assign the contents of the current record to a record variable of the

appropriate type, your code can manipulate the record as before,

independent of the underlying database.

The routine demonstrated below requires Windows version 3.1 or later

because it uses the Windows API function hmemcpy(), which was

introduced in Windows version 3.1. An error will result on the call to

hmemcpy() if you attempt to run the sample using Windows version 3.0.

More Information:

Follow these general steps to assign the current database record to a

record variable:

1. Define a Type ... End Type structure that represents the record

   structure of the database table that you are going to use. This

   requires that the number and data types of the fields in the table

   be known in advance.

   To determine the structure of the table quickly, run the Data Manager

   tool provided with Visual Basic. From the Data Manager File menu,

   choose Open to open the database. Select a Table from the list

   displayed in the Database window, and choose the Design button to

   see the table's field names, data types, and field lengths.

2. Dimension a variable of the user-defined type structure created in

   step 1.

3. Create a generic routine using the Windows API hmemcpy() function to

   copy each field of the current database record into a string. To do

   this, step through all of the fields in the Fields collection and

   accumulate the fields together into a single string.

4. Use the hmemcpy() function to copy the contents of the string created

   in step 3 to the record variable created in step 2.

Perform the following steps to create an example application that

demonstrates how to copy the current database record into a user-defined

structure. This example shows you how to use the Data control to copy

a record from the BIBLIO.MDB sample database provided with Visual Basic.

1. Start Visual Basic or from the File menu, choose New Project (ALT, F, N)

   if Visual Basic is already running. Form1 is created by default.

2. Add two text boxes (Text1 and Text2) to Form1

3. Add a data control (Data1) to Form1

4. Add a command button (Command1) to Form1.

5. Using the following table as a guide, set the properties of the controls

   you added in steps 2, 3 and 4.

   Control Name   Property       New Value    Comment

   ------------------------------------------------------------------

   Command1       Caption        "Copy"

   Data1          DatabaseName   BIBLIO.MDB   You will also need to

                                              provide the full path to

                                              this file, which should

                                              be in your Visual Basic

                                              directory C:\VB

   Data1          RecordSource   Authors

   Text1          DataSource     Data1

   Text1          DataField      AU_ID

   Text2          DataSource     Data1

   Text2          DataField      Author

6. From the File menu, choose New Module (ALT, F, M). Module1 is created.

7. Add the following code to the general declarations section of Module1:

   Type typeAuthor

      AU_ID As Long

      Author As String * 255

   End Type

   ' Enter the following Declare on a single line:

   Declare Sub hmemcpy Lib "KERNEL" (dest As Any, src As Any, ByVal

                                     Size As Long)

8. Add the following code to Module1:

   Function GetCurrRec (ds As Dynaset) As String

      Dim i As Integer

      Static FieldStr As String

      Static recStr As String

      recStr = ""

      'Step through each field in the current record and accumulate

      'the contents of each field into a string

      For i = 0 To ds.Fields.Count - 1

         'Pad out to the right size

         FieldStr = Space(ds.Fields(i).Size)

         Select Case ds.Fields(i).Type

            'Copy the binary representation of the field to a

            'string (FieldStr)

            Case 1, 2       'Bytes

               hmemcpy ByVal FieldStr, CInt(ds.Fields(i).Value),

                                                     ds.Fields(i).Size

            Case 3          'Integers

               hmemcpy ByVal FieldStr, CInt(ds.Fields(i).Value),

                                                     ds.Fields(i).Size

            Case 4          'Long integers

               hmemcpy ByVal FieldStr, CLng(ds.Fields(i).Value),

                                                     ds.Fields(i).Size

            Case 5          'Currency

               hmemcpy ByVal FieldStr, CCur(ds.Fields(i).Value),

                                                     ds.Fields(i).Size

            Case 6          'Singles

               hmemcpy ByVal FieldStr, CSng(ds.Fields(i).Value),

                                                     ds.Fields(i).Size

            Case 7, 8       'Doubles

               hmemcpy ByVal FieldStr, CDbl(ds.Fields(i).Value),

                                                     ds.Fields(i).Size

            Case 9, 10      'String types

               hmemcpy ByVal FieldStr, ByVal CStr(ds.Fields(i).Value),

                                                Len(ds.Fields(i).Value)

            Case 11, 12     'Memo and long binary

               FieldStr = ds.Fields(i).GetChunk(0, ds.Fields(i).FieldSize())

         End Select

         'Accumulate the field string into a record string

         recStr = recStr & FieldStr

      Next

      'Return the accumulated string containing the contents of all

      'fields in the current record

      GetCurrRec = recStr

   End Function

9. Add the following code to the Command1_Click event in Form1:

   Sub Command1_Click ()

      Dim recAuthor As typeAuthor

      Dim strCurrRec As String

      Dim strVerify As String

      'Copy the current record in the Authors table to a string

      strCurrRec = GetCurrRec(Data1.RecordSet)

      'Copy the string to the record variable that has a structure

      'matching the struture of the current record in the Authors table

      hmemcpy recAuthor, ByVal strCurrRec, Len(recAuthor)

      'Verify that the correct results were returned by displaying

      'the contents of the record variable

      strVerify = "AU_ID: " & Format$(recAuthor.AU_ID) & Chr$(13)

      strVerify = strVerify & "Author: " & Trim(recAuthor.Author)

      MsgBox strVerify

   End Sub

10. From the Run menu, choose Start (ALT, R, S), or press the F5 key

    to run the program.

Click the scroll bar of the Data control to select an author. The Text1

box displays the author ID, and the Text2 box displays the author's

name. Click the "Copy" button to copy the current author's information

to the record variable and see contents of the record variable

displayed in a MsgBox.


Using a Data Control to Scroll Up and Down in a Recordset

See Also

This article is reprinted from the Microsoft Knowledge Base.  To view the article, maximize your help window.  This information applies to Visual Basic for Windows, versions 2.0 and 3.0.

Summary:

The data control provided with Visual Basic does not provide an

automatic way to scroll up or down in a recordset by groups (pages)

of records. This article shows you how to use the MoveNext and

MovePrevious methods to scroll up or down in a recordset by groups

(pages) of records without displaying all the records.

More Information:

Usually, when you use the MoveNext and MovePrevious methods to scroll

up or down by a specified number of records, all the records are

displayed as you move through them. This is undesirable behavior if

you want a way to scroll through the recordset by pages.

In order to display only the record you have scrolled to, without

displaying all the records in between, you need to use the Clone

method to clone the data control's recordset.

Once you clone the recordset, you can use the MoveNext and MovePrevious

methods to move to the desired record within the cloned recordset. Then

set the Bookmark property of the original recordset to the Bookmark

property of the cloned recordset. This makes the desired record the

current record in the original recordset and causes the fields of this

record to be displayed in the bound data controls.

Perform the following steps to create an example program that

demonstrates how to scroll up and down by pages in a data control's

recordset:

1. Start Visual Basic or from the File menu, choose New Project (ALT, F, N)

   if Visual Basic is already running. Form1 is created by default.

2. Add a data control (Data1) to Form1.

3. Add two text boxes (Text1 and Text2) to Form1.

4. Add two command buttons (Command1 and Command2) to Form1.

5. Using the following table as a guide, set the properties of the

   controls you added in steps 2, 3, and 4.

   Control Name   Property       New Value    Comment

   --------------------------------------------------------------------

   Command1       Caption        "Page Up"

   Command2       Caption        "Page Down"

   Data1          DatabaseName   BIBLIO.MDB   Provide the full path to

                                              to this file, which

                                              should be in the Visual

                                              Basic directory -- C:\VB

   Data1          RecordSource   Authors

   Text1          DataSource     Data1

   Text1          DataField      AU_ID

   Text2          DataSource     Data1

   Text2          DataField      Author

6. Add the following code to the general declarations section of Form1:

   Const PAGEUP = 1

   Const PAGEDOWN = 2

   Const Records_per_Page = 10

7. Add the following procedure to Form1:

   Sub Page (RecSet As Dynaset, ByVal iDirection As Integer, ByVal

                                                  Records As Integer)

      Dim dsClone As Dynaset

      Dim i As Integer

      'Copy the visible recordset. This is necessary so that you can

      'move through the clone recordset without displaying each record.

      Set dsClone = RecSet.Clone()

      'Set the current record of the cloned recordset to the current

      'record of the visible recordset.

      dsClone.Bookmark = RecSet.Bookmark

      'Scroll up or down N number of records in the cloned recordset.

      i = 1

      Do While i <= Records And Not dsClone.EOF And Not dsClone.BOF

         If iDirection = PAGEUP Then

            dsClone.MovePrevious

         Else

            dsClone.MoveNext

         End If

         i = i + 1

      Loop

      'If the above loop caused a BOF or EOF condition, move to the

      'beginning or end of the recordset as appropriate.

      If dsClone.BOF And iDirection = PAGEUP Then

         dsClone.MoveFirst

      ElseIf dsClone.EOF And iDirection = PAGEDOWN Then

         dsClone.MoveLast

      End If

      'Change the bookmark of the visible record set to the bookmark

      'of the desired record. This makes the current record of the

      'visible recordset match the record moved to in the cloned

      'dynaset. The fields of the record are displayed in the data

      'bound controls without displaying any intervening records.

      RecSet.Bookmark = dsClone.Bookmark

   End Sub

8. Add the following code to the Command1_Click event for Form1:

    Sub Command1_Click ()

       'Scroll up 10 records in the recordset associated with Data1

       Page Data1.RecordSet, PAGEUP, Records_per_Page

    End Sub

9. Add the following code to the Command2_Click event for Form1:

   Sub Command2_Click ()

      'Scroll down 10 records in the recordset associated with Data1

       Page Data1.RecordSet, PAGEDOWN, Records_per_Page

   End Sub

10. From the Run menu, choose Start (ALT, R, S), or press the F5 key

    to run the program.

Click the "Page Up" or "Page Down" button to scroll up or down in

10-record increments. Change the value of Records_per_Page to modify

the pagesize.


Connect Property

See Also

Applies To

Data control, Database object, TableDef object.

Description

Determines the information used to open an external database or to attach a table from an external database.

Data control [image] Read/write at design time and run time.

Database object [image] Read-only.

TableDef object [image] Read/write at run time only in the Professional Edition with a new object not yet appended to a collection.

Note   When using a Microsoft Access database, leave this property blank.

Syntax

{database | tabledef | datactrl }.Connect [ = connectinfo ]

Remarks

The database is the Database property of a data control.  In the Professional Edition, it can also be an object variable identifying an open Database.  The tabledef can be a member of the TableDefs collection of a data control's Database property.  In the Professional Edition, a tabledef can also be an object variable identifying an existing TableDef.

You can use the DatabaseName, Exclusive, ReadOnly, and Connect properties to open a database with a data control.  For example, a data control uses these property settings to open a Paradox database:

Data1.DatabaseName = "C:\PDX\PUBS"
Data1.Exclusive = True
Data1.ReadOnly = False
Data1.Connect = "Paradox;"

In the Professional Edition, these properties represent the arguments in the OpenDatabase function.  For example, the following code opens the same Paradox database:

Set MyDB = OpenDatabase("C:\PDX\PUBS", True, False, "Paradox;")

For ODBC external databases such as SQL Server or Oracle (which must have been registered with ODBC.INI), the Connect property value for the database might be as follows:

ODBC;DSN=ourdbsrvr,UID=guest;PWD=guest;

DSN is the data source name, UID is the user ID, and PWD is the password.

For a TableDef of a non-ODBC attached table, the Connect property is the path name of the file containing the table and the SourceTableName property identifies the Table within that file.  For ODBC attached tables, the Connect property is the same as for the ODBC database.

Note   For an attached table, you must set both the Connect and SourceTableName properties before using the Append method in order to establish a link.

If you provide no values (or empty strings) for the DatabaseName and Connect properties, a list of registered ODBC data source names appears, allowing a user to select one.

For more information about ODBC drivers such as SQL Server or Oracle, see the Help file provided with the driver.

If a password is required but not provided in the Connect property, a Login dialog box appears each time a table is accessed.

In the Professional Edition, you can attach a table of an external database or of another Microsoft Access database by creating a new TableDef object, setting the SourceTableName and Connect properties, then appending the TableDef to the TableDefs collection of a Database.

Data Type

String


See Also

Help:

Attributes Property

DatabaseName Property

Exclusive Property

New

OpenDatabase Function (Professional Edition Only)

ReadOnly Property

TableDefs Collection

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"

Programmer's Guide:

Chapter 20, "Accessing Databases with the Data Control"


Fields Property

See Also	Example (Professional Edition Only)

Applies To

Index object.

Description

Determines which TableDef fields are key fields in an index.  Read-only when the Index is a member of a collection.  Read/write only in the Professional Edition with a new object not yet appended to an Indexes collection.

Usage

index.Fields [ = fieldlist ]

Remarks

An Index object can have one or more fields representing key values for each record.  Field names are separated by semicolons.

To get the fieldlist for an index, specify both the index and the recordset:

Key = Data1.Recordset.Indexes("PrimaryKey").Fields

With a data control, the Index must be a member of an Indexes collection.  To get the value of this property, you can use the control's Recordset property, or you can use the TableDefs collection of the Database property of the data control.  For example:

Key = Data1.Database.TableDefs("Areas").Indexes("PrimaryKey").Fields

In the Professional Edition, you can use an object variable of type Index.  You can create a new Index in a table by creating a new Index object, setting its properties, then appending it to the Indexes collection of the table's TableDef object.

Data Type

String


See Also

Help:

Append Method (Professional Edition Only)

Fields Collection

Indexes Collection

Name Property

New

Unique Property

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


Fields Property Example (Professional Edition Only)

This example adds a new index to the Authors table.

Dim TempIndex As New Index	' Create new Index object.
TempIndex.Name = "Full Name"	' Set Index properties.
TempIndex.Fields = "LName; FName"
TempIndex.Unique = True
' Append the new Index to the Indexes collection.
MyDB.TableDefs("Authors").Indexes.Append TempIndex


Index Property (Control Arrays)

See Also	Example

Applies To

Check box, combo box, command button, common dialog, data control, directory list box, drive list box, file list box, frame, grid, horizontal scroll bar, image, label, line, list box, menu, OLE control, option button, picture box, shape, text box, timer, vertical scroll bar.

Description

Specifies the number that uniquely identifies a control in a control array.  Available only if the control is part of a control array; read-only at run time.

Usage

[form.]control [( integer )].Index

Setting

The Index property settings are:

Setting	Description

No value	(Default) Not part of an array.

0 to 32,767	Part of an array.  Specify an integer greater than or equal to 0 to assign a control to a control array.  You can specify the same name for two or more controls through the Name property.  Visual Basic automatically assigns the first unique index available within the control array.

Remarks

Because control array elements share the same Name property setting, you must use the Index property in code to refer to a particular control in the array.  The Index must appear as a number in parentheses next to the control array name [image] for example:

MyButtons(3)

When a control in the array recognizes that an event has occurred, Visual Basic calls the array's event procedure and passes the applicable Index as an additional argument.  This property is also used when you create controls dynamically at run time with the Load statement or remove them with the Unload statement.

With menu control arrays, the first menu item must have an index of 0, and the following menu items must have indexes numbered contiguously from top to bottom.

Note	To remove a control from a control array, change the control's Name property setting.

Data Type

Integer


See Also

Help:

Creating a Control Array

Creating a Menu Bar

Index Object

Index Property (Data Access)

Tag Property

Programmer's Guide:

Chapter 3, "Creating and Using Controls"

Chapter 4, "Menus and Dialogs"


Index Property (Control Arrays) Example

The example starts with two option buttons and adds new option buttons to the form each time you click a command button.  When you click an option button, the FillStyle property is set and a new circle is drawn.  To try this example, paste the code into the Declarations section of a form that has two option buttons (set the Name property to optButton for both buttons to create an array), a command button, and a large picture box.

Sub OptButton_Click (Index As Integer)
Dim H, W	' Declare variables.
Picture1.Cls	' Clear picture.
Picture1.FillStyle = Index	' Set FillStyle.
W = Picture1.ScaleWidth / 2	' Get size of circle.
H = Picture1.ScaleHeight / 2
Picture1.Circle (W, H), W / 2	' Draw circle.
End Sub

Sub Command1_Click ()
Static MaxIdx	' Largest index in array.
If MaxIdx = 0 Then MaxIdx = 1	' Preset MaxIdx.
MaxIdx = MaxIdx + 1	' Increment index.
If MaxIdx > 7 Then Exit Sub	' Put 8 buttons on form.
Load OptButton(MaxIdx)	' Create new item in array.
' Set location of new option button under previous button.
OptButton(MaxIdx).Top = OptButton(MaxIdx - 1).Top + 360
OptButton(MaxIdx).Visible = True	' Make new button visible.
End Sub


Index Property (Data Access}

See Also	Example (Professional Edition Only)

Applies To

Table objectv

Description

With data access, determines which existing index is the current index used to sort records in a Table and in recordsets created from that Table.  The default is blank.  Not available at design time; read/write at run time.

Syntax

table.Index [ = indexname ]

Remarks

The data in a table exists in the order it was entered.  Set the Index property to the name of an index to set the order to a named index in the Indexes collection of a TableDef object.

The specified index must already be defined.  If you set the Index property to an index that doesn't exist, or if the index isn't set when you use the Seek method, an error occurs.

To set this property with a data control, specify the TableDef, set the index, then Refresh the control:

Data1.RecordSource = "Publishers"
Data1.Database.TableDefs("Publishers").Index = "PrimaryKey"
Data1.Refresh

In the Professional Edition, you can create a new Index in a Table by creating a new Index object, setting its properties, then appending it to the Indexes collection of the Table's TableDef.

You can use the Indexes collection of a TableDef to determine what indexes are available in a Table.

The records in a Table can be ordered only according to the indexes defined for it.  To sort the Table records in some other order, create a Dynaset or Snapshot that has a different sort order.  To specify the sort order for Dynasets and Snapshots, use the Sort property.

The Index property of a control is not the same as the Index property of a data access object.

Data Type

String


See Also

Help:

Append Method

Index Property (Control Arrays)

Indexes Collection

New

Seek Method (Professional Edition Only)

Sort Property (Professional Edition Only)

TableDef Object

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"

Chapter 3, "Creating Programs to Manipulate Data"

Programmer's Guide

Chapter 20, "Accessing Databases with the Data Control"


Index Property Example

See the example for the Unique property.


Size Property

See Also	Example (Professional Edition Only)

Applies To

Field object.

Description

Determines the maximum size, in bytes, of a specified Field.  Read-only when the Field is a member of the Fields collection of a TableDef in an open Database.  Read/write only in the Professional Edition with a new object not yet appended to a collection, or with an existing Field object in a closed Database.

Syntax

field.Size [ = sizenum ]

Settings

The Size property settings for specific Microsoft Access field data types are:

Size	Type	Description

1	1	True/False

1	2	Byte

2	3	Integer

4	4	Long

8	5	Currency

4	6	Single

8	7	Double

8	8	Date/Time

1 to 255	10	Text

0	11	Long Binary

0	12	Memo

Remarks

The Size property is primarily determined by its Type property except for Text fields (type 10).  For Long Binary and Memo fields, the size is always 0.  You can use the FieldSize method to determine the size of the data in a specific record.  For Text fields, you can specify the maximum length of the Field in bytes.  The maximum Size for Text fields is 255.

To specify a Field using the data control, use the Fields collection of the Recordset property, or of a TableDef in the TableDefs collection of the control's Database property.  For example:

HowBig = Data1.Recordset.Fields("PubID").Size
HowBig = Data1.Database.TableDefs("Authors").Fields("LName").Size

The maximum size of individual records in Memo and Long Binary fields is limited only by your system resources.

Data Type

Long


See Also

Help:

Fields Collection

FieldSize Method

Name Property

New

TableDef Object

TableDefs Collection

Type Property

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


Size, Type Properties Example (Professional Edition Only)

This example adds a new field to the set of Fields in the Calls table.

Const DB_TEXT = 10	' Type = Text.
Dim TempField As New Field	' Create a new object.
TempField.Name = "Baseball League"	' Set Field properties.
TempField.Type = DB_TEXT
TempField.Size = 20
' Append the new Field to the Fields collection.
MyDB.TableDefs("Publishers").Fields.Append TempField


Type Property

See Also	Example (Professional Edition Only)

Applies To

Field object.

Description

Determines the type of data a Field contains.  Read-only if the Field is a member of the Fields collection of a TableDef.  Read/write only in the Professional Edition with a new object not yet appended to a collection.

Usage

field.Type [ = typenumber ]

Setting

The symbolic constants and settings of the Type property are:

Constant	Setting	Description	Visual Basic data type

DB_BOOLEAN	1	True/False	Integer (0 or [image] 1)

DB_BYTE	2	Byte	Integer (0 [image] 255)

DB_INTEGER	3	Integer	Integer

DB_LONG	4	Long	Long

DB_CURRENCY	5	Currency	Double

DB_SINGLE	6	Single	Single

DB_DOUBLE	7	Double	Double

DB_DATE	8	Date/Time	Variant

DB_TEXT	10	Text	String

DB_LONGBINARY	11	Long Binary	String

DB_MEMO	12	Memo	String

These values are in the Visual Basic file DATACONS.TXT.

Remarks

With a data control, the Field is a member of the Fields collection of the Recordset property.  You can also access a Field in a TableDef of the TableDefs collection of the Database property of a data control.

If the database does not support one of these types, an error occurs when a field of that type is used.

In the Professional Edition, you can create a new Field by creating a new Field object, setting its properties, then appending the Field to the Fields collection of a TableDef.


See Also

Help:

Fields Collection

Name Property

New

Size Property

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


proTypeEx
Type Property Example

See the example for the Size property.


Unique Property

See Also	Example (Professional Edition Only)

Applies To

Index object.

Description

Determines whether an Index allows records with duplicate values in key fields.  This property is read-only if the Index is a member of the Indexes collection of a TableDef.  Read/write only in the Professional Edition with a new object not yet appended to a collection.

Usage

indexobject.Unique [ = { True | False }]

Setting

The Unique property settings are:

Setting	Description

True	Records must be unique.

False	Records need not be unique.

Remarks

If the Unique property of indexobject is True, then no two records can contain the same data value in the listed key fields.  An attempt to add or edit a record that results in a duplicate unique key generates an error when the record is updated.

With a data control, the Index must be a member of an Indexes collection.  To get the value of the Unique property, you can use the TableDefs collection of the Database property of a data control.  For example:

If Data1.Database.TableDefs("Areas").Indexes("Full Name").Unique Then...

In the Professional Edition, you can also use an object variable of type Index.  You can create a new Index in a Table by creating a New Index object, setting its properties, then adding it to the Indexes collection of the table's TableDef object with the Append method.

Data Type

Long


See Also

Help:

Append Method

Fields Property

Indexes Collection

New

TableDef Object

Update Method

Data Access Guide:

Chapter 2, "Database Management Using Visual Basic"


Index (Data Access), Unique Properties Example (Professional Edition Only)

This example adds a new Index to a TableDef, then makes that index the current index, and creates a Dynaset based on the Table.

Const DB_TEXT = 10	' Type = Text.
Dim Tb As Table, Dn As Dynaset
TempIndex As New Index	' Create a new object.
TempIndex.Name = "PubID Name"	' Set Index properties.
TempIndex.Fields = "PubID;Name"
TempIndex.Unique = True
' Append the new Index to the Indexes collection
MyDB.TableDefs("Publishers").Indexes.Append TempIndex
Set Tb = MyDB.OpenTable("Publishers")	' Open the table.
Tb.Index = "PubID Name"	' Set table's current index.
Set Dn = Tb.CreateDynaset()	' Create Dynaset on the table.


Accessibility for People With Disabilities

Microsoft is committed to making its products and services easier for everyone to use.  This help file provides information about the following products and services, which make Microsoft Windows more accessible for people with disabilities:

Microsoft support services for people who are deaf or hard-of-hearing

Access Pack for Microsoft Windows, a software utility that makes using Microsoft Windows easier for people with motion or hearing disabilities

Keyboard layouts designed for people who type with only one hand or a wand

Microsoft software documentation on audio cassettes and floppy disks

Products available for people who are blind or have low vision

Hints for customizing Microsoft Windows

Information about other products and services for people with disabilities

Note   The information in this section applies only to Windows users in the United States.  If you are outside the United States, your Windows package contains a subsidiary information card listing product support telephone numbers and addresses.  You can contact your subsidiary to find out whether the type of products and services described in this help file are available in your area.


MS Support Services for People Who are Deaf or Hard-of-Hearing

Through a text telephone (TT or TDD) service, Microsoft provides people who are deaf or hard-of-hearing with complete access to Microsoft's product and customer support services.

You can contact Microsoft support services using a text telephone by dialing (206) 6354948 between 6:00 A.M. and 6:00 P.M. Pacific time.  Microsofts product support services are subject to Microsofts prices, terms, and conditions in place at the time the service is used.


Access Pack for Microsoft Windows

Microsoft distributes Access Pack for Microsoft Windows, which provides people with movement or hearing disabilities better access to computers running Microsoft Windows.  Access Pack for Microsoft Windows contains several features that do the following:

Allow single-fingered typing of SHIFT, CTRL and ALT key combinations.

Ignore accidental keystrokes.

Adjust the rate at which a character is repeated when you hold down a key, or turn off character repeating entirely.

Prevent extra characters if you unintentionally press a key more than once.

Enable you to control the mouse cursor using the keyboard.

Enable you to control the computer's keyboard and mouse using an alternate input device.

Provide a visual cue when the computer makes sounds.

Access Pack for Microsoft Windows is included on the Microsoft Windows Driver Library in the file ACCESS.EXE.  If you have a modem, you can download Microsoft Windows Driver Library components from network services, including the following:

CompuServe®

GEnie™

Microsoft OnLine

Various user-group bulletin boards (such as the bulletin-board services on the Association of PC User Groups network)

Microsoft Download Service (MSDL), which you can reach by calling (206) 936-MSDL (936-6735) any time except between 1:00 A.M. and 2:30 A.M. Pacific time.  Use the following communications settings:

For this setting	Specify

Baud rate	1200, 2400, or 9600

Parity	None

Data bits	8

Stop bits	1

People within the United States who do not have a modem can order disks by calling Microsoft Product Support Services at (206) 637-7098 or (206) 635-4948 (text telephone).


Keyboard Layouts for Single-Handed Users

Microsoft distributes Dvorak keyboard layouts that make the most frequently typed characters on a keyboard more accessible to people who have difficulty using the standard "QWERTY" layout.  There are three Dvorak layouts: one for two-handed users, one for people who type only with their left hand, and one for people who type only with their right hand.  The left or right hand keyboard layouts can also be used by people who type with a single finger or a wand.  You do not need to purchase any special equipment in order to use these features.

Microsoft Windows already supports the Dvorak keyboard layout, which can be useful for coping with or avoiding types of repetitive motion injuries associated with typing.  The two layouts for people who type with only one hand are distributed as Microsoft Application Note GA0650.  It is also contained in file GA0650.ZIP on most network services or GA0650.EXE on the Microsoft Download Service.  For instructions on obtaining this application note see Access Pack for Microsoft Windows


Documentation on Audio Cassettes and Floppy Disks

People who cannot use printed documentation can obtain most of Microsoft's publications from Recording for the Blind, Inc.  Recording for the Blind distributes these documents to registered members of their distribution service, either on audio cassettes or on floppy disks.  Recording for the Blind's collection contains more than 80,000 titles, including Microsoft product documentation and books from Microsoft Press.  You can contact Recording for the Blind at the following address:

Recording for the Blind, Inc.
20 Roszel Road
Princeton, NJ  08540

Phone: (800) 221-4792
Fax: (609) 987-8116

From outside the United States, you can contact Recording for the Blind at:

(609) 452-0606


Products for People Who are Blind or Have Low Vision

There are numerous products available to help people who are blind or have low vision use Microsoft Windows.  For people with low vision there are several screen enlargement utilities, and for people who cannot use visual information there are screen readers which provide alternative output by synthesized voice or refreshable Braille displays.  In addition, people with low vision can customize the Microsoft Windows display to suit their disabilities.

For more information on the various products available, see Getting More Information. For more information about customizing Microsoft Windows for low vision individuals, see Customizing Windows.


Customizing Windows

There are many ways you can adjust the appearance and behavior of Microsoft Windows to suit varying eyesight and motor skills without requiring any additional software or hardware.  These include ways to adjust the appearance as well as the behavior of the mouse and keyboard.  The specific methods available depend on which operating system you are using.  Application notes are available describing the specific methods available for each operating system.

For information relating to Windows 3.0 see Application Note GA0000.  For information relating to Windows 3.1 or Windows for Workgroups 3.1 see Application Note GA0000.  For information relating to Windows NT 3.1 see Application Note GA0000.  For information on obtaining application notes see Access Pack for Microsoft Windows.


Getting More Information

For more information on Microsoft products and services for people with disabilities, contact Microsoft Customer Sales and Service at (800) 426-9400 (voice) or (206) 635-4948 (text telephone).

The Trace R&D Center at the University of Wisconsin--Madison produces a book and a compact disc that describe products that help people with disabilities use computers. The book, titled Trace ResourceBook, provides descriptions and photographs of about 2,000 products. The compact disc, titled Co-Net CD,provides a database of more than 17,000 products and other information for people with disabilities. It is issued twice a year and should be available in many public libraries by early 1993.

You can contact the Trace R&D Center by using the following address or telephone numbers:

Trace R&D Center
S-151 Waisman Center
1500 Highland Avenue
Madison, WI 537052280

Voice telephone:	(608) 2632309
Text telephone:	(608) 2635408
Fax: (608) 262-8838

For general information and recommendations on how computers can help specific individuals, you should consult a trained evaluator who can best match the individual's needs with the available solutions.

If you are in the United States, you can obtain information about resources in your area by calling the National Information System, an information and referral center for people with disabilities, at the following address:

National Information System (NIS)
Center for Developmental Disabilities
University of South Carolina, Benson Bldg.
Columbia, SC 29208

Phone:	(800) 922-9234 (voice/text telephone outside South Carolina)
(800) 922-1107 (voice/text telephone in South Carolina)

Fax:	(800) 777-6058

This service is available only in the English language.


ANSI Character Set

Characters 128 - 255

 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

* *	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, may affect the visual display of text.

These characters aren't supported by Microsoft Windows.


ANSI Character Set
ANSI Character Set (128 - 255)

Characters 0 - 127

 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 aren't supported by Microsoft Windows.


Conversion Functions

Asc Function

CCur Function

CDbl Function

CInt Function

CLng Function

CSng Function

CStr Function

CVar Function

CVDate Function

Format, Format$ Function

Str, Str$ Function

Val Function


Asc Function

See Also	Example

Returns a numeric value that is the ANSI code for the first character in a string expression.

Syntax

Asc(stringexpression)

Remarks

If the stringexpression argument is a zero-length String or a Null Variant (VarType 1), a run-time error will occur.


See Also

ANSI Character Set

Chr, Chr$ Function


Asc Function Example

The example uses the Asc function to return the numeric equivalent of a range of characters.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, Msg	' Declare variables.

For I = Asc("A") To Asc("Z")	' From A through Z.

Msg = Msg & Chr(I)	' Create a string.

Next I

MsgBox Msg	' Display results.

End Sub


CVDate Function

See Also	Example

Converts an expression to a Variant of VarType 7 (Date).

Syntax

CVDate(expression)

Remarks

The argument expression must be a string expression or a numeric expression that can be interpreted as a date.  The acceptable range for date information is January 1, 100 A.D. (-657434) through December 31, 9999 A.D. (2958465).

The following table identifies the action that occurs as a result of evaluating expression.

If expression is this type	CVDate takes this action
A numeric expression	Checks range. if not in range, generates a run time error; otherwise converts expression to a date.
A string expression that looks like a date, for example,  "1 May 1992 12:00 PM"	Converts expression to a date.
A string expression that looks like a number, for example, "33664"	Converts expression to a number. Checks range.  If not in range, generates a run-time error; otherwise converts expression to a date.
Any other string expression	Generates a run-time error.
For string expressions, CVDate recognizes date formats that can be set in the International section of the WIN.INI file using the Microsoft Windows Control Panel.  However, CVDate cannot recognize a long date format if it also contains the day-of-the-week string.

If a string expression contains only numbers, CVDate may not be able to determine the correct order of day, month, and year if it is provided in a format other than one of the current WIN.INI date settings.

Note	You may be able to use the IsDate function to determine if either a numeric expression or a string expression that looks like a date can actually be converted to a date.  However, IsDate cannot determine if a string that looks like a number can be converted to a date.

Note	When converting from a number to a date, Visual Basic converts any fractional part of the number to a time of day, starting at midnight.


See Also

Data Type Conversion Functions

IsDate Function


CVDate Function Example

The example returns a Variant of VarType 7 containing the date serial for your birth date.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim BirthDate, Msg, TestDate	' Declare variables.

Msg = "Enter your birth date using any form you like."

Do

TestDate = InputBox(Msg)	' Get user date.

Loop Until IsDate(TestDate)	' Test for valid date.

BirthDate = CVDate(TestDate)	' Make Variant.

Msg = "The short form of your birth date is " & BirthDate

MsgBox Msg	' Display message.

End Sub


Data Type Conversion Functions

See Also	Example

Explicitly converts expressions from one data type to another.

Syntax

CCur(expression)

CDbl(expression)

CInt(expression)

CLng(expression)

CSng(expression)

CStr(expression)

CVar(expression)

Remarks

The argument expression can be any valid string expression or numeric expression.

The following table shows which data type is returned by each data type conversion function.

Function 	From 	To

CCur	Any valid expression	Currency

CDbl	Any valid expression	Double

CInt	Any valid expression	Integer

CLng	Any valid expression	Long

CSng	Any valid expression	Single

CStr	Any valid expression	String

CVar	Any valid expression	Variant

The numeric conversion functions CCur, CDbl, CInt, CLng, and CSng explicitly control the data type of a numeric expression.  For example, you can use CCur to force currency arithmetic (which has greater precision but less range) in cases in which integer, double-precision, or single-precision arithmetic normally would occur.  CInt and CLng force integer arithmetic in cases in which currency, single-precision, or double-precision arithmetic normally would occur.  CDbl and CSng force double-precision or single-precision arithmetic in cases in which currency or integer arithmetic normally would occur.

Tip	Use these data type conversion functions to document your code to show that the result of a calculation should be expressed as a particular data type rather than the normal data type of the result.

For the CCur, CInt, CLng, and CSng functions, if expression lies outside the acceptable range, an Overflow error occurs and a message is displayed unless it is trapped in error-handling code.

Note	CInt differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number.  When the fractional part is exactly 0.5, the CInt function always rounds it to the nearest even number.  For example, 0.5 rounds to 0, and 1.5 rounds to 2.


See Also

Visual Basic Data Types

Int Function, Fix Function


Data Type Conversion Function Examples

CCur Function Example

CDbl Function Example

CInt Function Example

CLng Function Example

CSng Function Example

CStr Function Example

CVar Function Example


CCur Function Example

CCur converts a value calculated as a Double to a Currency with four decimal digits of precision to the right of the decimal place, displaying the result in conventional currency value format with two places to the right of the decimal.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Amount, Msg, Percent, SalesTax	' Declare variables.

Percent = 8.2	' Set tax percentage rate.

Msg = "What is the taxable currency amount?"

Amount = InputBox(Msg)	' Get user input.

SalesTax = CCur(Amount * (Percent * .01))	' Calculate tax.

Msg = "Tax on " & Format(Amount, "Currency")

Msg = Msg & " is " & Format(SalesTax, "Currency")

MsgBox Msg	' Display results.

End Sub


CDbl Function Example

The CDbl function converts a Currency value to a Double.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim CurrVal, CurrPercent, Msg, Percent	' Declare variables.

Percent = 8.2	' Set tax rate.

Msg = "Enter a currency value."

CurrVal = CCur(InputBox(Msg))	' Get user input.

CurrPercent = CDbl(CurrVal * Percent * .01)	' Calculate value.

Msg = Percent & "% of "

Msg = Msg & Format(CurrVal, "Currency")

Msg = Msg & " is $" & CurrPercent

Msg = Msg & " expressed as a double-precision number."

MsgBox Msg	' Display results.

End Sub


CInt Function Example

The example converts an angle in radians to an angle in degrees and minutes.  The CInt function is used to convert a double-precision value to an integer value.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Degs, Mins, Pi, Msg	' Declare variables.

Dim Rads, Rads2Degs, WholeDegs, WholeMins

Pi = 4 * Atn(1)	' Calculate Pi.

Rads2Degs = 180 / Pi	' Calculate conversion factor.

Msg = "Please enter an angle in radians."

Rads = InputBox(Msg)	' Get angle in radians.

Degs = Rads * Rads2Degs	' Convert radians to degrees.

Mins = Degs - Int(Degs)	' Get fractional part.

WholeMins = CInt(Mins * 60)	' Convert to between 0 and 60.

WholeDegs = Int(Degs)	' Get whole number part.

If WholeMins = 60 Then	' 60 minutes = 1 degree.

WholeDegs = WholeDegs + 1

WholeMins = 0

End If

Msg = "Angle = " & WholeDegs & " degrees, "

Msg = Msg & WholeMins & " minutes."

MsgBox Msg	' Display results.

End Sub


CLng Function Example

The example uses the CLng function to convert double-precision numbers to long integers.  It also demonstrates how CLng rounds numbers when converting.  Note that 25427.45 is rounded down to 25427, whereas 25427.55 is rounded up to 25428.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

NL = Chr(13) & Chr(10)	' Define newline.

Msg = "25427.45 rounds to " & CLng(25427.45) & "."

Msg = Msg & NL & "25427.55 rounds to "

Msg = Msg & CLng(25427.55) & "."

MsgBox Msg	' Display results.

End Sub


CSng Function Example

The example uses the CSng function to convert double-precision numbers to single-precision.  It also demonstrates how CSng rounds numbers when converting.  Note that 75.3421115 is rounded down to 75.34211, whereas 75.3421155 is rounded up to 75.34212.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL	' Declare variables.

NL = Chr(13) & Chr(10)	' Define newline.

Msg = "75.3421115 rounds to " & CSng(75.3421115)

Msg = Msg & "." & NL & "75.3421555 rounds to "

Msg = Msg & CSng(75.3421555) & "."

MsgBox Msg	' Display results.

End Sub


CStr Function Example

The example uses the CStr function to convert a Double to a String.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NumVal, StrVal	' Declare variables.

Msg = "Enter some numeric value."

NumVal = InputBox(Msg)	' Get user input.

StrVal = CStr(NumVal)	' Perform conversion.

Msg = "StrVal is a Variant containing a number that has "

Msg = Msg & "been converted to a String."

MsgBox Msg	' Display message.

End Sub


CVar Function Example

CVar takes a String value expressed in thousands, concatenates three zeros, and converts the entire expression to a Variant.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, SalesInK, TotalUnits	' Declare variables.

SalesInK = InputBox("How many thousand units did you sell?")

TotalUnits = CVar(SalesInK & "000")

Msg = "You sold " & Format(TotalUnits, "###,###") & " units."

MsgBox Msg	' Display message.

End Sub


Val Function

See Also	Example

Returns the numeric value of a string of characters.

Syntax

Val(stringexpression)

Remarks

The argument stringexpression is a sequence of characters that can be interpreted as a numeric value.  The Val function stops reading the string at the first character that it cannot recognize as part of a number.  Val also strips blanks, tabs, and line feeds from the argument string.  For example, the following returns the value 1615198:

Val("    1615 198th Street N.E.")

Symbols and characters often considered part of a numeric value, such as the dollar sign and commas, are not recognized by Val as numeric.  The Val function does recognize the radix prefixes &O (for octal) and &H (for hexadecimal).  In the code below, Val returns the decimal value -1 for the hexadecimal value shown:

Val("&HFFFF")

The Val function always returns a Double.  If the result of the Val function is assigned to a variable, the Double returned by Val is forced into the data type of the variable.

Tip	If the string expression you want to convert to numbers contains only numbers, consider using one of the numeric data type conversion functions (CCur, CDbl, CInt, CLng, CSng, or CVar) to perform the conversion.  To convert a numeric value to a String or Variant, you can use the Format, CStr, or CVar function.

Note	The usefulness of the Val function is all but eliminated if you use the Variant data type for your variables.  This is because conversion back and forth between strings and numbers is accomplished automatically.


See Also

Data Type Conversion Functions

Format, Format$ Function

Str, Str$ Function


Val Function Example

The example uses the Val function to determine if the first characters in a string are a number.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variables.

Dim Number As Double

Number = Val(InputBox$("Enter a number"))	' Get user input.

Msg = "The number you entered is:" & Number

MsgBox Msg	' Display message.

End Sub


Call Statement

See Also	Example

Transfers program control to a Visual Basic Sub procedure or a dynamic-link library (DLL) procedure.

Syntax 1

Call name [(argumentlist)]

Syntax 2

name [argumentlist]

Remarks

The Call statement has these parts:

Part	Description

Call	Optional keyword used to transfer program control to another procedure.

name 	Name of the procedure to call.

argumentlist	Variables, arrays, or expressions to pass to the procedure.

You are never required to use the Call keyword when calling a procedure.  If you use the Call keyword to call a procedure that requires arguments, the argument list must be enclosed in parentheses.  If you omit the Call keyword, you also must omit the parentheses around the argument list.

You can pass arguments to a procedure by reference or by value.  Values of arguments passed by reference can be altered by the procedure when the arguments are returned; Visual Basic supplies the actual address of the argument.  Arguments passed by value are assigned a temporary address and the values cannot be altered.  Arguments are passed by reference unless enclosed by parentheses or declared using the ByVal keyword.

When passing arguments to DLL procedures, you may want to pass arguments by value.  Many DLL routines don't support all Visual Basic data types and ByVal will attempt a conversion.  You can also use the ByVal reserved word when you declare the DLL procedure in the Declarations section.  The ByVal reserved word cannot be used with a variable of a user-defined type, an object type, or a variable that is an array.

To pass a whole array, use the array name followed by empty parentheses.


See Also

Declare Statement


Call Statement Example

The example shows two ways to call the MessageBeep procedure in USER.EXE, a Microsoft Windows DLL.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Declare Sub MessageBeep Lib "User" (ByVal N As Integer)

Sub Form_Click ()

Dim I	' Declare variable.

Call MessageBeep(0)	' Call Windows procedure.

For I = 1 To 100 : Next I	' Insert short delay between calls.

MessageBeep 0	' Call again without Call keyword.

End Sub


DoEvents Function, DoEvents Statement

Example

Causes Visual Basic to yield execution so that Microsoft Windows can process events.

Function Syntax

DoEvents( )

Statement Syntax

DoEvents

Remarks

The DoEvents function returns the number of visible forms.

DoEvents passes control to the Windows environment.  Control is not returned until the Windows environment has finished processing the events in its queue and all keys in the SendKeys queue have been sent.

Use DoEvents to interrupt processing so the Windows environment can respond normally to other events, such as keyboard input and mouse clicks.  If parts of your code take up too much processor time, use DoEvents to relinquish control to the Windows environment.

Caution	Make sure the procedure that has given up control with DoEvents is not executed again by a different part of your program before the first DoEvents call returns; this could cause unpredictable results.  In addition, do not use DoEvents if other applications could possibly interact with your procedure in unforeseen ways during the time you have yielded control.


DoEvents Statement Example

In this example, DoEvents yields to the Windows environment only in the second loop, allowing keystrokes every 1000 loops.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, Msg, N	' Declare variables.

MsgBox "Choose OK, then try pressing a key."

For I = 1 To 15000	' Start first loop.

N = Int(5000 * Rnd + 1)	' Generate random number.

Next I	' Increment loop counter.

Msg = "Note that any keys you pressed weren't processed"

Msg = Msg & " until the 1st loop was finished. Now choose OK"

Msg = Msg & " and try again."

MsgBox Msg	' Display message.

For I = 1 To 15000	' Start second loop.

N = Int(5000 * Rnd + 1)	' Generate random number.

If I Mod 1000 = 0 Then DoEvents	' Yield to other events.

Next I	' Increment loop counter.

Msg = "During the second loop, your keystrokes were processed"

Msg = Msg & " each time the count was evenly divisible by 1000."

Msg = Msg & " improving the response but degrading the performance."

MsgBox Msg	' Display message.

End Sub


Do...Loop Statement

See Also	Example

Repeats a block of statements while a condition is true or until a condition becomes true.

Syntax 1

Do [{While | Until} condition]

[statementblock]

[Exit Do]

[statementblock]

Loop

Syntax 2

Do

[statementblock]

[Exit Do]

[statementblock]

Loop [{While | Until} condition]

Remarks

The Do...Loop statement has these parts:

Part	Description

Do 	Must be the first statement in a Do...Loop control structure.

While	Indicates that the loop is executed while condition is true.

Until	Indicates that the loop is executed until condition is true.

condition	Numeric or string expression that evaluates true (nonzero) or false (0 or Null).

statementblock	Program lines between the Do and Loop statements that are repeated while or until condition is true.

Exit Do	Only used within a Do...Loop control structure to provide an alternate way to exit a Do...Loop.  Any number of Exit Do statements may be placed anywhere in the Do...Loop.  Often used with the evaluation of some condition (for example, If...Then), Exit Do transfers control to the statement immediately following the Loop.

Loop	Ends a Do...Loop.

When Do...Loop statements are nested, control is transferred to the Do...Loop that is one nested level above the loop in which the Exit Do occurs.


See Also

Exit Statement

While...Wend Statement


Do...Loop Statement Example

The example creates an infinite Do...Loop that can be exited only if the user enters a number in a range.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Reply	' Declare variable.

Do

Reply = InputBox("Enter a number greater than 1 and less than 9.")

If Reply > 1 And Reply < 9 Then	' Check range.

Exit Do	' Exit Do Loop.

End If

Loop

End Sub

Alternatively, the same thing can be accomplished by incorporating the range test in the Do...Loop as follows:

Sub Form_Click ()

Dim Reply	' Declare variable.

Do

Reply = InputBox("Enter a number greater than 1 and less than 9.")

Loop Until Reply > 1 And Reply < 9

End Sub


End Statement

See Also	Example

Ends a Visual Basic procedure or block.

Syntax

End [{Function | If | Select | Sub | Type}]

Remarks

You can use the End statement in any of the following ways:

Statement	Description

End Function	Ends a Function procedure definition.  You must use End Function with Function.  Automatically added when you create a new Function procedure.

End If	Ends a block If...Then statement.  Required to end a block
If...Then...Else.

End Select	Required to end a Select Case block.

End Sub	Required to end a Sub procedure.  Automatically added when you create a new Sub procedure.

End Type	Required to end a user-defined type definition (Type statement).

End	By itself, terminates program execution.  Equivalent to choosing End from the  Run menu.  Never required and may be placed anywhere in a procedure.

While the End statement is never required to terminate program execution, it is generally accepted as good programming practice since it closes files, destroys forms, and clears the value of all variables.

The End statement does not trigger either the QueryUnload or the Unload event.


See Also

Exit Statement

Function Statement

If...Then...Else Statement

Select Case Statement

Stop Statement

Sub Statement

Type Statement


End Statement Example

The example uses End to end code execution, to end a Select Case block, and to end a Sub procedure.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim UserInput	' Declare variable.

Do	' Set up infinite loop.

UserInput = UCase(InputBox("Enter A or X to end program."))

Select Case UserInput	' Evaluate input.

Case "A" : MsgBox "You entered 'A'."

Case "X" : End	' End execution if user entered X.

Case Else : MsgBox "You made an invalid choice. Try again."

End Select	' End Select Case block.

Loop

End Sub	' End Sub procedure.


Exit Statement

See Also	Example

Exits a Do...Loop, a For...Next loop, a Function procedure, or a Sub procedure.

Syntax

Exit { Do | For | Function | Sub }

Remarks

You can use the Exit statement in any of the following ways:

Statement	Description

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 in which it occurs.

Exit For	Provides a way to exit a For...Next loop.  It can be used only in a For...Next loop.  Exit For transfers control to the statement following the Next statement.  When used within nested For...Next loops, Exit For transfers control to the loop that is one nested level above the loop in which it occurs.

Exit Function	Immediately exits the Function procedure in which it appears.  Program execution continues with the statement following the statement that has called the Function.

Exit Sub	Immediately exits the Sub procedure in which it appears.  Program execution continues with the statement following the statement that has called the Sub.

Do not confuse Exit statements with End statements.  Exit does not define the end of a structure.


See Also

Do...Loop Statement

End Statement

For...Next Statement

Function Statement

Stop Statement

Sub Statement


Exit Statement Example

The example uses the Exit statement to exit a For...Next loop, a Do...Loop, and a Sub procedure.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, Num	' Declare variables.

Do	' Set up infinite loop.

For I = 1 To 1000

Num = Int(Rnd * 100)	' Generate random numbers.

Select Case Num	' 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...Next Statement

See Also	Example

Repeats a group of instructions a specified number of times.

Syntax

For counter = start To end [ Step increment ]

[statementblock]

[Exit For]

[statementblock]

Next [counter [, counter][, ...]]

Remarks

The For...Next statement has these parts:

Part	Description

For	Begins a For...Next loop control structure.  Must appear before any other part of the structure.

counter	Numeric variable used as the loop counter.  The variable cannot be an array element or a record element.

start	Initial value of counter.

To	Separates start and end values.

end	Final value of counter.

Step	Indicates that increment is explicitly stated.

increment	Amount counter is changed each time through the loop.  If you do not specify Step, increment defaults to one.

statementblock	Program lines between For and Next that are executed the specified number of times.

Exit For	Only used within a For...Next control structure to provide an alternate way to exit.  Any number of Exit For statements may be placed anywhere in the For...Next loop.  Often used with the evaluation of some condition (for example, If...Then), Exit For transfers control to the statement immediately following the Next

Next	Ends a For...Next loop.  Causes increment to be added to counter.

The Step value controls loop execution as follows:

When step is	Loop executes if

Positive or 0	counter <= end

Negative	counter >= end

Once the loop has been entered and all the 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 in the first place), 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 the program more difficult to read and debug.

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

A Next statement with the form Next K, J, I is equivalent to the following sequence of statements:

Next K

Next J

Next I

Note	If you omit the variable in a Next statement,  the value of Step increment is added to the variable associated with the most recent For statement.  If a Next statement is encountered before its corresponding For statement, an error occurs.


See Also

Do...Loop Statement

Exit Statement

While...Wend Statement


For...Next Statement Example

The example puts five lines of the uppercase alphabet into a message box using two nested loops.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, Msg, NL, Rep	' Declare variables.

NL = Chr(13) & Chr(10)	' Define newline.

For Rep = 5 To 1 Step -1	' Set up five repetitions.

For I = Asc("A") To Asc("Z")	' Convert alpha to numbers.

Msg = Msg & Chr(I)	' Append each letter to string.

Next I

Msg = Msg & NL	' Add newline for each rep.

Next Rep

MsgBox Msg	' Display message box.

End Sub


GoSub...Return Statement

See Also	Example

Branch to, and return from, a subroutine within a procedure.

Syntax

 GoSub {linelabel | linenumber}
. . .

linelabel: or linenumber
. . .

Return

Remarks

The GoSub...Return statement has these parts:

Part	Description

GoSub	Causes program flow to branch to a subroutine within a procedure.

linelabel	Label that marks the first line of the subroutine.  The linelabel must begin with an alphabetic character, must end with a colon, must be 40 characters or less, and must not be a Visual Basic keyword.  Each linelabel must be unique in the module in which it is used.  Line labels are not case-sensitive and may begin in any column as long as they are the first nonblank characters on the line.

linenumber	Line number that marks the first line of the subroutine.  The linenumber can be any number of 40 characters or less, can contain only decimal digits (0-9), and must not end with a colon.  Each linenumber must be unique in the module in which it appears.  Line numbers may begin in any column as long as they are the first nonblank characters.  If linenumber is greater than 65,529, the Erl function cannot properly report the line number where an error has occurred.

Return	Causes program flow to return to the statement following the GoSub statement.  For every GoSub statement there must be an associated Return.

GoSub and Return can be used anywhere in a procedure, but the GoSub and corresponding Return must occur within the same procedure.  A subroutine can contain more than one Return statement, but the first Return statement encountered causes program flow to branch back to the statement immediately following the most recently executed GoSub statement.

Note	You cannot enter or exit Sub procedures with GoSub...Return.

Caution	Subroutines that call themselves (recursive subroutines) can easily run out of stack space and halt your program unexpectedly.


See Also

End Statement

GoTo Statement

On...GoSub Statement, On...GoTo Statement

Sub Statement


GoSub...Return Statement Example

The example uses GoSub to call a subroutine from within a Sub procedure.  Notice that the GoTo branch avoids the subroutine.  This kind of branching is generally considered to be poor programming technique.  To avoid this kind of branching, turn subroutines into Sub procedures.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Num	' Declare variable.

Num = InputBox("Type a number.")

GoSub Routine	' Branch to subroutine.

GoTo Nextpart	' Branch around subroutine.

Routine:	' Start of subroutine.

Num = Num / 2

Return	' Return from subroutine.

Nextpart:	' Continuation of program.

Msgbox "Half of your number is " & Num

End Sub


GoTo Statement

See Also	Example

Branches unconditionally to a specified line within a procedure.

Syntax

GoTo { linelabel | linenumber}

Remarks

The GoTo statement has these parts:

Part	Description

GoTo	Causes program execution to continue at another place within a procedure.

linelabel	Label that marks the line to execute next.  The linelabel must begin with an alphabetic character, must end with a colon, must be 40 characters or less, and must not be a Visual Basic keyword.  Each linelabel must be unique in the module in which it is used.  Line labels are not case-sensitive and may begin in any column as long as they are the first nonblank characters on the line.

linenumber	Line number that marks the line to execute next.  The linenumber can be any number of 40 characters or less, can contain only decimal digits (0-9), and must not end with a colon.  Each linenumber must be unique in the module in which it appears.  Line numbers may begin in any column as long as they are the first nonblank characters.  If linenumber is greater than 65,529, the Erl function cannot properly report the line number where an error has occurred.

GoTo can branch only to lines within the procedure where it appears.

Note	Programs with many GoTo statements can be difficult to read and debug.  Use structured control statements (Do...Loop, For...Next, If...Then...Else, Select Case) whenever possible.


See Also

Do...Loop Statement

For...Next Statement

GoSub...Return Statement

If...Then...Else Statement

Select Case Statement


GoTo Statement Example

The example uses GoTo to branch around a subroutine.  This kind of branching is generally considered to be poor programming technique.  To avoid this kind of branching, turn subroutines into Sub procedures.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Num	' Declare variable.

Num = InputBox("Type a number.")

GoSub Routine	' Branch to subroutine.

GoTo Nextpart	' Branch around subroutine.

Routine:	' Start of subroutine.

Num = Num / 2

Return	' Return from subroutine.

Nextpart:	' Continuation of program.

Msgbox "Half of your number is " & Num

End Sub


If...Then...Else Statement

See Also	Example

Allows conditional execution, based on the evaluation of an expression.

Syntax 1

If condition Then thenpart  [Else elsepart]

Syntax 2

If condition1  Then
[statementblock-1]
[ElseIf condition2 Then
[statementblock-2] ]
[Else
[statementblock-n] ]
End If

Remarks

Syntax 1

The single-line form is often useful for short, simple conditional tests.  Syntax 1 has these parts:

Part	Description

If	Begins the simple If...Then control structure.

condition	One of two types of expressions:

A numeric or string expression that evaluates true (nonzero) or false (0 and Null).

A single expression of the form TypeOf object Is objecttype.  The object is a form or control variable and objecttype is any one of the recognized Visual Basic object types.

Then	Identifies actions to be taken if condition is satisfied.

thenpart	Statements or branches performed when condition is true or if object is of the type specified by objecttype.

Else	Identifies actions taken if condition is not satisfied.  If the Else clause is not present, control passes to the next statement in the program.

elsepart	Statements or branches performed when condition is false or object is not of the specified objecttype.

The thenpart and the elsepart fields both have this syntax:

{statements | [GoTo] linenumber | GoTo linelabel }

The thenpart and elsepart syntax has these parts:

Part	Description

statements	One or more Visual Basic statements, separated by colons.

GoTo	Keyword that is optional with a line number but required with a line label.

linenumber	A valid program line number.

linelabel	A valid program line label.

Note	You can have multiple statements with a condition, but they 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

Syntax 2

The block form of If...Then...Else provides more structure and flexibility than the single-line form and is usually easier to read, maintain, and debug.  Syntax 2 has these parts:

Part	Description

If	Keyword that begins the block If...Then decision control structure.

condition1	Same as condition used in the single-line form shown above.

Then	Keyword used to identify the actions to be taken if a condition is satisfied.

statementblock-1	One or more Visual Basic statements executed if condition1 is true or if object is of the type specified by objecttype.

ElseIf	Keyword indicating that alternative conditions must be evaluated if condition1 is not satisfied.

condition2	Same as condition used in the single-line form shown above.

statementblock-2	One or more Visual Basic statements executed if condition2 is true or if object is of the type specified by objecttype.

Else	Keyword used to identify the actions taken if none of the previous conditions are satisfied.

statementblock-n	One or more Visual Basic statements executed if condition1 and condition2 are both false or if object is not of the type specified by objecttype

End If	Keyword that ends the block form of the If...Then.

In executing a block If, Visual Basic tests condition1, the first numeric expression or TypeOf expression.  If the expression is true or if object is of the type specified by objecttype, the statements following Then are executed.

If the first expression is false or if object is not of the type specified by objecttype, Visual Basic begins evaluating each ElseIf condition in turn.  When Visual Basic finds a true condition or an object that is of the type specified by objecttype, the statements immediately following the associated Then are executed.  If none of the ElseIf conditions is true or no object is of the type specified in its associated objecttype, the statements following the Else are executed.  After executing the statements following Then or Else, the program continues with the statement following End If.

The Else and ElseIf clauses are both optional.  You can have as many ElseIf clauses as you like in a block If, but none can appear after an Else clause.  Any of the statement blocks can contain nested block If statements.

Visual Basic looks at what appears after the Then keyword to determine whether or not an If statement is a block If.  If anything other than a comment appears after Then, the statement is treated as a single-line If statement.

A block 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 in front of them.  The block If must end with an End If statement.

Standard numeric and string expressions cannot be evaluated in the same conditional expression as expressions that use the form If TypeOf object Is objecttype.  Use a separate ElseIf block for objects.

For example:

If a > 1 And a <= 100 Then

...

ElseIf TypeOf controlVar Is ListBox Then

...

End If

Tip	Select Case may be more useful when evaluating a single expression that has several possible actions.


See Also

Select Case Statement


If...Then...Else Statement Example

The example illustrates the various forms of the If...Then...Else syntax.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim X, Y	' Declare variables.

X = InputBox("Enter a number greater than 0 and less than 1000.")

If X < 10 Then

Y = 1	' 1 digit.

ElseIf X < 100 Then

Y = 2	' 2 digits.

Else

Y = 3	' 3 digits.

End If

If Y > 1 Then Unit = " digits." Else Unit = " digit."

MsgBox "The number you entered has " & Y & Unit

End Sub


On...GoSub, On...GoTo Statements

See Also	Example

Branch to one of several specified lines, depending on the value of an expression.

Syntax 1

On expression GoSub destinationlist

Syntax 2

On expression GoTo destinationlist

Remarks

The On...GoSub, On...GoTo syntax has these parts:

Part	Description

On	Begins the On...GoSub or On...GoTo control structure.

expression	Any numeric expression that evaluates to a value between 0 and 255, inclusive.  (The expression is rounded to an integer value before the On...GoSub or On...GoTo statement is evaluated.)  The value of expression determines which of the lines in destinationlist the program branches to.

GoSub	Causes program flow to branch to a subroutine within a procedure.

GoTo	Causes program execution to continue at another place within a procedure.

destinationlist	List of line numbers and line labels separated by commas..

If the value of expression is less than 1 or greater than the number of items in the list, one of the following results occurs:

Value	Result

Equal to 0	Program control drops to the next statement.

Greater than number of items in list	Program control drops to the next statement.

Negative 	Illegal function call error is generated.

Greater than 255	Illegal function call error is generated.

You can mix line numbers and line labels in the same list.  The number of line labels and line numbers you can use with On...GoSub and On...GoTo is limited only by the number you can physically fit on a single line.

Tip	Select Case provides more structure and a more flexible way to perform multiple branching.


See Also

GoSub...Return Statement

GoTo Statement

Select Case Statement


On...GoSub, On...GoTo Statement Example

The example uses On...GoSub to branch to one of two subroutines depending on user input.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, N	' Declare variables.

N = InputBox("Enter a number greater than 0 and less than 3.")

Msg = "You didn't follow directions."	' Error message.

On N GoSub Chose1, Chose2	' Choose subroutine.

MsgBox Msg	' Display results.

End

Chose1:

Msg = "You chose 1." : Return

Chose2:

Msg = "You chose 2." : Return

End Sub


Select Case Statement

See Also	Example

Executes one of several statement blocks depending on the value of an expression.

Syntax

Select Case testexpression

[Case expressionlist1

[statementblock-1] ]

[Case expressionlist2

[statementblock-2] ]

[Case Else

[statementblock-n] ]

End Select

Remarks

The Select Case syntax has these parts:

Part	Description

Select Case	Begins the Select Case decision control structure.  Must appear before any other part of the Select Case structure.

testexpression	Any numeric or string expression.  If testexpression matches the expressionlist associated with a Case clause, the statementblock following that Case clause is executed up to the next Case clause, or for the final one, up to the End Select.  Control then passes to the statement following End Select.  If testexpression matches more than one Case clause, only the statements following the first match are executed.

Case	Sets apart a group of Visual Basic statements to be executed if an expression in expressionlist matches testexpression.

expressionlist	The expressionlist consists of a comma-delimited list of one or more of the following forms.

expression

expression To expression

Is compare-operator expression

statementblock	Elements statementblock-1 to statementblock-n consist of any number of Visual Basic statements on one or more lines.

Case Else	Keyword indicating the statementblock to be executed if no match is found between the testexpression and an expressionlist in any of the other Case selections.  When there is no Case Else statement and no expression listed in the Case clauses matches testexpression, program execution continues at the statement following End Select.

End Select	Ends the Select Case.  Must appear after all other statements in the Select Case control structure.

The argument expressionlist has these parts:

Part	Description

expression	Any numeric or string expression.  The type of the expression must be compatible with the type of testexpression.  (The type of the expression will be coerced to the same type as testexpression.  For example, if testexpression is an integer, expressionlist can contain a double-precision expression, but it will be coerced to an integer.)

To	Keyword used to specify a range of values. If you use the To keyword to indicate a range of values, the smaller value must precede To.

Is	Keyword used with comparison operators to specify a range of values.  If not provided, it is automatically inserted.

compare-operator	Any valid comparison operator, except Is and Like.

Note	Do not  confuse the Is comparison operator with the Is keyword used in the Select Case statement.  They are not the same.

Although not required, it is a good idea to have a Case Else statement in your Select Case block to handle unforeseen testexpression values.

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

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 alphabetical order, and the current value of TestItem$:

Case "everything", "nuts" To "soup", TestItem$

Select Case statements can be nested.  Each Select Case statement must have a matching End Select statement.


See Also

If...Then...Else Statement

On...GoSub, On...GoTo Statements

Option Compare Statement


Select Case Statement Example

The example uses Select Case to decide what action to take based on user input.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, UserInput	' Declare variables.

Msg = "Please enter a letter or number from 0 through 9."

UserInput = InputBox(Msg)	' Get user input.

If Not IsNumeric(UserInput) Then	' Is it letter or number?

If Len(UserInput) <> 0 Then

Select Case Asc(UserInput)	' If it's a letter.

Case 65 To 90	' Must be uppercase.

Msg = "You entered the uppercase letter '"

Msg = Msg & Chr(Asc(UserInput)) & "'."

Case 97 To 122	' Must be lowercase.

Msg = "You entered the lower-case letter '"

Msg = Msg & Chr(Asc(UserInput)) & "'."

Case Else	' Must be something else.

Msg = "You did not enter a letter or a number."

End Select

End If

Else

Select Case CDbl(UserInput)	' If it's a number.

Case 1, 3, 5, 7, 9	' It's odd.

Msg = UserInput & " is an odd number."

Case 0, 2, 4, 6, 8	' It's even.

Msg = UserInput & " is an even number."

Case Else	' Out of range.

Msg = "You entered a number outside "

Msg = Msg & "the requested range."

End Select

End If

MsgBox Msg	' Display message.

End Sub


Shell Function

Example

Runs an executable program.

Syntax

Shell(commandstring [, windowstyle])

Remarks

The Shell function has these parts:

Part	Description

commandstring	Name of the program to execute and any required arguments or command line switches.  If the program name in commandstring doesn't include a .COM, .EXE, .BAT, or .PIF file extension, .EXE is assumed.

windowstyle	Number corresponding to the style of the window in which the program is to be executed.  If windowstyle is omitted, the program is opened minimized with focus, the same as windowstyle = 2.

The following table identifies the values for windowstyle and the resulting style of window:

Value	Window style

1, 5, 9	Normal with focus.

2	Minimized with focus (default).

3	Maximized with focus.

4, 8	Normal without focus.

6, 7	Minimized without focus.

If the Shell function successfully executes the named program, it returns the instance handle of the started program.  The instance handle is a token identifying the running program.  If the Shell function can't start the named program, an error occurs.

Note	The Shell function runs other programs asynchronously.  That means that you cannot depend on a program started with Shell to be finished executing before the code following the Shell function in your Visual Basic application is executed.


Shell Function Example

The example uses Shell to leave the current application and run the Calculator program included with Microsoft Windows; it then uses the SendKeys statement to send keystrokes to either quit the Calculator or add some numbers, depending on the user's choice.  AppActivate is used to move the focus between Microsoft Visual Basic and the Calculator.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, X, Msg	' Declare variables.

AppActivate "Microsoft Visual Basic"	' Change focus to Visual Basic.

SendKeys "%{ }{Down 3}{Enter}", True	' Minimize Visual Basic.

X = Shell("Calc.exe", 1)	' Shell Calculator.

For I = 1 To 100	' Set up counting loop.

SendKeys I & "{+}", True	' Send keystrokes to Calculator

Next I	' to add each value of I.

SendKeys "=", True	' Get grand total.

AppActivate "Microsoft Visual Basic"	' Return focus to Visual Basic.

Msg = "Choose OK to close the Calculator.

MsgBox Msg	' Display OK prompt.

AppActivate "Calculator"	' Return focus to Calculator.

SendKeys "%{F4}", True	' Alt+F4 to close Calculator.

AppActivate "Microsoft Visual Basic"	' Return focus to Visual Basic.

SendKeys "%{ }{Enter}", True	' Restore Visual Basic to size.

End Sub


Stop Statement

See Also	Example

Suspends execution of the running Visual Basic code.

Syntax

Stop

Remarks

You can place Stop statements anywhere in procedures to suspend program execution.

The Stop statement suspends program execution, but unlike End, doesn't close files or clear variables.  To continue a program suspended by the Stop statement, choose Continue from the Run menu or Single Step from the Debug menu.

Under certain circumstances, you also may be able to restart program execution immediately after the Stop statement by entering a statement in the Debug window.  For example, if the Stop statement occurs in an error handler, you can enter a Resume statement in the Debug window to resume program execution.  If the Stop statement occurs in a subroutine (not a Sub procedure), you can enter a Return statement in the Debug window to continue the program.

If you don't use line numbers or line labels, you can specify which line you want to have executed next by using Set Next Statement from the Debug menu and then choosing Continue or Single Step to begin execution.  If you do use line numbers or line labels, you can continue a suspended program at a specific point by entering a GoTo statement with an appropriate line number or line label in the Debug window.


See Also

End Statement


Stop Statement Example

For each step through this For...Next loop, Stop suspends execution.  To resume program execution, choose Continue from the Run menu.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I	' Declare variable.

For I = 1 To 10	' Start For...Next loop.

Debug.Print I	' Print I to Debug window.

Stop	' Stop each time through.

Next I

End Sub


While...Wend Statement

See Also	Example

Executes a series of statements in a loop as long as a given condition is true.

Syntax

While condition
[statementblock]

Wend

The While...Wend statement has these parts:

Part	Description

While	Begins the While...Wend loop control structure.

condition	Any numeric or string expression that evaluates true (nonzero) or false (0 and Null).  If condition is true, all statements in statementblock are executed until the Wend 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 Wend statement.

statementblock	Any number of Visual Basic statements on one or more lines.

Wend	Ends the While...Wend.

Remarks

While...Wend loops can be nested to any level.  Each Wend matches the most recent While.

Caution	Do not branch into the body of a While...Wend loop without executing the While statement.  Doing so may cause run-time errors or program problems that are difficult to locate.

Tip	The Do...Loop statement provides more structure and a more flexible way to perform looping.


See Also

Do...Loop Statement


While...Wend Statement Example

The example uses While...Wend in a sorting routine.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Const MAX = 5	' Declare constant.

Dim Exchange, I, Msg, NL, Temp	' Declare variables.

Static A(MAX)	' Declare an array.

NL = Chr(13) & Chr(10)	' Define newline.

A(1) = "New York"	' Put data in array in no

A(2) = "Paris"	' particular order so it

A(3) = "Chicago"	' can be sorted.

A(4) = "London"

A(5) = "Berlin"

Exchange = True	' Force 1st pass through array.

While Exchange	' Sort until no elements are

Exchange = False	' exchanged.

' Compare array elements by pairs.  When two are exchanged,

' force another pass by setting exchange to TRUE.

For I = 2 To MAX

If A(I - 1) > A(I) Then

Exchange = True	' Make swap.

Temp = A(I): A(I) = A(I - 1): A(I - 1) = Temp

End If

Next I

Wend

Msg = "Sorted order: " & NL & NL	' Create message that shows

For I = 1 To MAX	' sorted order of array

Msg = Msg & A(I) & NL	' contents.

Next I

MsgBox Msg	' Display message.

End Sub


Visual Basic Data Types

See Also

The following table shows the fundamental data types supported by Visual Basic, and the type-declaration suffix, storage size, and range of each data type.

Data type	Suffix	Storage size	Range
Integer	%	2 bytes	-32,768 to 32,767.
Long (long integer)	&	4 bytes	-2,147,483,648 to 2,147,483,647.
Single (single-precision floating-point)	!	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)	#	8 bytes	-1.79769313486232E308 to  -4.94065645841247E-324 for negative values; 4.94065645841247E-324 to 1.79769313486232E308 for positive values.
Currency (scaled integer)	@	8 bytes	-922,337,203,685,477.5808 to 922,337,203,685,477.5807.
String	$	1 byte per character	0 to approximately 65,500 bytes. (Some storage overhead is required.)
Variant	None	As appropriate	Any numeric value up to the range of a Double or any character text.
User-defined (using Type)	None	Number required by elements	The range of each element is the same as the range of its fundamental data type, listed above.


See Also

Currency Data Type

Double Data Type

Integer Data Type

Long Data Type

Single Data Type

String Data Type

Type Statement

Variant Data Type


Integer Data Type

See Also

Integer variables are stored as 16-bit numbers (2 bytes) ranging in value from -32,768 to 32,767.  The type-declaration character for an Integer is % (ANSI character 37).

In addition to representing numbers in this range, Integers can represent Boolean values (values that can have only one of two states).  For Boolean values, -1 represents true and 0 represents false.  You can also use the Visual Basic reserved words True and False, which return -1 and 0, respectively.

You can also use Integers to represent enumerated values.  An enumerated value can contain a finite set of unique whole numbers, each of which has special meaning in the context in which it is used.  Enumerated values provide a convenient way to select among a known number of choices.


See Also

Long Data Type

Visual Basic Data Types


Long Data Type

See Also

Long (long integer) variables are stored as signed 32-bit numbers (4 bytes) ranging in value from -2,147,483,648 to 2,147,483,647.  The type-declaration character for a Long is & (ANSI character 38).


See Also:

Integer Data Type

Visual Basic Data Types


Single Data Type

See Also

Single (single-precision floating-point) variables are stored as 32-bit numbers (4 bytes) ranging in value from -3.402823E38 to -1.401298E-45 for negative values and from 1.401298E-45 to 3.402823E38 for positive values.  The type-declaration character for a Single is ! (ANSI character 33).

Note	Single-precision floating-point numbers are stored in memory using IEEE 32-bit floating-point format.  Each floating-point value consists of three parts: the sign, the exponent, and the mantissa.  In a single-precision number, the sign takes 1 bit, the exponent takes 8 bits, and the mantissa uses the remaining 23 bits plus an additional implied bit.


See Also

Double Data Type

Visual Basic Data Types


Double Data Type

See Also

Double (double-precision floating-point) variables are stored as 64-bit numbers (8 bytes) ranging in value from -1.79769313486232E308 to -4.94065645841247E-324 for negative values and from 4.94065645841247E-324 to 1.79769313486232E308 for positive values.  The type-declaration character for a Double is # (ANSI character 35).

Note	Double-precision floating-point numbers are stored in memory using IEEE 64-bit floating-point format. Each floating-point value consists of three parts: the sign, the exponent, and the mantissa.  In a double-precision number, the sign takes 1 bit, the exponent takes 11 bits, and the mantissa uses the remaining 52 bits plus an additional implied bit.


See Also

Single Data Type

Visual Basic Data Types


Currency Data Type

See Also

Currency variables are stored as 64-bit numbers (8 bytes) in a two's complement integer format, and are scaled by 10,000 to give a fixed-point number with 15 digits to the left of the decimal point and 4 digits to the right.  This representation provides a range of -922,337,203,685,477.5808 to 922,337,203,685,477.5807.  The type-declaration character for a Currency variable is @ (ANSI character 64).

The Currency data type is useful for calculations involving money and for fixed-point calculations in which accuracy is particularly important.


See Also

Long Data Type

Visual Basic Data Types


String Data Type

See Also

There are two kinds of strings:

Variable-length strings, which can contain up to approximately 65,500 characters.  Because some storage overhead is required, a string can't actually be 64K long.

Fixed-length strings, which contain a declared number of characters (less than 64K).

The type-declaration character for a String is $ (ANSI character 36).  The codes for String characters range from 0 to 255.  String characters used by all applications designed for Microsoft Windows consist of ANSI characters.  The first 128 characters (0-127) correspond to the letters and symbols on a standard U.S. keyboard.  These first 128 characters are the same as those defined by the ASCII character set.  The second 128 characters (128-255) represent special characters, such as letters in international alphabets, accents, currency symbols, and fractions.


See Also

Variant Data Type

Visual Basic Data Types


Variant Data Type

See Also

The Variant data type is the default for Visual Basic [image] the data type that all variables become if they are not explicitly declared as some other type (using statements such as Dim, Global, or Deftype).  The Variant data type has no type-declaration character.

The Variant is a special data type that can contain numeric, string, or date data as well as the special values Empty and Null.  You can determine how the data in a Variant is treated by using the VarType function.  The following table illustrates the return value of the VarType function and the corresponding interpretation of the contents of the Variant:

Return value	Interpretation of Variant
0	Empty (uninitialized)
1	Null (no valid data)
2	Integer
3	Long (long integer)
4	Single (single-precision floating-point)
5	Double (double-precision floating-point)
6	Currency (scaled integer)
7	Date
8	String
Numeric data can be any integer or real number value ranging from -1.797693134862315D308 to -4.94066D-324 for negative values and from 4.94066D-324 to 1.797693134862315D308 for positive values.  Generally, numeric Variant data is maintained in its original fundamental data type within the Variant.  For example, if you assign an Integer to a Variant, subsequent operations treat the Variant as if it were an Integer.  However, if an arithmetic operation is performed on a Variant containing an Integer, a Long, or a Single, and the result exceeds the normal range for the original data type, the result is promoted within the Variant to the next larger data type.  An Integer is promoted to a Long, and a Long and a Single are promoted to a Double.  An Overflow error occurs when Variant variables containing Currency and Double values exceed their respective ranges.

Always use the Variant data type when the data could contain date information, Empty, or a Null.  You can also use the Variant data type in place of any fundamental data type to work with data in a more flexible way.  If the contents of a Variant variable are digits, they may be either the string representation of the digits or their actual value, depending on the context.  For example:

Dim MyVar As Variant

MyVar = 98052

In the example shown above, MyVar contains a numeric representation [image] the actual value 98052.  Arithmetic operators work as expected on Variant variables that contain numeric values or string data that can be interpreted as numbers.  If you use the + operator to add MyVar to another Variant containing a number or to a variable of a numeric data type, the result is an arithmetic sum.  See the information about addition and concatenation operators for complete information on how to use them with Variant data.

The value Empty denotes a Variant variable that hasn't been initialized.  A Variant containing Empty is 0 if it is used in a numeric context and a zero-length string if it is used in a string context.

Don't confuse Empty with Null.  Null indicates that the Variant variable intentionally contains no valid data.


See Also

+ Operator

& Operator

VarType Function

Visual Basic Data Types


Any Data Type

The Any data type is used only to suppress type checking of arguments passed to dynamic-link library (DLL) procedures.


User-Defined Data Type

See Also

Any data type that you define using the Type reserved word.  User-defined data types can contain one or more elements of any fundamental Visual Basic data type.


See Also

Type Statement

Visual Basic Data Types


Date, Date$ Functions

See Also	Example

Returns the current system date.

Syntax

Date[$]

Remarks

Date returns a Variant of VarType 7 (Date) containing a date stored internally as a Double.

Date$ returns a 10-character string of the form mm-dd-yyyy, where mm is the month (01-12), dd is the day (01-31), and yyyy is the year (1980-2099).

The return value of the Date$ function is equivalent to:

Format$(Now,"mm-dd-yyyy")

To set the system date, use the Date[$] statement.


See Also

CVDate Function

Date, Date$ Statements

Format, Format$ Functions

Now Function

Time, Time$ Functions

Time, Time$, Statements


Date, Date$ Functions Example

The example uses the Date function to provide the default date for the input box when prompting the user for a new date. To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Default, Msg, NewDate	' Declare variables.

Msg = "Enter a new date in the form mm-dd-yyyy"

Default = Date	' Current date.

NewDate = InputBox(Msg, "", Default)	' Get user input.

If Len(NewDate) > 0 Then	' Check if valid.

Date = NewDate	' Set date.

Msg = "System date set to "

Msg = Msg & Format(DateValue(NewDate), "dddd, mmmm d, yyyy")

Else

Msg = "You did not enter a valid date."

End If

MsgBox Msg	' Display message.

End Sub


Date, Date$ Statements

See Also	Example

Sets the current system date.

Syntax

Date[$] = expression

Remarks

For the Date statement, expression must be a String formatted as a date or a Variant of VarType 7 (Date) or VarType 8 (String).  If expression is a String (or a Variant of VarType 8) that contains only numbers delimited by valid date separators, Date recognizes the order for month, day, and year according to the Short Date format in the International section of the Windows Control Panel.  Date 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, Date recognizes December 30, 1991; Dec 30, 1991; 30-Dec-1991; and 30 December 91.  If expression is not already a Variant of VarType 7, Date attempts to convert it.  If it can't be converted to a date from January 1, 1980 through December 31, 2099, an error occurs.

For Date$, expression must have one of the following forms, where mm (01-12) and dd (01-31) are the month and day and yy or yyyy (1980-2099) is the year:

mm-dd-yy

mm-dd-yyyy

mm/dd/yy

mm/dd/yyyy

If you use the Date[$] statement to set the date with versions of MS-DOS earlier than 3.3, the change remains in effect only until you change it again or turn off your computer.  Many computers have a battery-powered CMOS RAM that retains date and time information when the computer is turned off.  However, to permanently change the date on computers running earlier versions of MS-DOS, you may have to use your Setup disk or perform some equivalent action.  Refer to the documentation for your particular system.


See Also

Date, Date$ Functions

Time, Time$ Functions

Time, Time$ Statements


Date, Date$ Statements Example

The example uses the Date statement to set the computer system date to a new date entered by the user.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Default, Msg, NewDate	' Declare variables.

Msg = "Enter a new date in the form mm-dd-yyyy"

Default = Date	' Current date.

Newdate = InputBox(Msg, "", Default)	' Get user input.

If Len(Newdate) > 0 Then	' Check if valid.

Date = Newdate	' Set date.

Msg = "System date set to "

Msg = Msg & Format(DateValue(Newdate), "dddd, mmmm d, yyyy")

Else

Msg = "You did not enter a valid date."

End If

MsgBox Msg	' Display message.

End Sub


DateSerial Function

See Also	Example

Returns the date serial for a specific year, month, and day.

Syntax

DateSerial(year,month,day)

Remarks

The DateSerial function has these parts:

Part	Description

year	A number between 100 and 9999, inclusive, or a numeric expression.

month	A number between 1 and 12, inclusive, or a numeric expression.

day	A number between 1 and 31, inclusive, or a numeric expression.

To express a specific date, such as December 31, 1991, the range of numbers for each DateSerial argument should conform to the accepted range of values for the unit.  These values are 1 through 31 for days and 1 through 12 for months.  You also can specify relative dates for each argument by using a numeric expression representing the number of days, months, or years before or after a certain date.  The following example uses expressions instead of absolute date numbers.  The DateSerial function returns a date that is the day before the first day (1 - 1) of two months before August (8 - 2) of 10 years before 1990 (1990 - 10) [image] in other words, May, 31, 1980.

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

For the argument year, values between 0 and 99, inclusive, are interpreted as the years 1900-1999.  For all other year arguments, use the complete four-digit year (for example, 1800).

The DateSerial function returns a Variant of VarType 7 (Date) containing a date that is stored internally as a double-precision number.  This number represents a date from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Negative numbers represent dates prior to December 30, 1899.

If the date specified by the three arguments, either directly or by expression, falls outside the acceptable range of dates, an error occurs.


See Also

DateValue Function

Day Function

Month Function

Now Function

TimeSerial Function

TimeValue Function

Weekday Function

Year Function


DateSerial Function Example

In this example, the DateSerial function returns a Variant (VarType 7) containing a date created from the integer arguments.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, RelVal, UserDate, Verb	' Declare variables.

Dim Flag, DD, MM, YY, WhatDay

Flag = False

Msg = "Enter a date in form mm/dd/yyyy"

Do

UserDate = InputBox(Msg)	' Get user input.

If Len(UserDate) <> 10 Then UserDate = Format(Now, "mm/dd/yyyy")

MM = Left(UserDate, 2)	' Get month number.

If MM >= 1 And MM <= 12 Then Flag = True Else Flag = False

DD = Mid(UserDate, 4, 2)	' Get day number.

If DD >= 1 And DD <= 31 Then Flag = True Else Flag = False

YY = Right(UserDate, 4)	' Get year number.

If YY >= 1753 And YY <= 2078 Then Flag = True Else Flag = False

Loop Until Flag = True

RelVal = DateSerial(YY, MM, DD)	' Get date serial.

Select Case RelVal	' Use correct verb.

Case Is < Int(Now): Verb = " was a "

Case Is > Int(Now): Verb = " will be a "

Case Else: Verb = " is a "

End Select

WhatDay = Format(RelVal, "dddd")	' Determine day.

Msg = UserDate & Verb & WhatDay & "."

MsgBox Msg	' Display message.

End Sub


DateValue Function

See Also	Example

Returns the date represented by a String argument.

Syntax

DateValue(stringexpression)

Remarks

The argument stringexpression is a String representing a date from January 1, 100 through December 31, 9999.

If stringexpression includes only numbers separated by valid date separators, DateValue recognizes the order for month, day, and year according to the Short Date setting in the International section of the Microsoft Windows Control Panel.  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 recognizes December 30, 1991 and Dec 30, 1991.

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

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

The DateValue function returns a Variant of VarType 7 (Date) containing a date that is stored internally as a double-precision number.  This number represents a date from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Negative numbers represent dates prior to December 30, 1899.


See Also

DateSerial Function

Day Function

Month Function

Now Function

TimeSerial Function

TimeValue Function

Weekday Function

Year Function


DateValue Function Example

The example uses the DateValue function to convert the String provided by the user to a Variant of VarType 7 (Date).  The Variant is then used to determine the day of the week for the user-provided date.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, RelVal, UserDate, Verb	' Declare variables.

Dim Flag, DD, MM, YY, WhatDay

Msg = "Enter a date in the form mm/dd/yyyy."

UserDate = InputBox(Msg)	' Get user input.

If Len(UserDate) <> 10 Then 	' Use today's date

UserDate = Format(Now, "mm/dd/yyyy")	' if user didn't

End If	' use right format.

RelVal = DateValue(UserDate)	' Get date serial.

Select Case RelVal	' Use correct verb.

Case Is < Int(Now): Verb = " was a "

Case Is > Int(Now): Verb = " will be a "

Case Else : Verb = " is a "

End Select

WhatDay = Format(RelVal, "dddd")	' Determine day.

MsgBox UserDate & Verb & WhatDay & "."	' Display message.

End Sub


Day Function

See Also	Example

Returns an integer between 1 and 31, inclusive, that represents the day of the month for a date argument.

Syntax

Day(dateexpression)

Remarks

The dateexpression part of the syntax is any numeric expression or string expression that can represent a date and time from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Numbers to the left of the decimal point in dateexpression represent the date; numbers to the right represent the time.  Negative numbers represent dates prior to December 30, 1899.

If dateexpression is Null, this function returns a Null.


See Also

Date, Date$ Functions

Date, Date$ Statements

Hour Function

Minute Function

Month Function

Now Function

Second Function

Weekday Function

Year Function


Day Function Example

The example uses the Day function to determine the day of the month.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim DayNum, DaySuffix	' Declare variables.

DayNum = Day(Now)	' Get the current day number.

Select Case DayNum	' Get the proper suffix

Case 1, 21, 31	' for each number.

DaySuffix = "st"

Case 2, 22

DaySuffix = "nd"

Case 3, 23

DaySuffix = "rd"

Case Else

DaySuffix = "th"

End Select

MsgBox "Today is the " & DayNum & DaySuffix & " day of the month."

End Sub


Hour Function

See Also	Example

Returns an integer between 0 and 23, inclusive, that represents the hour of the day corresponding to the time provided as an argument.

Syntax

Hour(dateexpression)

Remarks

The dateexpression part of the syntax is any numeric expression or string expression that can represent a date and time from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Numbers to the left of the decimal point in dateexpression represent the date; numbers to the right represent the time.  Negative numbers represent dates prior to December 30, 1899.

If dateexpression is Null, this function returns a Null.


See Also

Day Function

Minute Function

Month Function

Now Function

Second Function

Time, Time$ Functions

Time, Time$ Statements

Weekday Function

Year Function


Hour Function Example

In this example, the TimeValue function creates a Variant of VarType 7 (Date) for midnight.  The Hour, Minute, and Second functions determine the hour, minute, and second values so the difference can be calculated.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim HourDiff, MinuteDiff, Msg, SecondDiff	' Declare variables

Dim Instant, Midnight, TotalMinDiff, TotalSecDiff

Midnight = TimeValue("23:59:59")

Instant = Now	' Get current time.

HourDiff = Hour(Midnight) - Hour(Instant)	' Get differences.

MinuteDiff = Minute(Midnight) - Minute(Instant)

SecondDiff = Second(Midnight) - Second(Instant) + 1

If SecondDiff = 60 Then

MinuteDiff = MinuteDiff + 1	' Add 1 to minute.

SecondDiff = 0	' Zero seconds.

End If

If MinuteDiff = 60 Then

HourDiff = HourDiff + 1	' Add 1 to hour.

MinuteDiff = 0	' Zero minutes.

End If

TotalMinDiff = (HourDiff * 60) + MinuteDiff	' Get totals.

TotalSecDiff = (TotalMinDiff * 60) + SecondDiff

Msg = "There are a total of " & Format(TotalSecDiff, "#,##0")

Msg = Msg & " seconds until midnight. That translates to "

Msg = Msg & HourDiff & " hours, " & MinuteDiff

Msg = Msg & " minutes, and " & SecondDiff & " seconds."

MsgBox Msg	' Display message.

End Sub


Minute Function

See Also	Example

Returns an integer between 0 and 59, inclusive, that represents the minute of the hour corresponding to the time provided as an argument.

Syntax

Minute(dateexpression)

Remarks

The argument dateexpression is any numeric expression or string expression that can represent a date and/or time from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Numbers to the left of the decimal point in dateexpression represent the date; numbers to the right represent the time.  Negative numbers represent dates prior to December 30, 1899.

If dateexpression is Null, this function returns a Null.


See Also

Day Function

Hour Function

Month Function

Now Function

Second Function

Time, Time$ Functions

Time, Time$ Statements

Weekday Function

Year Function


Minute Function Example

In this example, the TimeValue function creates a Variant of VarType 7 (Date) for midnight.  The Hour, Minute, and Second functions determine the hour, minute, and second values so the difference can be calculated.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim HourDiff, MinuteDiff, Msg, SecondDiff	' Declare variables

Dim Instant, Midnight, TotalMinDiff, TotalSecDiff

Midnight = TimeValue("23:59:59")

Instant = Now	' Get current time.

HourDiff = Hour(Midnight) - Hour(Instant)	' Get differences.

MinuteDiff = Minute(Midnight) - Minute(Instant)

SecondDiff = Second(Midnight) - Second(Instant) + 1

If SecondDiff = 60 Then

MinuteDiff = MinuteDiff + 1	' Add 1 to minute.

SecondDiff = 0	' Zero seconds.

End If

If MinuteDiff = 60 Then

HourDiff = HourDiff + 1	' Add 1 to hour.

MinuteDiff = 0	' Zero minutes.

End If

TotalMinDiff = (HourDiff * 60) + MinuteDiff	' Get totals.

TotalSecDiff = (TotalMinDiff * 60) + SecondDiff

Msg = "There are a total of " & Format(TotalSecDiff, "#,##0")

Msg = Msg & " seconds until midnight. That translates to "

Msg = Msg & HourDiff & " hours, " & MinuteDiff

Msg = Msg & " minutes, and " & SecondDiff & " seconds."

MsgBox Msg	' Display message.

End Sub


Month Function

See Also	Example

Returns an integer between 1 and 12, inclusive, that represents the month of the year for a date argument.

Syntax

Month(dateexpression)

Remarks

The dateexpression part of the syntax is any numeric expression or string expression that can represent a date and/or time from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Numbers to the left of the decimal point in dateexpression represent the date; numbers to the right represent the time.  Negative numbers represent dates prior to December 30, 1899.

If dateexpression is Null, this function returns a Null.


See Also

Date, Date$ Functions

Date, Date$ Statements

Day Function

Hour Function

Minute Function

Now Function

Second Function

Weekday Function

Year Function


Month Function Example

The example uses the Month function to determine the month of the year.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim MonthNum, MonthSuffix, Msg, Serial	' Declare variables.

Serial = Now	' Get date serial number.

MonthNum = Month(Serial)	' Get current month number.

Select Case MonthNum	' Get proper suffix

Case 1	'  for each number.

MonthSuffix = "st"

Case 2

MonthSuffix = "nd"

Case 3

MonthSuffix = "rd"

Case Else

MonthSuffix = "th"

End Select

Msg = Format(Serial, "mmmm") & " is the " & MonthNum

Msg = Msg & MonthSuffix & " month of the year."

MsgBox Msg	' Display message.

End Sub


Now Function

See Also	Example

Returns a date that represents the current date and time according to the setting of the computer's system date and time.

Syntax

Now

Remarks

The Now function returns a Variant of VarType 7 (Date) containing a date and time that are stored internally as a double-precision number.  This number represents a date and time from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Numbers to the left of the decimal point represent the date; numbers to the right represent the time.

Note	When displayed directly, the Now function's return value is displayed as a string using the short date and time formats set in the Microsoft Windows Control Panel.


See Also

Date, Date$ Functions

Date, Date$ Statements

Day Function

Hour Function

Minute Function

Month Function

Second Function

Time, Time$ Functions

Time, Time$ Statements

Weekday Function

Year Function


Now Function Example

In this example, the Now function returns the current date as a Variant of VarType 7 (Date) containing a date.  The Format function formats the date as a long date including the day and date.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Today	' Declare variable.

Today = Now	' Get current date and time.

MsgBox "Today is " & Format(Today, "dddd, mmmm dd, yyyy") & "."

End Sub


Second Function

See Also	Example

Returns an integer between 0 and 59, inclusive, that represents the second of the minute for a time argument.

Syntax

Second(dateexpression)

Remarks

The argument dateexpression is any numeric expression or string expression that can represent a date and/or time from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Numbers to the left of the decimal point in dateexpression represent the date; numbers to the right represent the time.  Negative numbers represent dates prior to December 30, 1899.

If dateexpression is Null, this function returns a Null.


See Also

Day Function

Hour Function

Minute Function

Month Function

Now Function

Time, Time$ Functions

Time, Time$ Statements

Weekday Function

Year Function


Second Function Example

In this example, the TimeValue function creates a Variant of VarType 7 (Date) for midnight.  The Hour, Minute, and Second functions determine the hour, minute, and second values so the difference can be calculated.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim HourDiff, MinuteDiff, Msg, SecondDiff	' Declare variables

Dim Instant, Midnight, TotalMinDiff, TotalSecDiff

Midnight = TimeValue("23:59:59")

Instant = Now	' Get current time.

HourDiff = Hour(Midnight) - Hour(Instant)	' Get differences.

MinuteDiff = Minute(Midnight) - Minute(Instant)

SecondDiff = Second(Midnight) - Second(Instant) + 1

If SecondDiff = 60 Then

MinuteDiff = MinuteDiff + 1	' Add 1 to minute.

SecondDiff = 0	' Zero seconds.

End If

If MinuteDiff = 60 Then

HourDiff = HourDiff + 1	' Add 1 to hour.

MinuteDiff = 0	' Zero minutes.

End If

TotalMinDiff = (HourDiff * 60) + MinuteDiff	' Get totals.

TotalSecDiff = (TotalMinDiff * 60) + SecondDiff

Msg = "There are a total of " & Format(TotalSecDiff, "#,##0")

Msg = Msg & " seconds until midnight. That translates to "

Msg = Msg & HourDiff & " hours, " & MinuteDiff

Msg = Msg & " minutes, and " & SecondDiff & " seconds."

MsgBox Msg	' Display message.

End Sub


Time, Time$ Functions

See Also	Example

Returns the current system time.

Syntax

Time[$][( )]

Remarks

Time returns a Variant of VarType 7 (Date) containing a time stored internally as the fractional part of a double-precision number.

The Time$ function returns an eight-character string of the form hh:mm:ss, where hh is the hour (00-23), mm is the minute (00-59), and ss is the second (00-59).  A 24-hour clock is used; therefore, 8:00 P.M. appears as 20:00:00.

The output of the Time$ function is equivalent to:

Format$(Now,"hh:mm:ss")

To set the system time, use the Time$ statement.


See Also

Date, Date$ Functions

Date, Date$ Statements

Time, Time$ Statements

Timer Function


Time, Time$ Function Example

The example uses the Time function to provide the default time for the input box when prompting the user for a new time.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NewTime	' Declare variables.

Msg = "Enter a new time in the form hh:mm:ss"

NewTime = InputBox(Msg, "", Time)	' Get user input.

If Len(NewTime) > 0 Then	' Check if valid.

Time = NewTime	' Set time.

Msg = "System time now set to "

Msg = Msg & Time & "."	' Put time in message.

Else

Msg = "You did not enter a valid time."

End If

MsgBox Msg	' Display message.

End Sub


Time, Time$ Statements

See Also	Example

Sets the system time.

Syntax

Time[$] = expression

Remarks

For the Time statement, expression must be a String formatted as a time or a Variant of VarType 7 (Date) or of VarType 8 (String).  If expression is a String (or a Variant of VarType 8), times can be entered using a 12- or 24-hour clock.  For example, "2:24PM" and "14:24" are both valid time arguments.  If expression is not already a Variant containing a valid time, Time attempts to convert it using the time separators specified in the International section of the Windows Control Panel.  If it can't be converted to a valid time, an error occurs.

For Time$, expression must have one of the following forms, where hh is the hour (00-23), mm is the minute (00-59), and ss is the second (00-59):

Form	Description

hh	Sets the hour; the minute and the second default to 00.

hh:mm	Sets the hour and the minute; the second defaults to 00.

hh:mm:ss	Sets the hour, the minute, and the second.

A 24-hour clock is used, so 8:00 P.M. is entered as 20:00:00.

Note	If you use the Time[$] statement to set the time with versions of MS-DOS earlier than 3.3, the change remains in effect only until you change it again or turn off your computer.  Many computers have a battery-powered CMOS RAM that retains date and time information when the computer is turned off.  However, to permanently change the time in the CMOS RAM on computers running earlier versions of MS-DOS, you may have to use your Setup disk or perform some equivalent action.  Refer to the documentation for your particular system.


See Also

Date, Date$ Functions

Date, Date$ Statements

Time, Time$ Functions


Time, Time$ Statements Example

The example uses the Time statement to set the computer system time to a new time entered by the user.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NewTime	' Declare variables.

Msg = "Enter a new time in the form hh:mm:ss"

NewTime = InputBox(Msg, "", Time)	' Get user input.

If Len(NewTime) > 0 Then	' Check if valid.

Time = NewTime	' Set time.

Msg = "System time now set to "

Msg = Msg & Time & "."	' Put time in message.

Else

Msg = "You did not enter a valid time."

End If

MsgBox Msg	' Display message.

End Sub


Timer Function

See Also	Example

Returns the number of seconds that have elapsed since 12:00 A.M. (midnight).

Syntax

Timer

Remarks

The Timer function is automatically used with the Randomize statement to generate a seed for the Rnd (random-number) function.  You can also use it to time programs or parts of programs.


See Also

Randomize Statement


Timer Function Example

The example uses the Timer function to keep track of elapsed time required to find all prime numbers between 1 and 1000.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Const UNMARK = 0, MARKIT = Not UNMARK, MAXNUM = 1000

Static Mark(MAXNUM)	' Set up an array.

Dim Delta, Finish, I, Msg, N, Num, Start	' Declare variables.

Start = Timer	' Set start time.

Num = 0	' Initialize number counter.

For N = 3 To MAXNUM Step 2	' Find all primes.

If Not Mark(N) Then

Delta = 2 * N

For I = 3 * N To MAXNUM Step Delta

Mark(I) = MARKIT

Next I

Num = Num + 1

End If

Next N

Finish = Timer	' Set end time.

Msg = "The program took " & (Finish - Start)

Msg = Msg & " seconds to find "

Msg = Msg & Num & " prime numbers."

MsgBox Msg	' Display message.

End Sub


TimeSerial Function

See Also	Example

Returns the time serial for a specific hour, minute, and second.

Syntax

TimeSerial(hour, minute, second)

Remarks

The TimeSerial function has these parts:

Part	Description

hour	An hour between 0 (12:00 A.M.) and 23 (11:00 P.M.), inclusive, or a numeric expression.

minute	A minute between 0 and 59, inclusive, or a numeric expression.

second	A second between 0 and 59, inclusive, or a numeric expression.

To express a specific time, such as 11:59:59, the range of numbers for each TimeSerial argument should conform to the accepted range of values for the unit.  These values are 0 through 23 for hours and 0 through 59 for minutes and seconds.  You also can specify relative times for each argument by using a numeric expression representing the 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 (0 - 15) six hours before noon (12 - 6), or 5:45:00 A.M.

TimeSerial(12 - 6, 0 - 15, 0)

The TimeSerial function returns a Variant of VarType 7 (Date) containing a time that is stored internally as a double-precision fractional number between 0 and .99999.  This number represents a time between 0:00:00 and 23:59:59, or 12:00:00 A.M.  and 11:59:59 P.M., inclusive.

If the time specified by the three arguments, either directly or by expression, falls outside the acceptable range of times, an error occurs.


See Also

DateSerial Function

DateValue Function

Hour Function

Minute Function

Now Function

Second Function

TimeValue Function


TimeSerial Function Example

In this example, the TimeSerial function creates a time serial from a number of hours, minutes, and seconds.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim HourDiff, MinuteDiff, Msg, SecondDiff	' Declare variables

Dim Instant, Midnight, TotalMinDiff, TotalSecDiff

Midnight = TimeValue("23:59:59")

Instant = Now	' Get current time.

HourDiff = Hour(Midnight) - Hour(Instant)	' Get the differences.

MinuteDiff = Minute(Midnight) - Minute(Instant)

SecondDiff = Second(Midnight) - Second(Instant) + 1

If SecondDiff = 60 Then

MinuteDiff = MinuteDiff + 1	' Add 1 to minute.

SecondDiff = 0	' Zero seconds.

End If

If MinuteDiff = 60 Then

HourDiff = HourDiff + 1	' Add 1 to hour.

MinuteDiff = 0	' Zero minutes.

End If

TotalMinDiff = (HourDiff * 60) + MinuteDiff	' Get totals.

TotalSecDiff = (TotalMinDiff * 60) + SecondDiff

TotalDiff = TimeSerial(HourDiff, MinuteDiff, SecondDiff)

Msg = "There are a total of " & Format(TotalSecDiff, "#,##0")

Msg = Msg & " seconds until midnight.  That translates to "

Msg = Msg & HourDiff & " hours, " & MinuteDiff

Msg = Msg & " minutes, and " & SecondDiff & " seconds."

Msg = Msg & " Expressed in standard time notation, it becomes "

Msg = Msg & Format(TotalDiff, "hh:mm:ss") & "."

MsgBox Msg	' Display message.

End Sub


TimeValue Function

See Also	Example

Returns the time represented by a String argument.

Syntax

TimeValue(stringexpression)

Remarks

The argument stringexpression is a String representing a time from 0:00:00 (12:00:00 A.M.) through 23:59:59 (11:59:59 P.M.).  You can enter valid times using a 12- or 24-hour clock.  For example, "2:24PM" and "14:24" are both valid time arguments.

If stringexpression contains date information, TimeValue doesn't return it.  However, if stringexpression includes invalid date information, an error occurs.

The TimeValue function returns a Variant of VarType 7 (Date) containing a time that is stored internally as a double-precision number between 0 and .99999.  This number represents a time between 0:00:00 and 23:59:59, or 12:00:00 A.M.  and 11:59:59 P.M., inclusive.


See Also

DateSerial Function

DateValue Function

Hour Function

Minute Function

Now Function

Second Function

TimeSerial Function


TimeValue Function Example

In this example, the TimeValue function creates a Variant of VarType 7 (Date) for midnight.  The Hour, Minute, and Second functions determine the hour, minute, and second values so the difference can be calculated.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim HourDiff, MinuteDiff, Msg, SecondDiff	' Declare variables

Dim Instant, Midnight, TotalMinDiff, TotalSecDiff

Midnight = TimeValue("23:59:59")

Instant = Now	' Get current time.

HourDiff = Hour(Midnight) - Hour(Instant)	' Get differences.

MinuteDiff = Minute(Midnight) - Minute(Instant)

SecondDiff = Second(Midnight) - Second(Instant) + 1

If SecondDiff = 60 Then

MinuteDiff = MinuteDiff + 1	' Add 1 to minute.

SecondDiff = 0	' Zero seconds.

End If

If MinuteDiff = 60 Then

HourDiff = HourDiff + 1	' Add 1 to hour.

MinuteDiff = 0	' Zero minutes.

End If

TotalMinDiff = (HourDiff * 60) + MinuteDiff	' Get totals.

TotalSecDiff = (TotalMinDiff * 60) + SecondDiff

Msg = "There are a total of " & Format(TotalSecDiff, "#,##0")

Msg = Msg & " seconds until midnight. That translates to "

Msg = Msg & HourDiff & " hours, " & MinuteDiff

Msg = Msg & " minutes, and " & SecondDiff & " seconds."

MsgBox Msg	' Display message.

End Sub


Weekday Function

See Also	Example

Returns an integer between 1 (Sunday) and 7 (Saturday) that represents the day of the week for a date argument.

Syntax

Weekday(dateexpression)

Remarks

The dateexpression part of the syntax is any numeric expression or string expression that can represent a date and/or time from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Numbers to the left of the decimal point in dateexpression represent the date; numbers to the right represent the time.  Negative numbers represent dates prior to December 30, 1899.

If dateexpression is Null, this function returns a Null.


See Also

Date, Date$ Functions

Date, Date$ Statements

Day Function

Hour Function

Minute Function

Month Function

Now Function

Second Function

Year Function


Weekday Function Example

The example uses Weekday to determine the day of the week.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim DayNum, Msg	' Declare variables.

DayNum = Weekday(Now)	' Get current day of the week.

If DayNum = 1 Or DayNum = 7 Then 	' See if it's a weekend day

Msg = "Today is a weekend day."

Else	' or a weekday.

Msg = "Today is a weekday."

End If

MsgBox Msg	' Display message.

End Sub


Year Function

See Also	Example

Returns an integer between 100 and 9999, inclusive, that represents the year of a date argument.

Syntax

Year(dateexpression)

Remarks

The dateexpression part of the syntax is any numeric expression or string expression that can represent a date and/or time from January 1, 100 through December 31, 9999, where January 1, 1900 is 2.  Numbers to the left of the decimal point in dateexpression represent the date; numbers to the right represent the time.  Negative numbers represent dates prior to December 30, 1899.

If dateexpression is Null, this function returns a Null.


See Also

Date, Date$ Functions

Date, Date$ Statements

Day Function

Hour Function

Minute Function

Month Function

Now Function

Second Function

Weekday Function


Year Function Example

The example uses the Year function to determine whether or not the current year is a leap year.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim CurYear, LeapYear, Msg	' Declare variables.

CurYear = Year(Now)	' Get current year.

If CurYear Mod 4 = 0 And CurYear Mod 100 = 0 Then

If CurYear Mod 400 = 0 Then	' Evenly divisible by 400?

LeapYear = "is a leap year."

Else	' Not evenly divisible.

LeapYear = "is a centesimal year but not a leap year."

End If

ElseIf CurYear Mod 4 = 0 Then

LeapYear = "is a leap year."

Else

LeapYear = "is not a leap year."

End If

MsgBox "The current year, " & CurYear & ", " & LeapYear

End Sub


DDE Methods

LinkExecute Method

LinkPoke Method

LinkRequest Method

LinkSend Method


LinkExecute Method

See Also	Example

Sends a command string to the other application in a dynamic data exchange (DDE) conversation.

Syntax

control.LinkExecute cmdstring

Remarks

The LinkExecute method has these parts:

Part	Description

control	Name of the Visual Basic control involved in a DDE conversation.  The control can be any label, picture box, or text box.

cmdstring	String expression containing a command recognized by the other application.

The actual value of cmdstring will vary depending on the source applications.  For example, Microsoft Excel and Microsoft Word for Windows will accept command strings that consist of their macro commands enclosed by square brackets.  To see what command strings a source application will accept, consult documentation for that application.


See Also

LinkPoke Method

LinkRequest Method

LinkSend Method


LinkExecute Method Example

The example establishes a DDE link with Microsoft Excel, places some values into cells in the first row of a new worksheet, and charts the values.  LinkExecute sends Microsoft Excel the command to activate a worksheet, select some values, and chart them.  To try this example, Microsoft Excel must be installed and in your path.  Paste the code into the Declarations section of a form that has a text box with the default name Text1.  Then press F5 and click the form.

Sub Form_Click ()

Const NONE = 0, LINK_MANUAL = 2	' Declare constants.

Dim Cmd, I, Q, Row, Z	' Declare variables.

Q = Chr(34)	' Define quote marks.

' Create a string containing Excel macro commands:

Cmd = "[ACTIVATE(" & Q &"SHEET1" & Q & ")]"

Cmd = Cmd & "[SELECT(" & Q & "R1C1:R5C2" & Q & ")]"

Cmd = Cmd & "[NEW(2,1)][ARRANGE.ALL()]"

If Text1.LinkMode = NONE Then

Z = Shell("Excel", 4)	' Start Excel.

Text1.LinkTopic = "Excel|Sheet1"	' Set link topic.

Text1.LinkItem = "R1C1"	' Set link item.

Text1.LinkMode = LINK_MANUAL	' Set link mode.

End If

For I = 1 To 5

Row = I	' Define row number.

Text1.LinkItem = "R" & Row & "C1"	' Set link item.

Text1.Text = Chr(64 + I)	' Put value in Text.

Text1.LinkPoke	' Poke value to cell.

Text1.LinkItem = "R" & Row & "C2"	' Set link item.

Text1.Text = Row	' Put value in Text.

Text1.LinkPoke	' Poke value to cell.

Next I

Text1.LinkExecute Cmd	' Execute Excel commands.

End Sub


LinkPoke Method

See Also	Example

Transfers the contents of a control to the source application in a dynamic data exchange (DDE) conversation.

Syntax

control.LinkPoke

Remarks

The control is the name of a text box, picture box, or label involved in a DDE conversation as a destination.  If control is a text box, LinkPoke transfers the current contents of the Text property to the source.  If control is a picture box, LinkPoke transfers the current contents of the Picture property to the source.  If control is a label, LinkPoke transfers the current contents of the Caption property.

Typically, information in a DDE conversation flows from source to destination.  However, LinkPoke allows a destination control to supply data to the source.  Not all source applications will accept information supplied in this way; if the source application does not accept the data, an error occurs.


See Also

LinkExecute Method

LinkRequest Method

LinkSend Method


LinkPoke Method Example

The example establishes a DDE link with Microsoft Excel, places some values into cells in the first row of a new worksheet, and charts the values.  LinkPoke sends the values to be charted to the Microsoft Excel worksheet.  To try this example, Microsoft Excel must be installed and in your path.  Paste the code into the Declarations section of a form that has a text box with the default name Text1.  Then press F5 and click the form.

Sub Form_Click ()

Const NONE = 0, LINK_MANUAL = 2	' Declare constants.

Dim Cmd, I, Q, Row, Z	' Declare variables.

Q = Chr(34)	' Define quote marks.

' Create a string containing Excel macro commands:

Cmd = "[ACTIVATE(" & Q &"SHEET1" & Q & ")]"

Cmd = Cmd & "[SELECT(" & Q & "R1C1:R5C2" & Q & ")]"

Cmd = Cmd & "[NEW(2,1)][ARRANGE.ALL()]"

If Text1.LinkMode = NONE Then

Z = Shell("Excel", 4)	' Start Excel.

Text1.LinkTopic = "Excel|Sheet1"	' Set link topic.

Text1.LinkItem = "R1C1"	' Set link item.

Text1.LinkMode = LINK_MANUAL	' Set link mode.

End If

For I = 1 To 5

Row = I	' Define row number.

Text1.LinkItem = "R" & Row & "C1"	' Set link item.

Text1.Text = Chr(64 + I)	' Put value in Text.

Text1.LinkPoke	' Poke value to cell.

Text1.LinkItem = "R" & Row & "C2"	' Set link item.

Text1.Text = Row	' Put value in Text.

Text1.LinkPoke	' Poke value to cell.

Next I

Text1.LinkExecute Cmd	' Execute Excel commands.

End Sub


LinkRequest Method

See Also	Example

Asks the source in a dynamic data exchange (DDE) conversation to update the contents of a control.

Syntax

control.LinkRequest

Remarks

The control is the name of a text box, picture box, or label involved in a DDE conversation as a destination.  LinkRequest causes the source application to provide fresh data to the control, updating the Text property if the control is a text box, the Picture property if the control is a picture box, or the Caption property if the control is a label.

If the LinkMode property of the control is set to Automatic (1), the source application will automatically update the control and LinkRequest is not needed.  If the LinkMode property of the control is set to Manual (2), the source application will only update the control when  requested to with the LinkRequest method.  If the LinkMode property of the control is set to Notify (3), the source will notify the destination that data has changed by causing the LinkNotify event to occur.  The destination must then use LinkRequest to actually update the data.


See Also

LinkExecute Method

LinkMode Property

LinkNotify Event

LinkPoke Method

LinkSend Method


LinkRequest Method Example

The example uses LinkRequest to update the contents of a text box with the values in a Microsoft Excel worksheet. To try this example, you must have Microsoft Excel running on your computer.  Place some data in the first cells in the first column in the default worksheet (called Sheet1.XLS).  Paste the code shown below into the Declarations section of a form that has a text box control called Text1.  Then press F5 and click the form.

Sub Form_Click ()

Const NONE = 0, LINK_MANUAL = 2	' Declare constants.

If Text1.LinkMode = NONE Then	' Test link mode.

Text1.LinkTopic = "Excel|Sheet1"	' Set link topic.

Text1.LinkItem = "R1C1"	' Set link item.

Text1.LinkMode = LINK_MANUAL	' Set link mode.

Text1.LinkRequest	' Update text box

Else

If Text1.LinkItem  = "R1C1" Then

Text1.LinkItem = "R2C1"

Text1.LinkRequest	' Update text box.

Else

Text1.LinkItem = "R1C1"

Text1.LinkRequest	' Update text box.

End If

End If

End Sub


LinkSend Method

See Also	Example

Transfers the contents of a picture control to the destination application in a dynamic data exchange (DDE) conversation.

Syntax

control.LinkSend

Remarks

The control must be a picture box on a form that is acting as a source in a DDE conversation.

When other applications establish automatic links with a form in your application, Visual Basic notifies them when the contents of text boxes and labels on the form change.  However, Visual Basic does not automatically notify DDE destinations when the Picture property of a picture on a source form changes.  Because the amount of data in a picture can be very large, and because it seldom makes sense to update destinations as each pixel in the picture changes, Visual Basic requires that you use the LinkSend method to explicitly notify DDE destinations when a picture box has changed.


See Also

LinkExecute Method

LinkPoke Method

LinkRequest Method

Picture Property


LinkSend Method Example

The example allows you to draw lines in a picture box and then uses the LinkSend method to update DDE destinations with the new contents of the picture box.  Draw lines by clicking the left mouse button; update DDE destinations by clicking the right mouse button.  To try this example, place a picture box named Picture1 on a form.  Set the LinkMode property for the form to Normal.  Paste the code into the Declarations section of the form and start the Visual Basic example running by pressing F5.  Once you have the example running, start another application that can accept picture data through DDE, such as Microsoft Excel or Microsoft Word for Windows.  Create an automatic link in that other application to the picture control in your application.  For example:

Microsoft Excel 3.0 [image] create a picture and size it so you can see the data when it is sent.  Enter the following formula for the picture into the Excel Formula bar:

=Project1|Form1!Picture1

Microsoft Word for Windows 2.0 [image] insert a field.  Enter the following text into the Field Code text box, replacing the equal sign:

ddeauto project1 form1 picture1

Format the field paragraph so that line spacing is automatic.

In both cases, if the Visual Basic project name is not Project1, you should substitute the appropriate project name in the formulas above.  Likewise, if the LinkTopic property for the form is not Form1, you should substitute the contents of the LinkTopic property for Form1 in the formula above.

Note	You must start the Visual Basic example before you establish the link from the other application.

Sub Picture1_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)

Dim LeftButton, RightButton	' Declare variables.

Picture1.AutoRedraw = True	' Turn on AutoRedraw.

LeftButton = Button And 1	' Define left button.

RightButton = Button And 2	' Define right button.

' Left button draws a line to the point from the previous end point.

' Right button updates DDE destinations with the contents of the picture.

If LeftButton Then

Picture1.Line -(X, Y)	' Draw lines in picture box.

ElseIf RightButton Then	' Update the picture in the

Picture1.LinkSend	' other application.

DoEvents	' Yield to Windows events.

End If

End Sub


Const Statement

See Also	Example

Declares symbolic constants for use in place of values.

Syntax

[Global] Const constantname = expression [, constantname = expression] . . .

Remarks

The Const statement has these parts:

Part	Description

Global	Reserved word that can precede Const in modules to declare constants that can be referred to by all procedures in all forms and modules.

constantname 	Name of the constant.

expression 	Expression assigned to the constant.  It can consist of literals (such as 1.0), other constants, or any of the arithmetic or logical operators except exponentiation (^).  You also can use a single string literal, such as "Error on input".  You cannot use string concatenation, variables, user-defined functions, or intrinsic Visual Basic functions (such as Chr[$])  in expressions assigned to constants.

Tip	Constants can make your programs self-documenting and easier to modify.  Unlike variables, constants can't be inadvertently changed while your program is running.

You can add a type-declaration character to constantname to indicate the data type of the constant, but this character is not part of the name.  For example:

Const MAXDIM% = 250
...
Dim AccountNames$(MAXDIM)

If you don't use a type-declaration character in the name, the constant is given a data type based on the expression in the Const statement.  Strings always yield a String constant, but numeric expressions are evaluated and the constant is given the simplest type that can represent the constant.  Because a constant must be a single predefined type, it can't be a Variant.  By definition, a Variant can appear as different data types depending on context.  Constants are not affected by Deftype statements, such as DefInt.

Caution	Constants must be defined before referring to them.  Put Global constant definitions in a single module to avoid a cross-module dependency that cannot be resolved.

Constants declared in a Sub or a Function procedure are local to that procedure.  A constant declared outside a procedure (in the Declarations section of a module) is defined throughout the module in which it is declared.  Constants declared outside a procedure using the Global reserved word can be used by all procedures in all forms and modules.  You can use constants anywhere you would use an expression.

Note	You cannot use the Global keyword to declare constants in forms, because form constants are available only to procedures within the form where they are declared.

Tip	Use all uppercase letters for constant names to make them easy to recognize in your program listings.


See Also

Deftype Statements

Let Statement


Const Statement Example

The example uses Const to define the symbolic constant PI.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()
Const PI = 3.141592654	' Define constant.

Dim Area, Circum, Msg, Radius	' Declare variables.

Msg = "Enter the radius of a circle in centimeters."

Radius = InputBox(Msg)	' Get user input.

Circum = 2 * PI * Radius	' Calculate circumference.

Area = PI * (Radius ^ 2)	' Calculate area.

Msg = "The circumference of the circle is "

Msg = Msg & Circum & " cm. Its area is "

Msg = Msg & Area & " cm."

MsgBox Msg	' Display message.

End Sub


Declare Statement

See Also	Example

Declares references to external procedures in a dynamic-link library (DLL).

Syntax 1

Declare Sub globalname Lib "libname" [Alias "aliasname" ][([argumentlist])]

Syntax 2

Declare Function globalname Lib libname [Alias aliasname ] [([argumentlist])] [As type]

Remarks

The Declare statement has these parts:

Part	Description

Sub	Indicates that the procedure doesn't return a value.

Function	Indicates that the procedure returns a value and can be used in an expression.

globalname	The name of the Sub or Function procedure called.  Procedure names follow the same rules used for naming other Visual Basic variables.  Function procedure names can include a type-declaration character indicating the data type returned by the procedure.  This name cannot appear as the name of any other procedure.

For Function procedures, the data type of the procedure determines the data type it returns.  If the function name doesn't use a type-declaration character, you can use an As clause following the argumentlist to specify the return type of the function.

Lib	Indicates that a DLL contains the procedure being declared.  The Lib clause is required for all declarations.

libname	String literal that is the name of the DLL that contains the declared procedure.

Alias	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 Visual Basic reserved word. You can also use Alias when a DLL procedure has the same name as a Global variable or constant or any other procedure in the same scope.  Alias is also useful if any characters in the DLL procedure name aren't allowed in Visual Basic names.

aliasname	String literal that identifies the name of the procedure in the DLL.

argumentlist	List of variables representing arguments that are passed to the Sub or Function procedure when it is called.

As type	Declares the data type of the value returned by a Function procedure.  The argument type may be Integer, Long, Single, Double, Currency, String (variable-length only), or Variant.

The argument argumentlist has the following syntax:

[ByVal] variable [ As type] [,[ByVal] variable [ As type] ] . . .

The following list describes the parts of argumentlist.

Part	Description

ByVal	Indicates that the argument is passed by value rather than by reference.  The ByVal reserved word cannot be used with a variable of a user-defined type, an object type, or a variable that is an array.  When ByVal precedes a numeric argument variable, the actual argument is converted to the numeric type indicated in the Declare statement before being passed.  When ByVal precedes a String argument variable, the address of the null-terminated string data is sent to the procedure.  When ByVal is not included, a string descriptor is sent to the called DLL procedure.

variable	A Visual Basic variable name.  If you use a type-declaration character with variable, don't use the As clause.  If there is no As clause, the default data type of variable is used.

As type	Declares the data type of variable:  Integer, Long, Single, Double, Currency, String, Variant, Any, a user-defined type, or any object type.

Use the Any data type in an As clause only to override type checking for that argument.

Use the Declare statement to declare external procedures (procedures contained in a DLL).  A Declare statement for an external procedure can appear only in the Declarations section of a form or module.  DLL procedures declared in any module are available to all procedures in all forms and modules, but DLL procedures declared in a form are only available to the procedures in the form.

Empty parentheses indicate that the Sub or Function procedure has no arguments and that arguments should be checked to ensure that none are passed.  In the following example, First takes no arguments.  If you use arguments in a call to First, an error occurs:

Declare Sub First Lib "MyLib" ()

When an argument list appears, the number and type of arguments are checked each time the procedure is called.  In the following example, First takes one Long argument:

Declare Sub First Lib "MyLib" (X&)

Note	You can't have fixed-length strings in the parameter list of a Declare statement because only variable-length strings can be passed to procedures.  Fixed-length strings can appear as procedure arguments, but they are converted to variable-length strings before being passed.


See Also

Call Statement


Declare Statement Example

The example uses the Declare statement to declare a reference to an external function (GetProfileString) in the Windows Kernel DLL.  To try this example, paste the code into the Declarations section of a form.  Make sure that the entire Declare statement appears as a single line in the Declarations section.  Then press F5 and click the form.

Declare Function GetProfileString Lib "Kernel" (ByVal SName$, ByVal KName$,ByVal Def$, ByVal Ret$, ByVal Size%) As Integer

Sub Form_Click ()

Dim Msg, Success	' Declare variables

Dim KName$, Ret$, SName$

SName$ = "Intl"	' WIN.INI section name.

KName$ = "sCountry"	' WIN.INI country setting.

Ret$ = String$(255, 0)	' Initialize return string.

' Call Windows Kernel DLL.
Success = GetProfileString(SName$, KName$, "", Ret$, Len(Ret$))

If Success Then	' Evaluate results.

Msg = "Your country setting is: " & Ret$

Else

Msg = "There is no country setting in your WIN.INI file."

End If

MsgBox Msg	' Display message.

End Sub


Deftype Statements

See Also	Example

Used in the Declarations section of forms and modules to set the default data type for variables and Function procedures.

Syntax

DefInt letterrange [,letterrange] . . .

DefLng letterrange [,letterrange] . . .

DefSng letterrange [,letterrange] . . .

DefDbl letterrange [,letterrange] . . .

DefCur letterrange [,letterrange] . . .

DefStr letterrange [,letterrange] . . .

DefVar letterrange [,letterrange] . . .

Remarks

The argument letterrange has the following form:

letter1 [-letter2]

The arguments letter1 and letter2 specify the range of variables for which a default data type will be set.  Each argument represents the first letter of variable names and can be any uppercase or lowercase letter of the alphabet.  For instance, a letter range of A-D sets the default data type for all variables that begin with A, B, C, or D. The case of the letters in letterrange isn't significant.

The reserved word you use (type in Deftype) determines which of the following data types will be the default setting of variables in letterrange: Integer(DefInt), Long(DefLng), Single(DefSng), Double(DefDbl), Currency(DefCur), String(DefStr), or Variant (DefVar).  For example, in the following program fragment, Message is a string variable:

DefStr A-Q
...
Message = "Out of stack space."

A Deftype statement affects only the form or module in which it is used.  For example, a DefInt statement in one module affects only the default data type of variables declared in that module; the default data type of variables in forms and other modules is unaffected.  If not explicitly declared with a Deftype statement, the default data type for all variables and all Function procedures in forms and modules is Variant.

When a letter range is specified, it usually defines the data type for variables that begin with letters in the first 128 characters of the ANSI character set.  However, when you specify the letter range A-Z, you set the default to the specified data type for all variables, including any that begin with international characters from the extended part of the ANSI character set (128-255).

Once the range A-Z has been specified, you cannot further redefine any subranges of variables using Deftype statements.  In fact, once a range has been specified, if you include a previously defined letter in another Deftype statement, an error occurs.  However, you can explicitly assign the data type of any variable, defined or not, using a Dim statement or a type-declaration character.  For example, you can use the following code in the Declarations section of a form or module to define a variable as a Double even though the default data type is Integer:

DefInt A-Z
Dim TaxRate As Double

You can use the following statement in a procedure to explicitly assign the data type of Pi:

Pi! = 3.141593

A type-declaration character always takes precedence over a Deftype statement.  Deftype statements don't affect elements of user-defined types.


See Also

ANSI Character Set

Let Statement


Deftype Statement Example

The example uses the Deftype statements to set default data types of variables in two ranges.  Variables beginning with the letters A-K will be Integer; variables beginning with L-Z will be String.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

DefInt A-K

DefStr L-Z

Sub Form_Click ()

NL = Chr(10)	' Define newline.

IntVal = 2.3455

Msg = "Notice that none of the string variables in this demo have "

Msg = Msg & "the $ type-declaration character appended to their "

Msg = Msg & "names." & NL & NL & "The DefStr statement defines "

Msg = Msg & "the default for variables starting with letters 'L' "

Msg = Msg & "through 'Z' to be of the string data type."

MsgBox Msg

Msg = "Notice that the variable 'IntVal' has been defined as an "

Msg = Msg & "integer. Even though it is assigned a real value, it "

Msg = Msg & "behaves as an integer, i.e., IntVal = "

Msg = Msg & IntVal & " instead of 2.3455."

MsgBox Msg	' Display message.

End Sub


Dim Statement

See Also	Example

Declares variables and allocates storage space.  When used in the Declarations section of a form or module, the variables declared with Dim are available to all procedures within the form or module.  When used at the procedure level, the variables are available only in the procedure.

Syntax

Dim varname[([subscripts])][As [New] type][, varname[([subscripts])][As [New] type] ] . . .

Remarks

The Dim statement has these parts:

Part	Description

varname	Name of a variable.

subscripts	Dimensions of an array variable.  You can declare multiple dimensions.  The syntax of subscripts is described below.

As type	Reserved word used to declare the data type of a variable.  The type may be Integer, Long, Single, Double, Currency, String (for variable-length strings), String * length (for fixed-length strings), Variant, a user-defined type, or an object type.  Use a separate As type clause for each variable being defined.

New	Creates a new instance of a specific object type, such as Form1.  The New reserved word cannot be used to create new variables of any of the fundamental data types, nor can it be used to create a variable of any generic object type (MDIForm, Form or Control.) or any specific control type (CommandButton, TextBox, and so on).

The argument subscripts has the following syntax:

[lower To ]upper[,[lower To] upper] . . .

The To reserved word provides a way to indicate both the lower and upper bounds of an array variable's subscripts.  The following statements are equivalent if there is no Option Base statement:

Dim A(8,3)
Dim A(0 To 8, 0 To 3)
Dim A(8, 0 To 3)

Array subscripts can be negative.  To can be used to specify any range of subscripts between -32,768 and 32,767, inclusive.  For example:

Dim A(-4 To 10)
Dim B(-99 To -5, -3 To 0)

The maximum number of array dimensions allowed in a Dim statement is 60.

If you use a subscript that is greater than the specified maximum or smaller than the specified minimum, an error occurs.

Use a Dim statement in the Declarations section or in Sub or Function procedures to declare the data type of a variable.  For example, the following statement declares the variable as an Integer.

Dim NumberOfEmployees As Integer

Also use a Dim statement in the Declarations section or in Sub or Function procedures to declare the object type of a variable.  The following statement declares a variable for a new instance of a form.

Dim X As New Form1

If New is not used when declaring an object variable, no instance of the object actually exists.  The variable must be assigned to an existing object of type using the Set statement before it can be used.  Until it is assigned to an existing object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

You can also use the Dim statement with empty parentheses to declare dynamic arrays.  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 Global or Dim statement, an error occurs.

When variables are initialized, numeric variables are initialized to 0, Variant variables to Empty.  Variable-length strings are initialized as zero-length strings, and fixed-length strings are filled with zeros.  The fields of user-defined type variables are initialized as if they were separate variables.

Tip	When you use the Dim statement in a procedure, it is a generally accepted programming practice to put Dim statements at the beginning of the procedure.

The reserved word Shared is preserved for compatibility with earlier versions of Basic, but has no effect in Visual Basic.


See Also

Global Statement

Option Base Statement

ReDim Statement

Set Statement

Static Statement

Type Statement


Dim Statement Example

The example uses the Dim statement to declare variables at module and procedure level.  Dim is also used to declare a new instance of a form.  To try this example, which also illustrates the action of the Arrange method, paste the code into the Declarations section of an MDI Form named MDIForm1 that has an MDI child form (named Form1), and a picture box (named Picture1).  Then press F5 and click anywhere in the picture box.

Const FORMCOUNT = 5

Dim F(FORMCOUNT) As New Form1

Sub MDIForm_Load ()

Dim I	' Declare local variable.

Load Form1	' Load original Form1.

For I = 1 To FORMCOUNT

F(I).Caption = "Form" & I + 1	' Change caption on copies.

F(I).Show	' Load 5 copies of Form1.

Next I

End Sub

Sub Picture1_Click ()

Static ClickCount	' Declare variables.

Dim I, PrevWidth, Start

ClickCount = ClickCount + 1	' Increment click counter.

Select Case ClickCount

Case 1

MDIForm1.Arrange 1	' Tile horizontally.

Case 2

MDIForm1.Arrange 2	' Tile vertically.

Case 3	' Minimize each form.

PrevWidth = MDIForm1.Width	' Get MDIForm width.

MDIForm1.Width = PrevWidth / 2	' Divide it in half.

Form1.WindowState = 1	' Minimize the original.

For I = 1 To FORMCOUNT	' Look at each instance of F.

If TypeOf F(I) Is Form1 Then

F(I).WindowState = 1	' Minimize each copy.

End If

Next I

Start = Timer	' Get timer start point.

Do

Loop Until Timer >= Start + 5

MDIForm1.Width = PrevWidth	' Resize to original size.

MDIForm1.Arrange 3	' Arrange icons.

End Select

End Sub


Erase Statement

See Also	Example

Reinitializes the elements of fixed arrays and deallocates dynamic-array storage space.

Syntax

Erase arrayname [, arrayname] . . .

Remarks

The argument arrayname is the name of the array to be erased.  It is important to know whether an array is fixed (ordinary) or dynamic because Erase behaves differently depending on the type of array.  For fixed arrays, no memory is recovered. Erase sets the elements of a fixed array as follows:

Type of array	Effect of Erase on fixed-array elements
Fixed numeric array	Sets each element to zero
Fixed string array (variable-length)	Sets each element to zero-length ("")
Fixed string array (fixed-length)	Sets each element to zero
Fixed Variant array	Sets each element to Empty
Array of user-defined types	Sets each element as if it were a separate variable
Array of objects	Sets each element to the special value Nothing
For dynamic arrays,  Erase frees the memory used by the array.  Before your program can refer to the dynamic array again, it must redeclare the array variable's dimensions using a ReDim statement.


See Also

Dim Statement

ReDim Statement


Erase Statement Example

In this example, a two-dimensional array is created, filled, and erased.  When the Erase statement is executed, zeros replace the contents of each element, but no memory space is recovered.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Static Sub Form_Click ()

Dim I As Integer, J As Integer	' Declare Variables.

Dim Total As Long

Dim Matrix(50, 50) As Integer	' Create 2-D integer array.

For I = 1 To 50

For J = 1 To 50

Matrix(I, J) = J	' Put some values into array.

Next J

Next I

Erase Matrix	' Erase array.

Total = 0	' Initialize total counter.

For I = 1 To 50

For J = 1 To 50

Total = Total + Matrix(I, J)	' Sum elements after Erase

Next J	' to make sure all are set

Next I	' to zero.

Msg = "An array has been created, filled, and erased. When the "

Msg = Msg & "Erase statement was executed, zeros replaced the "

Msg = Msg & "previous contents of each element.  The total of "

Msg = Msg & "all elements is now " & Total & ", "

Msg = Msg & "demonstrating that all elements have been cleared."

MsgBox Msg	' Display message.

End Sub


Function Statement

See Also	Example

Declares the name, arguments, and code that form the body of a Function procedure.

Syntax

[Static] [Private] Function functionname [(argumentlist)] [As type]

[statementblock]

[functionname = expression]

[Exit Function]

[statementblock]

[functionname = expression]

End Function

Remarks

All executable code must be in Function or Sub procedures.  You can't define a Function procedure inside another Function or Sub procedure.

The Function statement has these parts:

Part	Description

Static	Indicates that the Function procedure's local variables are preserved between calls.  The Static attribute doesn't affect variables that are declared outside the Function procedure, even if they are used in the procedure.

Private	Indicates that the Function procedure is accessible only to other procedures in the module in which it exists.  No other procedure in any other module has access.  The Private keyword has no effect when declaring Function procedures in a form since they are not available outside the form anyway.

Function	Marks the beginning of a Function procedure.

functionname	Name of the function.  Function procedure names follow the same rules that constrain the names of other variables and can include a type-declaration character.  Because Function names are recognized by all procedures in all modules, functionname cannot be the same as any other globally recognized name in the program.  Such names include the names of procedures (in Visual Basic or a dynamic-link library [DLL]), Global variables, and Global constants.  To avoid a name conflict, you can use the Private reserved word to make the Function procedure local to the module in which it appears, but access to it will not be available from any procedure in any other module.  Even if you use the Private reserved word, functionname still cannot be the same as any other module-level variable, constant, or procedure name in the same module.

Note that the type of the name determines the data type returned by the Function procedure.  To specify the return data type of the Function procedure, either use an As clause following argumentlist or include a type-declaration character in the Function name.  For example, to create a Function procedure that returns a string, you can include a dollar sign in the name, use an As String clause, or give it a name defined as a string name with a DefStr statement.

argumentlist	List of variables, representing arguments, that are passed to the Function procedure when it is called.  Multiple variables are separated by commas.  Unless identified with the ByVal reserved word, individual arguments are passed by reference, so changing an argument's value inside the Function procedure changes its value in the calling procedure.  If an argument passed to a function is an expression, it is treated as if it used the ByVal reserved word: no part of the expression is altered by the function.

As type	Reserved word used to declare the data type of the value returned by the Function procedure; type can be Integer, Long, Single, Double, Currency, String, or Variant.

statementblock	Any group of statements that are to be executed within the body of the Function procedure.

expression	Return value of the function.  A Function procedure returns a value by assigning that value to the function functionname.  Any number of such assignments can appear anywhere within the procedure.  If no value is assigned to functionname, the procedure returns a default value: A numeric function returns 0, a String function returns a zero-length string (""), and a Variant function returns Empty.

Exit Function	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.

End Function	Marks the end of a Function procedure.

The argument argumentlist has the following syntax:

[ByVal]variable[( )] [As type] [, [ByVal]variable[( )] [ As type] ] . . .

It has these parts.

Part	Description

ByVal	Indicates that the argument is passed by value rather than by reference.  The ByVal reserved word cannot be used with a variable of a user-defined type, an object type, or a variable that is an array.

variable	Name of the variable representing the argument.  For array variables, use the parentheses but omit the number of dimensions.

As type	Declares the data type of variable.  The type may be Integer, Long, Single, Double, Currency, String (variable-length strings only), Variant, a user-defined type, or an object type.  Use a separate As type clause for each argument.

Like a Sub procedure, a Function procedure is a separate procedure that can take arguments, perform a series of statements, and change the values of its arguments.  However, unlike a Sub procedure, a Function procedure can be used in an expression in the same manner as any intrinsic function, such as Sqr, Cos, or Chr.

You can call a Function procedure by using the function name, followed by the argument list in parentheses, in an expression.  If the function has no arguments, you still must include the parentheses.

Caution	Function procedures can be recursive; that is, they can call themselves to perform a given task.  However, recursion can lead to stack overflow.  The Static reserved word is usually not used with recursive Function procedures.

To return a value from a function, assign the value to the function name.  For example, in a function named BinarySearch, you might assign the value of the constant False to the name to indicate that the value was not found.

Function BinarySearch(...)

...

' Value not found. Return a value of False.

If lower > upper Then

BinarySearch = 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.  Other variables 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 name conflict can occur if anything you have defined in the Declarations section has the same name.  If your procedure refers to an undeclared variable that has the same name as another procedure, a Global or module-level constant or variable, or an object, Visual Basic assumes that your procedure is referring to that module-level name.  Explicitly declare variables to avoid this kind of conflict.  You can use an Option Explicit statement to force explicit declaration of variables.

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

Dim Statement

Global Statement

Option Explicit Statement

Static Statement

Sub Statement


Function Statement Example

The example uses the Function statement to declare the name of a Function procedure.  Exit Function is used to exit the procedure before the End Function statement is encountered.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, SqrN	' Declare variables.

Dim N As Double

N = InputBox("Calculate the square root of what number? ")

Msg = "The square root of " & N

SqrN = SquareRoot(N)	' Call user-defined function.

Select Case SqrN

Case 0: Msg = Msg & " is zero."

Case -1: Msg = Msg & " is an imaginary number."

Case Else: Msg = Msg & " is" & SqrN

End Select

MsgBox Msg	' Display message.

End Sub

Function SquareRoot (X As Double) As Double

Select Case Sgn(X)	' Evaluate sign of argument.

Case 1	' OK if positive.

SquareRoot = Sqr(X)

Exit Function

Case 0	' Notify user if 0.

SquareRoot = 0

Case -1	' Notify user if negative.

SquareRoot = -1

End Select

End Function


Global Statement

See Also	Example

Used  in the Declarations section of a module to declare global variables and allocate storage space.  Global variables are available to all procedures in all forms and modules.

Syntax

Global varname[([subscripts])] [As [New] type] [, varname[([subscripts])] [As [New] type] ] . . .

Remarks

The Global statement has these parts:

Part	Description

varname	Name of a variable.

subscripts	Dimensions of an array.  You can declare multiple dimensions.  The syntax of subscripts is described below.

As type	Reserved word used to declare the data type of a variable.  The type may be Integer, Long, Single, Double, Currency, String (for variable-length strings), String * length (for fixed-length strings), Variant, a user-defined type, or an object type.  Use a separate As type clause for each variable being defined.

New	Creates a new instance of a specific object type, such as Form1.  The New reserved word cannot be used to create new variables of any of the fundamental data types, nor can it be used to create a variable of any generic object type (MDIForm, Form or Control.) or any specific control type (CommandButton, TextBox, and so on).

The argument subscripts has the following syntax:

[lower To ]upper[,[lower To] upper] . . .

The To reserved word provides a way to indicate both the lower and upper bounds of an array variable's subscripts.  The following statements are equivalent if there is no Option Base statement:

Global A(8,3)

Global A(0 To 8, 0 To 3)

Global A(8, 0 To 3)

Array subscripts can be negative. To can be used to specify any range of subscripts between -32,768 and 32,767, inclusive.  For example:

Global A(-4 To 10)

Global B(-99 To -5, -3 To 0)

The maximum number of array dimensions allowed in a Global statement is 60.

If you use a subscript that is greater than the specified maximum or smaller than the specified minimum, an error occurs.

Use the Global statement in the Declarations section of a module to declare variables that are available to all procedures in all modules.  You can also use the Global statement to declare the data type of a variable.  For example, the following statement declares the variable as an Integer:

Global NumberOfEmployees As Integer

The following statement declares a variable for a new instance of a form:

Global X As New Form1

If New is not used when declaring an object variable, no instance of the object actually exists.  The variable must be assigned to an existing object of type using the Set statement before it can be used.  Until it is assigned to an existing object, the declared object varaible has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

You can also use the Global statement with empty parentheses to declare dynamic arrays.  After declaring a dynamic array, use the ReDim statement within a procedure level 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 Global or Dim statement, an error occurs.

Note	You cannot use the Global statement in forms, because form variables are available only to procedures within the form where they are declared.

When variables are initialized, numeric variables are initialized to 0, Variant variables to Empty.  Variable-length strings are initialized as zero-length strings, and fixed-length strings are filled with zeros.  The fields of user-defined type variables are initialized as if they were separate variables.


See Also

Const Statement

Dim Statement

Option Base Statement

ReDim Statement

Static Statement

Type Statement


Global Statement Example

The example uses the Global statement to declare two variables in a module.  The first is a global dynamic-array variable; the second is a global integer variable.  To try this example, paste the Form_Click procedure into the Declarations section of a form containing a list box named List1. Paste the remaining code into the Declarations section of a module.  Then press F5 and click the form.

Sub Form_Click ()

LoadGlobalArray	' Call GlobalDemo procedure.

For I = 1 To UBound(TestArray)	' Determine array size and

List1.AddItem TestArray(I)	' put array items in list box.

Next I

End Sub

Global TestArray()	' Declare dynamic-array.

Global Size As Integer	' Declare integer.

Sub LoadGlobalArray ()

Dim I	' Declare local variables.

Size = Int(100 * Rnd + 1)	' Generate random size.

ReDim TestArray(Size)	' Define how many elements.

For I = 1 to Size	' Index of elements.

TestArray(I) = Int(100 * Rnd + 1)	' Put random number in each element.

Next I

End Sub


LBound Function

See Also	Example

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

Syntax

LBound(array [,dimension])

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.

The LBound function has the following parts:

Part	Description

array	Name of an array variable.

dimension	Integer indicating which dimension's lower bound is returned.  Use 1 for the first dimension, 2 for the second dimension, and so on.  If dimension is omitted, 1 is assumed.

LBound returns the values listed in the table below 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 default lower bound for any dimension is either 0 or 1, depending on the setting of the Option Base statement.

Arrays for which dimensions are set using the To clause in a Dim, Global, ReDim, or Static statement can have any integer value as a lower bound.


See Also

Dim Statement

Global Statement

Option Base Statement

ReDim Statement

Static Statement

UBound Function


LBound Function Example

The example uses the LBound function to determine the lower bounds for a three-dimensional array.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B, C, Msg, NL, TB	' Declare variables.

Dim Array()	' Declare array variable.

NL = Chr(10): TB = Chr(9)	' Define newline, tab.

' Generate some random dimensions between 2 and 10 for array size.

A = -Int(9 * Rnd + 2)	' First dimension.

B = Int(9 * Rnd + 2)	' Second dimension.

C = Int(9 * Rnd + 2)	' Third dimension.

ReDim Array(A To 20, B to 20 , C to 20)	' Set dimensions.

Msg = "The test array has the following lower bounds: " & NL

Msg = Msg & TB & "Dimension 1 = " & LBound(Array, 1) & NL

Msg = Msg & TB & "Dimension 2 = " & LBound(Array, 2) & NL

Msg = Msg & TB & "Dimension 3 = " & LBound(Array, 3)

MsgBox Msg	' Display message.

End Sub


Let Statement

See Also	Example

Assigns the value of an expression to a variable.

Syntax

[Let] variable = valueexpression

Remarks

The Let statement has these parts:

Part	Description

variable	Name of the variable

=	Assignment operator

valueexpression	Value assigned to the variable

The reserved word Let is always optional.  You can assign a String or numeric expression to a variable without using the Let reserved word.  In fact, most Basic programmers never use the Let reserved word.

A value expression can be assigned to a variable only if the data types they have are compatible.  You can't assign String expressions to numeric variables, and you can't assign numeric expressions to String variables.  If you do, a Type mismatch error occurs at compile time.

Variant variables can be assigned either String or numeric expressions.  However, the reverse is not true.  Any Variant except a Null can be assigned to a String variable, but only a Variant that contains a value that can be interpreted as a number can be assigned to a numeric variable.  Use the IsNumeric function to determine if the Variant can be converted to a number.

Caution	Assigning an expression of one numeric data type to a variable of a different numeric data type coerces the value of the expression into the data type of the resulting variable.

Let statements can be used to assign one record variable to another only when both variables are of the same user-defined type.  Use the LSet statement to assign record variables of different user-defined types.


See Also

Const Statement

IsNumeric Function

LSet Statement

Set Statement


Let Statement Example

The example uses statements with and without the Let reserved word to assign the value of an expression to a variable.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, Pi	' Declare variable.

' Assign Pi using Let statement.

Let Pi = 4 * Atn(1)

' Assign Msg without Let statement.

Msg = "The area of circle whose radius is 3 inches is "

Msg = Msg & (Pi * (3^2)) & " inches."

MsgBox Msg	' Display message.

End Sub


Option Compare Statement

See Also	Example

Declares the default comparison mode to use when string data is compared.

Syntax

Option Compare {Binary | Text}

Remarks

The Option Compare statement is used in the Declarations section of a form or module to specify the string comparison method for that form or module.

String comparisons can be either Binary or Text.

Binary comparisons are case sensitive; so, for example, an "M" doesn't match an "m".  When determining whether a character is less than, equal to, or greater than another character, the program uses the character's relative order of appearance in the ANSI character set.

Text comparisons are case insensitive; so, for example, an "M" matches an "m".  In addition, the relative order of characters is not the same as it is for Binary.  For Text comparisons, the relative order of characters is determined by the setting of the country code in the international section of your WIN.INI file.

When  a form or module doesn't include an Option Compare statement, the default text comparison method is Binary.


See Also

ANSI Character Set

Comparison Operators

InStr Function

StrComp Function


Option Compare Statement Example

The example uses the Option Compare statement to set the string comparison method.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Option Compare Text	' Set string comparison.

Sub Form_Click ()

Dim LName, Msg, NameStr, UName	' Declare variables.

NameStr = InputBox("Enter your name.")	' Get name from user.

UName = UCase(NameStr)	' Make uppercase version.

LName = LCase(NameStr)	' Make lowercase  version.

If UName Like LName Then	' Compare them.

Msg = "'" & UName & "' matches '" & LName & "'. End the program, "

Msg = Msg & "then remove the 'Option Compare Text' line from the "

Msg = Msg & "Declarations section of the form and try the example again."

Else

Msg = "Now, '" & UName & "' does not match '" & LName & "'."

End If

MsgBox Msg	' Display message.

End Sub


Option Explicit Statement

See Also	Example

Forces explicit declaration of all variables.

Syntax

Option Explicit

Remarks

The Option Explicit statement is used in the Declarations section of a form or module to force explicit declaration of all variables for that form or module.

If you don't use the Option Explicit statement, all undeclared variables are of Variant data type (unless the default type is otherwise specified with a Deftype statement).  When you use the Option Explicit statement, all variables must be explicitly declared before they are used in Dim, Global, ReDim, or Static statements .  If you attempt to use an undeclared variable name, a Variable not declared error occurs at compile time.

Tip	Use Option Explicit to avoid mistyping the name of an existing variable or to avoid risking confusion in code in which the scope of the variable is not clear.

Note	You can automatically include an Option Explicit statement in your code by selecting the Environment menu item from the Options menu and changing the Require Variable Declaration option to Yes.


See Also

Const Statement

Deftype Statements

Dim Statement

Function Statement

Global Statement

ReDim Statement

Static Statement

Sub Statement


Option Explicit Statement Example

The example uses Option Explicit to force you to explicitly declare all variables. To try this example, paste the code into the Declarations section of a form.  Then press F5.  You'll immediately notice that because the variable X has not been formally declared using the Dim statement or equivalent, that the Variable not defined error message is displayed.

Option Explicit	' Force variable declaration.

Sub Form_Click ()

Print X	' Print X on form

End Sub


ReDim Statement

See Also	Example

Used at the procedure level to declare dynamic-array variables and allocate or reallocate storage space.

Syntax

ReDim [Preserve] varname(subscripts) [As type][, varname(subscripts) [As type] ] . . .

Remarks

The ReDim statement has these parts:

Part	Description

Preserve	Preserves the data in an existing array when you resize the last dimension.

varname	Name of a variable.

subscripts	Dimensions of an array.  You can declare multiple dimensions.  The syntax of subscripts is described below.

As type	Reserved word used to declare the data type of a variable.  The type may be Integer, Long, Single, Double, Currency, String (for variable-length strings), String * length (for fixed-length strings), Variant, a user-defined type, or an object type.  Use a separate As type clause for each variable being defined.

The argument subscripts has the following syntax:

[lower To ]upper[,[lower To] upper]. . .

The To reserved word provides a way to indicate both the lower and upper bounds of an array variable's subscripts.  The following statements are equivalent if there is no Option Base statement:

ReDim A(8,3)

ReDim A(0 To 8, 0 To 3)

ReDim A(8, 0 To 3)

Array subscripts can be negative.  To can be used to specify any range of subscripts between -32,768 and 32,767, inclusive.  For example:

ReDim A(-4 To 10)

ReDim B(-99 To -5, -3 To 0)

If you use a subscript that is greater than the specified maximum or smaller than the specified minimum, an error occurs.

The ReDim statement is usually used to size or resize a dynamic array that has already been formally declared using a Global or Dim statement with empty parentheses (without dimension subscripts).  If you first declare a dynamic array using a Global or Dim statement and include no dimension subscripts, the maximum number of array dimensions you can later specify with ReDim is eight.  If your array requires more than eight dimensions, you can use the ReDim statement  within a procedure to initially declare a local dynamic-array variable.  Your array can then have as many as 60 dimensions.

You can use the ReDim statement repeatedly to change the number of elements in an array.  However, you can't use ReDim to change the number of dimensions in an array.  For example, if you declare an array consisting of two dimensions (for example, ReDim A(10,10)), you can't use ReDim later to change it to an array with three dimensions. (for example, ReDim A(12,12,12,) ).  Similarly, you can't declare an array of Integers and later use ReDim to change the array to another data type.

If you use the Preserve reserved word, you can resize only the last array dimension.  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 cannot resize the first one. You can only change the size of 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)

When variables are initialized, numeric variables are initialized to 0, Variant variables to Empty.  Variable-length strings are initialized as zero-length strings, and fixed-length strings are filled with ANSI zeros (Chr(0)).  The fields of user-defined type variables are initialized as if they were separate variables.


See Also

Dim Statement

Global Statement

Option Base Statement

Static Statement


ReDim Statement Example

The example uses the ReDim statement to dynamically resize an array while a procedure is running.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim TestArray() As Integer	' Declare dynamic array.

Dim I, Msg, Size	' Declare variables.

Size = Int(100 * Rnd + 1)	' Generate random number.

ReDim TestArray(Size)	' Make array have Size elements.

For I = 1 To Size	' Index for number of elements.

TestArray(I) = Rnd	' Put number in each element.

Next I

ReDim TestArray(Size * 10)	' Make array 10 times larger.

For I = 1 To Size * 10	' Index for number of elements.

TestArray(I) = Rnd	' Put number in each element.

Next I

Msg = "This demo created a dynamic array of " & Size

Msg = Msg & " elements and filled each with a random number.  "

Msg = Msg & "It then resized the array to " & (Size * 10)

Msg = Msg & " elements, again filling each with a random number.  "

Msg = Msg & "Finally, it restored the array back to "

Msg = Msg & Size & " elements."

MsgBox Msg	' Display message.

End Sub


Rem Statement

Example

Used to include explanatory remarks in a program.

Syntax1

Rem remark

Syntax 2

' remark

Remarks

The argument remark is the text of any comments you want to include in your program.  Spaces and punctuation are permitted.  Comment text appears exactly as entered when the program is listed.  You can use comments to document how your code works or to provide any other information with your code.

If you use line numbers or line labels, you can branch from a GoTo or GoSub statement to a line containing a Rem statement.  Execution continues with the first executable statement following the Rem statement.

As shown in syntax 2, you can use a single quotation mark (apostrophe) instead of the Rem reserved word.  If the Rem reserved word follows other statements on a line, it must be separated from the statements by a colon.  However, when you use a single quotation mark, the colon is not required after other statements.


Rem Statement Example

The example illustrates the various forms of the Rem statement syntax.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg1, Msg2	' Declare variables.

Rem This is the first form of the syntax.

' This is the second form of the syntax.

Msg1 = "Hello" : Rem Comment after a statement separated by a colon.

Msg2 = "Goodbye" ' Second form after a statement without a colon.

MsgBox "This example illustrates Rem statement syntax."

End Sub


Set Statement

See Also	Example

Assigns an object reference to a variable.

Syntax

Set objectvar = {objectexpr | New formtype | Nothing}

Remarks

The Set statement has the following parts:

Part	Description

objectvar	Name of the variable to which the object reference is being assigned.

objectexpr	Expression consisting of the name of an object, another declared variable of the same object type, or a function or method that returns an object.

New	Reserved word used to create a new instance of a specific object type (created as design time), such as Form1.  The New reserved word cannot be used to create new variables of any of the fundamental data types, nor can it be used to create a variable of any generic object type (MDIForm, Form or Control.) or any specific control type (CommandButton, TextBox, and so on).

formtype	A specific form type, for example Form1.

Nothing	Reserved word used to discontinue association of objectvar with any specific object.  Assigning objectvar to Nothing releases all the resources associated with the previously referenced object when no other variable refers to it.

To be valid, objectvar must be an object type consistent with the object being assigned to it.  And, it must either have been explicitly declared (using a Dim, Global, ReDim, or Static statement) or implicitly declared for you by Visual Basic, as occurs, for example, with form types.

The following example illustrates how Dim is used to formally declare the variable LedgerForm as Form1.  The Dim statement only declares a variable of type Form1.  No instance of Form1 actually exists.  Set then assigns a reference to a new instance of Form1 to the LedgerForm variable.

Dim LedgerForm As Form1

Set LedgerForm = New Form1

In the following example for a control, the variable X is declared (using Dim) as a variable that refers to a list box.  The Set statement assigns the object reference for X to an actual instance of a list box on Form1, in this case List1.

Dim X As ListBox

Set X = Form1!List1

Generally, when you use Set to assign an object reference to a variable, no copy of the object is created for that variable.  Instead, a reference to the object is created.  More than one object variable can refer to the same object.  Because these variables are references to, rather than copies of the object, any change in the object is reflected in all variables that refer to it.

However, when you use the New reserved word in the Set statement, you are actually creating a new instance of the referenced form type.  The new instance is not loaded until you either explicitly load it using the Load statement or implicitly load it by referring to one of its properties, methods, or members in code.


See Also

Dim Statement

Global Statement

ReDim Statement

Static Statement


Set Statement Example

The example uses the Set statement to declare a reference to a new instance of Form1.  To try this example, which also illustrates the action of the Arrange method, paste the code into the Declarations section of an MDI Form named MDIForm1 that has an MDI child form (named Form1), and a picture box (named Picture1).  Then press F5 and click anywhere in the picture box..

Const FORMCOUNT = 5

Dim F(1 To FORMCOUNT) As Form1	' Create object type variable.

Sub MDIForm_Load ()

Dim I	' Declare local variable.

Load Form1	' Load original Form1.

For I = 1 To FORMCOUNT

Set F(I) = New Form1	' Refer to new instance of Form1.

F(I).Caption = "Form" & I + 1	' Change caption on copies.

F(I).Show	' Load 5 copies of Form1.

Next I

End Sub

Sub Picture1_Click ()

Static ClickCount	' Declare variables.

Dim I, PrevWidth, Start

ClickCount = ClickCount + 1	' Increment click counter.

Select Case ClickCount

Case 1

MDIForm1.Arrange 1	' Tile horizontally.

Case 2

MDIForm1.Arrange 2	' Tile vertically.

Case 3	' Minimize each form.

PrevWidth = MDIForm1.Width	' Get MDIForm width.

MDIForm1.Width = PrevWidth / 2	' Divide it in half.

Form1.WindowState = 1	' Minimize the original.

For I = 1 To FORMCOUNT	' Look at each instance of F.

If TypeOf F(I) Is Form1 Then

F(I).WindowState = 1	' Minimize each copy.

End If

Next I

Start = Timer	' Get timer start point.

Do

Loop Until Timer >= Start + 5

MDIForm1.Width = PrevWidth	' Resize to original size.

MDIForm1.Arrange 3	' Arrange icons.

End Select

End Sub


Static Statement

See Also	Example

Used at the procedure level to declare variables and allocate storage space.  Variables declared with the Static statement retain their value as long as the program is running.

Syntax

Static varname[([subscripts])] [As [New] type] [, varname[([subscripts])] [As [New] type] ] . . .

Remarks

The Static statement has these parts:

Part	Description

varname	Name of a variable.

subscripts	Dimensions of an array.  You can declare multiple dimensions.  The syntax of subscripts is described below.

As type	Reserved word used to declare the data type of the variable.  The type may be Integer, Long, Single, Double, Currency, String (for variable-length strings), String * length (for fixed-length strings), Variant, a user-defined type, or an object type.  Use a separate As type clause for each variable being defined.

New	Creates a new instance of a specific object type, such as Form1.  The New reserved word cannot be used to create new variables of any of the fundamental data types, nor can it be used to create a variable of any generic object type (MDIForm, Form or Control) or any specific control type (CommandButton, TextBox, and so on).

The argument subscripts has the following syntax:

[lower To ]upper[,[lower To] upper] . . .

The To reserved word provides a way to indicate both the lower and upper bounds of an array variable's subscripts.  The following statements are equivalent if there is no Option Base statement:

Static A(8,3)

Static A(0 To 8, 0 To 3)

Static A(8, 0 To 3)

Array subscripts can be negative.  To can be used to specify any range of subscripts between -32,768 and 32,767, inclusive.  For example:

Static A(-4 To 10)

Static B(-99 To -5, -3 To 0)

The maximum number of array dimensions allowed in a Static statement is 60.

If you use a subscript that is greater than the specified maximum or smaller than the specified minimum, an error occurs.

Use the Static statement in nonstatic procedures to explicitly declare Static variables.  You must use Static to declare a fixed-size array in nonstatic procedures.  In Static procedures, you can use either Static or Dim to declare Static variables.

Use a Static statement within a procedure to declare the data type of a Static variable.  For example, the following statement declares a fixed-size array of integers:

Static EmployeeNumber(200) As Integer

Also use the Static statement in Sub or Function procedures to declare the object type of a variable.  The following statement declares a variable for a new instance of a form:

Static X As New Form1

If New is not used when declaring an object variable, no instance of the object actually exists.  The variable must be assigned to an existing object of type using the Set statement before it can be used.  Until it is assigned to an existing object, the declared object variable has the special value Nothing, which indicates that it does not refer to any particular instance of an object.

Note	The Static statement and the Static reserved word affect the lifetime of variables differently.  If you declare a procedure using the Static reserved word (as in Static Sub CountSales ()), the storage space for all local variables within the procedure is allocated once and the value of the variables is preserved for the entire time the program is running.  For nonstatic procedures, storage space for variables is allocated each time the procedure is called and released when the procedure is exited.  The Static statement is used to declare variables within nonstatic procedures to preserve their value as long as the program is running.

When variables are initialized, numeric variables are initialized to 0, Variant variables to Empty.  Variable-length strings are initialized as zero-length strings, and fixed-length strings are filled with zeros.  The fields of user-defined type variables are initialized as if they were separate variables.

Tip	When you use the Static statement in a procedure, it is a generally accepted programming practice to put Static statements at the beginning of the procedure with any Dim statements.


See Also

Dim Statement

Function Statement

Global Statement

Option Base Statement

ReDim Statement

Sub Statement


Static Statement Example

The example uses the Static statement to declare a persistent variable in the Picture_Click procedure.  To try this example, which also illustrates the action of the Arrange method, paste the code into the Declarations section of an MDI Form named MDIForm1 that has an MDI child form (named Form1), and a picture box (named Picture1).  Then press F5 and click anywhere in the picture box..

Const FORMCOUNT = 5

Dim F(1 To FORMCOUNT) As New Form1

Sub MDIForm_Load ()

Dim I	' Declare local variable.

Load Form1	' Load original Form1.

For I = 1 To FORMCOUNT

F(I).Caption = "Form" & I + 1	' Change caption on copies.

F(I).Show	' Load 5 copies of Form1.

Next I

End Sub

Sub Picture1_Click ()

Static ClickCount As Integer	' Declare variables.

Dim I, PrevWidth, Start

ClickCount = ClickCount + 1	' Increment click counter.

Select Case ClickCount

Case 1

MDIForm1.Arrange 1	' Tile horizontally.

Case 2

MDIForm1.Arrange 2	' Tile vertically.

Case 3	' Minimize each form.

PrevWidth = MDIForm1.Width	' Get MDIForm width.

MDIForm1.Width = PrevWidth / 2	' Divide it in half.

Form1.WindowState = 1	' Minimize the original.

For I = 1 To FORMCOUNT	' Look at each instance of F.

If TypeOf F(I) Is Form1 Then

F(I).WindowState = 1	' Minimize each copy.

End If

Next I

Start = Timer	' Get timer start point.

Do

Loop Until Timer >= Start + 5

MDIForm1.Width = PrevWidth	' Resize to original size

MDIForm1.Arrange 3	' Arrange icons

End Select

End Sub


Sub Statement

See Also	Example

Declares the name, arguments, and code that form the body of a Sub procedure.

Syntax

[Static] [Private] Sub subname [(argumentlist)]

[statementblock]

[Exit Sub]

[statementblock]

End Sub

Remarks

All executable code must be in Sub or Function procedures.  You can't define a Sub procedure inside another Sub or Function procedure.

The Sub statement has these parts:

Part	Description

Static	Indicates that the Sub procedure's local variables are preserved between calls.  The Static attribute doesn't affect variables that are declared outside the Sub procedure, even if they are used in the procedure.

Private	Indicates that the Sub procedure is accessible only to other procedures in the module in which it exists.  No other procedure in any other module has access to it.  The Private keyword has no effect when declaring Sub procedures in a form since they are not available outside the form anyway.

Sub	Marks the beginning of a Sub procedure.

subname	Name of the procedure.  Sub procedure names follow the same rules that constrain the names of other variables but cannot include a type-declaration character.  Because Sub names are recognized by all procedures in all modules, subname cannot be the same as any other globally recognized name in the program.  Such names include the names of procedures (in Visual Basic or declared dynamic-link library [DLL]) procedures, Global variables, and Global constants.  To avoid a name conflict, you can use the Private reserved word to make the Sub local to the module in which it appears, but access to it will not be available from any procedure in any other module.  Even if you use the Private reserved word, subname cannot be the same as any other module-level variable, constant, or procedure name in the same module.

argumentlist	List of variables, representing arguments, that are passed to the Sub procedure when it is called.  Multiple variables are separated by commas.  Unless identified with the ByVal reserved word, arguments are passed by reference, so changing an argument's value inside the Sub procedure changes its value in the calling procedure.

statementblock	Any group of statements that are executed within the body of the Sub procedure.

Exit Sub	Causes 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.

End Sub	Marks the end of a Sub procedure.

The argument argumentlist has this syntax:

[ByVal] variable[( )] [As type] [, [ByVal]variable[( )] [ As type] ] . . .

It has these parts:

Part	Description

ByVal	Indicates the argument is passed by value rather than by reference.  The ByVal reserved word cannot be used with a variable of a user-defined type, an object type, or a variable that is an array.

variable	Name of the variable to pass as an argument.  For array variables, use the parentheses but omit the number of dimensions.

As type	Declares the data type of variable.  The type may be Integer, Long, Single, Double, Currency, String (variable-length strings only), Variant, a user-defined type, or an object type.  Use a separate As type clause for each argument.

Like a Function procedure, a Sub procedure is a separate procedure that can take arguments, perform a series of statements, and change the value of its arguments.  However, unlike a Function procedure, which returns a value, a Sub procedure can't be used in an expression.

You can 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.

Caution	Sub procedures can be recursive; that is, they can call themselves to perform a given task.  However, recursion can lead to stack overflow. The Static reserved word usually is not used with recursive 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.  Other variables 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 name conflict can occur if anything you have defined in the Declarations section has the same name.  If your procedure refers to an undeclared variable that has the same name as another procedure, a Global or module-level constant or variable, or an object, Visual Basic assumes that your procedure is referring to that module-level name.  Explicitly declare variables to avoid this kind of conflict.  You can use an Option Explicit statement to force explicit declaration of variables.

Note   You can't use GoSub, GoTo, or Return to enter or exit a Sub procedure.


See Also

Call Statement

Dim Statement

Function Statement

Global Statement

Option Explicit Statement

Static Statement


Sub Statement Example

The example uses the Sub statement to declare the name of two Sub procedures.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B	' Declare local variables.

A = InputBox("What is the length?")	' Ask for length of rectangle.

B = InputBox("What is the width?")	' Ask for width of rectangle.

SubDemo A, B	' Call Sub with arguments.

End Sub

Sub SubDemo(RLen, RWid)	' Sub with two arguments.

Dim Area	' Declare local variable.

Area = RLen * RWid	' Calculate area of rectangle.

MsgBox "Total area is " & Area	' Display result.

End Sub


Type Statement

Example

Defines a user-defined data type containing one or more elements.

Syntax

Type usertype
  elementname [(subscripts)] As typename
[ elementname [(subscripts)] As typename]
. . .
End Type

Remarks

The Type statement has these parts:

Part	Description

Type	Marks the beginning of a user-defined type.

usertype	Name of a user-defined data type.  It follows standard variable naming conventions.

elementname	Name of an element of the user-defined data type.  It follows standard variable-naming conventions.

subscripts	Dimensions of an array element.  You can declare multiple dimensions.  The syntax of subscripts is described below.

typename	One of these data types: Integer, Long, Single, Double, Currency, String (for variable-length strings), String * length (for fixed-length strings), Variant,  or another user-defined type.  The argument typename can't be an object type.

End Type	Marks the end of a user-defined type.

The argument subscripts has the following syntax:

[lower To ]upper[,[lower To] upper] . . .

The To reserved word provides a way to indicate both the lower and upper bounds of an array variable's subscripts.  Array subscripts can be negative.  To can be used to specify any range of subscripts between -32,768 and 32,767, inclusive.  The maximum number of array dimension is 60.

The Type statement can be used only in the Declarations section of a module.  Once you have declared a user-defined type using the Type statement, you can declare a variable of that type anywhere in your application.  Use Dim, Global, ReDim, or Static to declare a variable of a user-defined type.

Line numbers and line labels aren't allowed in Type...End Type blocks.

User-defined types are often used with data records because data records frequently consist of a number of related elements of different data types.

The following example shows the use of static arrays in a user-defined type:

Type StateData

CityCode (1 To 100) As Integer ' Declare a static array.

County As String * 30

End Type

Dim Washington(1 To 100) As StateData

In the preceding example, StateData includes the CityCode static array, and the record Washington has the same structure as StateData.

When you declare a static array within a user-defined type, its dimensions must be declared with numeric constants rather than variables.


Type Statement Example

The example uses Type to create a user-defined type with three elements. A variable is then declared of the user-defined type, and data is assigned to each element.  To try this example, paste the user-defined type definition into the Declarations section of a module.  Paste the remaining code into the Declarations section of a form.  Then press F5 and click the form.

Type TestRecord	' Create user-defined type.

CustNum As Long

CustName As String * 38

CustPurchase As String * 24

End Type

Sub Form_Click ()

Dim Answer, FileNum, Index, Msg, NL, TB	' Declare variables.

Static CustEntry As TestRecord	' Create output buffer.

NL = Chr(10): TB = Chr(9)	' Define newline, tab.

FileNum = FreeFile	' Get file number.

Open "TESTFILE" For Random As FileNum

Index = 1	' Keep track of records.

Do	' Get data to fill all

CustEntry.CustNum = Index	' the elements of the

Msg = "Enter customer name:"	' data records.

CustEntry.CustName = InputBox(Msg)

If CustEntry.CustName = String(38, 32) Then Exit Do

Msg = "Enter purchase:"

CustEntry.CustPurchase = InputBox(Msg)

Msg = "Customer #"

Msg = Msg & CustEntry.CustNum & NL

Msg = Msg & CustEntry.CustName & NL

Msg = Msg & CustEntry.CustPurchase & NL

Msg = Msg & NL & "Is this information correct?"

Answer = MsgBox(Msg, 4)	' Show record, confirm.

If Answer = 6 Then	' If Yes

Put FileNum, Index, CustEntry

Index = Index + 1	' Increment record.

End If

Loop

Close FileNum	' Close file.

Msg = "The records you input have been written to a file.  "

Msg = Msg & "Choose OK to remove the test file from your disk."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove test file.

End Sub


UBound Function

See Also	Example

Returns the largest available subscript for the indicated dimension of an array.

Syntax

UBound(array [, dimension])

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.

The UBound function has these parts:

Part	Description

array	Name of an array variable.

dimension	Integer indicating which dimension's upper bound is returned.  Use 1 for the first dimension, 2 for the second dimension, and so on.  If dimension is omitted, 1 is assumed.

UBound returns the values listed in the table below 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

Dim Statement

Global Statement

LBound Function

Option Base Statement

ReDim Statement

Static Statement


UBound Function Example

The example uses the UBound function to determine the upper bounds for a three-dimensional array.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B, C, Msg, NL, TB	' Declare variables.

Dim Array()	' Declare array variable.

NL = Chr(10): TB = Chr(9)	' Define newline, tab.

' Generate some random dimensions between 2 and 10 for array size.

A = -Int(9 * Rnd + 2)	' First dimension.

B = Int(9 * Rnd + 2)	' Second dimension.

C = Int(9 * Rnd + 2)	' Third dimension.

ReDim Array(A To 20, B to 20 , C to 20)	' Set dimensions.

Msg = "The test array has the following lower bounds: " & NL

Msg = Msg & TB & "Dimension 1 = " & UBound(Array, 1) & NL

Msg = Msg & TB & "Dimension 2 = " & UBound(Array, 2) & NL

Msg = Msg & TB & "Dimension 3 = " & UBound(Array, 3)

MsgBox Msg	' Display message.

End Sub


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


Abs Function

See Also	Example

Returns the absolute value of a number.

Syntax

Abs(number)

Remarks

The argument number can be any valid numeric expression.  The absolute value of a number is its unsigned magnitude.  For example, ABS(-1) and ABS(1) both return 1.

The data type of the return value is the same as that of the number argument.  However, if number is a Variant of VarType 8 (String) and can be converted to a number, the return value will be a Variant of VarType 5 (Double).  If the numeric expression results in a Null, Abs returns a Null.


See Also

Math Functions


Abs Function Example

The example finds the approximate value for a cube root.  It uses Abs to determine the absolute difference between two numbers.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, Precision, Value, X, X1, X2	' Declare variables.

Precision = .00000000000001

Value = InputBox("Enter a value: ")	' Prompt for input.

X1 = 0: X2 = Value	' Make first two guesses.

' Loop until difference between guesses is less than precision.

Do Until Abs(X1 - X2) < Precision

X = (X1 + X2) / 2

If X * X * X - Value < 0 Then	' Adjust guesses.

X1 = X

Else

X2 = X

End If

Loop

Msg = "The cube root of " & Value & " is "

Msg = Msg & X & "."

MsgBox Msg	' Display message.

End Sub


Atn Function

See Also	Example

Returns the arctangent of a number.

Syntax

Atn(number)

Remarks

The argument number can be any valid numeric expression.

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

The result is expressed in radians and is in the range -Pi/2 to Pi/2 radians.  Pi is approximately 3.141593.

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

Cos Function

Sin Function

Tan Function

Math Functions

Derived Math Functions


Atn Function Example

The example uses Atn to calculate Pi.  By definition, Atn(1) is 45 degrees; 180 degrees equals Pi radians.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, Pi	' Declare variables.

Pi = 4 * Atn(1)	' Calculate Pi.

Msg = "Pi is equal to " & Pi

MsgBox Msg	' Display results.

End Sub


Cos Function

See Also	Example

Returns the cosine of an angle.

Syntax

Cos(angle)

Remarks

The argument angle can be any valid numeric expression measured in radians.

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.  Pi is approximately 3.141593.


See Also

Atn Function

Sin Function

Tan Function

Math Functions

Derived Math Functions


Cos Function Example

The example uses Cos to calculate the cosine of an angle with a user-specified number of degrees.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Degrees, Msg, Pi, Radians	' Declare variables.

Pi = 4 * Atn(1)	' Calculate Pi.

Degrees = InputBox("Enter an angle in degrees.")	' Get user input.

Radians = Degrees * (Pi / 180)	' Convert to radians.

Msg = "The cosine of a " & Degrees

Msg = Msg & " degree angle is "

Msg = Msg & Cos(Radians) & "."

MsgBox Msg	' Display results.

End Sub


Exp Function

See Also	Example

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

Syntax

Exp(number)

Remarks

If the value of number exceeds 709.782712893, an Overflow 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

Log Function

Math Functions

Derived Math Functions


Exp Function Example

The example uses Exp to calculate the value of e.  Exp(1) is e raised to the power of 1.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

' Exp(x) is e ^x so Exp(1) is e ^1 or e.

Dim Msg, ValueOfE	' Declare variables.

ValueOfE = Exp(1)	' Calculate value of e.

Msg = "The value of e is " & ValueOfE

MsgBox Msg	' Display message.

End Sub


Int, Fix Functions

See Also	Example

Return the integer portion of a number.

Syntax

Int(number)

Fix(number)

Remarks

The argument number can be any valid numeric expression.  Both Int and Fix remove the fractional part of number and return the resulting integer value.

The data type of the return value is the same as that of the number argument.  However, if number is a Variant of VarType 8 (String) that can be converted to a number, the return type will be a Variant of VarType 5 (Double).  If the numeric expression results in a Null, Int and Fix return a Null.

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

Data Type Conversion Functions

Math Functions


Int Function, Fix Function Example

The example illustrates the difference between Int and Fix.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL, TB	' Declare variables.

NL = Chr(13) & Chr(10): TB = Chr(9)	' Define newline, tab.

Msg = "Int(-99.8) returns" & TB & Int(-99.8)

Msg = Msg & TB & "Fix(-99.8) returns" & TB & Fix(-99.8)

Msg = Msg & NL & "Int(-99.2) returns" & TB & Int(-99.2)

Msg = Msg & TB & "Fix(-99.2) returns" & TB & Fix(-99.2)

MsgBox Msg	' Display message.

End Sub


Log Function

See Also	Example

Returns the natural logarithm of a number.

Syntax

Log(number)

Remarks

The argument number can be any valid numeric expression that results in a value greater than 0.  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 Function procedure that calculates base-10 logarithms:

Static Function Log10(X)

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

End Function


See Also

Exp Function

Math Functions

Derived Math Functions


Log Function Example

The example calculates the value of e, then uses the Log function to calculate the natural logarithm of e to the first, second, and third powers.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, Msg, NL	' Declare variables.

NL = Chr(13) & Chr(10)	' Define newline.

Msg = Exp(1) & NL

For I = 1 To 3	' Do three times.

Msg = Msg & Log(Exp(1) ^ I) & NL

Next I

MsgBox Msg	' Display message.

End Sub


Randomize Statement

See Also	Example

Initializes the random-number generator.

Syntax

Randomize [number]

Remarks

The argument number can be any valid numeric expression.  Number is used to initialize the random-number generator by giving it a new seed value.  If you omit number, the value returned by the Timer function is used as the new seed value.

If Randomize is not used, the Rnd function returns the same sequence of random numbers every time the program is run.  To have the sequence of random numbers change each time the program is run, place a Randomize statement with no argument at the beginning of the program.


See Also

Rnd Function

Timer Function


Randomize Statement Example

The example simulates rolling a pair of dice by generating random values from 1 to 6.  Each time this program is run, Randomize uses the Timer function to generate a new random-number sequence.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Dice1, Dice2, Msg	' Declare variables.

Randomize	' Seed random number generator.

Dice1 = Int(6 * Rnd + 1)	' Generate first die value.

Dice2 = Int(6 * Rnd + 1)	' Generate second die value.

Msg = "You rolled a " & Dice1

Msg = Msg & " and a " & Dice2

Msg = Msg & " for a total of "

Msg = Msg & (Dice1 + Dice2) & "."

MsgBox Msg	' Display message.

End Sub


Rnd Function

See Also	Example

Returns a random number.

Syntax

Rnd[(number)]

Remarks

The argument number can be any valid numeric expression.

The Rnd function returns a Single value less than 1 but greater than or equal to 0.

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

Value of number	Number returned

< 0	The same number every time, as determined by number.

> 0	The next random number in the sequence.

= 0	The number most recently generated.

number omitted	The next random number in the sequence.

The same random-number sequence is generated every time the program is run because each successive call to the Rnd function uses the previous random number as a seed for the next number in the random-number sequence.

To have the program generate a different random-number sequence each time it is run, use the Randomize statement without an argument to initialize the random-number generator before Rnd is called.

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.


See Also

Randomize Statement

Math Functions


Rnd Function Example

The example uses the Rnd function to simulate rolling a pair of dice by generating random values from 1 to 6.  Each time this program is run, Randomize uses the Timer function to generate a new random-number sequence.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Dice1, Dice2, Msg	' Declare variables.

Randomize	' Seed random number generator.

Dice1 = Int(6 * Rnd + 1)	' Generate first die value.

Dice2 = Int(6 * Rnd + 1)	' Generate second die value.

Msg = "You rolled a " & Dice1

Msg = Msg & " and a " & Dice2

Msg = Msg & " for a total of "

Msg = Msg & (Dice1 + Dice2) & "."

MsgBox Msg	' Display message.

End Sub


Sgn Function

See Also	Example

Returns an integer indicating the sign of a number.

Syntax

Sgn(number)

Remarks

The argument number can be any valid numeric expression.  Its sign determines the value returned by the Sgn function:

If number > 0, then Sgn(number) returns 1.

If number = 0, then Sgn(number) returns 0.

If number < 0, then Sgn(number) returns -1.


See Also

Math Functions


Sgn Function Example

The example uses Sgn to determine the sign of a number.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, Number	' Declare variables.

Number = InputBox("Enter a number.")	' Get user input.

Select Case Sgn(Number)	' Evaluate user input.

Case 0	' Zero.

Msg = "You entered zero."

Case 1	' Positive.

Msg = "You entered a positive number."

Case -1	' Negative.

Msg = "You entered a negative number."

End Select

MsgBox Msg	' Display results.

End Sub


Sin Function

See Also	Example

Returns the sine of an angle.

Syntax

Sin(angle)

Remarks

The argument angle can be any valid numeric expression measured in radians.

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.  Pi is approximately 3.141593.


See Also

Atn Function

Cos Function

Tan Function

Math Functions

Derived Math Functions


Sin Function Example

The example uses Sin to calculate the sine of an angle with a user-specified number of degrees.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Degrees, Msg, Pi, Radians	' Declare variables.

Pi = 4 * Atn(1)	' Calculate Pi.

Degrees = InputBox("Enter an angle in degrees.")	' Get user input.

Radians = Degrees * (Pi / 180)	' Convert to radians.

Msg = "The sine of a " & Degrees

Msg = Msg & " degree angle is "

Msg = Msg & Sin(Radians) & "."

MsgBox Msg	' Display results.

End Sub


Sqr Function

See Also	Example

Returns the square root of a number.

Syntax

Sqr(number)

Remarks

The argument number can be any valid numeric expression that results in a value greater than or equal to 0.

The return type of Sqr function is Double.


See Also

Math Functions


Sqr Function Example

The example uses Sqr to calculate the square root of a user-supplied number.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, Number	' Declare variables.

Msg = "Enter a non-negative number."

Number = InputBox(Msg)	' Get user input.

If Number < 0 Then

Msg = "Cannot determine the square root of a negative number."

Else

Msg = "The square root of " & Number & " is "

Msg = Msg & Sqr(Number) & "."

End If

MsgBox Msg	' Display results.

End Sub


Tan Function

See Also	Example

Returns the tangent of an angle.

Syntax

Tan(angle)

Remarks

The argument angle can be any valid numeric expression measured in radians.

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

Tan returns a Double.  If the return value is too large, an Overflow error occurs.

To convert degrees to radians, multiply degrees by Pi/180.  To convert radians to degrees, multiply radians by 180/Pi.  Pi is approximately 3.141593.


See Also

Atn Function

Cos Function

Sin Function

Math Functions

Derived Math Functions


Tan Function Example

The example uses Tan to calculate the tangent of an angle with a user-specified number of degrees.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Degrees, Msg, Pi, Radians	' Declare variables.

Pi = 4 * Atn(1)	' Calculate Pi.

Degrees = InputBox("Enter an angle in degrees.")	' Get user input.

Radians = Degrees * (Pi / 180)	' Convert to radians.

Msg = "The tangent of a " & Degrees

Msg = Msg & " degree angle is "

Msg = Msg & Tan(Radians) & "."

MsgBox Msg	' Display results.

End Sub


Derived Math Functions

The following is a list of nonintrinsic mathematical functions that can be derived from the intrinsic math functions provided with Visual Basic:

Function	Visual Basic equivalent

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)) + 1.5708

Inverse Secant	Arcsec(X) = Atn(X / Sqr(X * X - 1)) + Sgn(Sgn(X) -1) * 1.5708

Inverse Cosecant	Arccosec(X) = Atn(X/Sqr(X * X - 1)) + (Sgn(X) - 1) * 1.5708

Inverse Cotangent	Arccotan(X) = Atn(X) + 1.5708

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	LogN(X) = Log(X) / Log(N)


ChDir Statement

See Also	Example

Changes the current default directory on a specified drive.

Syntax

ChDir path

Remarks

The argument path is a string expression that identifies which directory becomes the new default directory.  This argument must contain fewer than 128 characters and has the following syntax:

[drive:] [ \ ]directory[\directory] . . .

The argument drive is an optional drive specification; the argument directory is a directory name.  If you omit drive, ChDir changes the default directory on the current drive.

The ChDir statement works like the operating system command CHDIR, except that it cannot be abbreviated to CD like the system command.  Like the operating system command CHDIR, 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"

Use the CurDir[$] function to determine the current directory and the ChDrive statement to change the default drive.


See Also

ChDrive Statement

CurDir, CurDir$ Functions

Dir, Dir$ Functions

MkDir Statement

RmDir Statement


ChDir Statement Example

The example uses ChDir to change the default directory on the current drive.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Answer, Msg, NL	' Declare variables.

NL = Chr(10)	' Define newline.

CurPath = CurDir	' Get current path.

ChDir "\"

Msg = "The current directory has been changed to "

Msg = Msg & CurDir & NL & NL & "Press OK to change back "

Msg = Msg & "to your previous default directory."

Answer = MsgBox(Msg)	' Get user response.

ChDir CurPath	' Change back to user default.

Msg = "Directory changed back to " & CurPath & "."

MsgBox Msg	' Display results.

End Sub


ChDrive Statement

See Also	Example

Changes the current drive.

Syntax

ChDrive drive

Remarks

The argument drive is a string expression that specifies a new default drive.  It corresponds to an existing drive and must be in the range A to lastdrive, where lastdrive is the maximum drive letter you set in your CONFIG.SYS file.

If you supply a zero-length argument (""), the current drive doesn't change.  If the argument drive is a multiple-character string, ChDrive uses only the first letter.

Use the CurDir[$] function to determine the current drive and directory and the ChDir statement to change the default directory.


See Also

ChDir Statement

CurDir, CurDir$ Functions

MkDir Statement

RmDir Statement


ChDrive Statement Example

The example changes the currently logged drive to the new drive indicated by the letter entered by the user.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

On Error Resume Next

Dim CurPath, Drive, HasColon, Msg, NewDrive, NL	' Declare variables

NL = Chr(10)	' Define newline.

CurPath = CurDir	' Get current path.

If Err = 68 Then	' In case current

Drive = "invalid."	' drive is invalid

Err = 0	' reset error to 0.

Else

Drive = Left(CurPath, 2)	' Get drive letter.

End If

Msg = "Your currently logged drive is " & Drive & NL & NL

Msg = Msg & "Enter the letter of another drive to make the "

Msg = Msg & "logged drive."

NewDrive = InputBox(Msg)	' Prompt for new drive.

HasColon = InStr(1, NewDrive, ":")	' Check for colon.

' If there is no colon, append one to NewDrive.

If Not HasColon Then NewDrive = Left(NewDrive, 1) & ":"

ChDrive NewDrive	' Change drive.

Select Case Err

Case 68	' Device unavailable error.

Msg = "That drive is not available. No drive change "

Msg = Msg & "was made."

Case 71	' Disk not ready error.

Msg = "Close the door on your drive and try again."

Case 5	' Illegal function call.

Msg = "You probably didn't enter a drive letter. No drive "

Msg = Msg & "change was made."

Case Else

Msg = "Drive changed to " & UCase(NewDrive)

End Select

MsgBox Msg	' Display results.

End Sub


Command, Command$ Function

Example

Returns the argument portion of the command line used to launch Microsoft Visual Basic.

Syntax

Command[$]

Remarks

Command returns a Variant; Command$ returns a String.

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 (compiled to an .EXE file), Command[$] returns any argument(s) that appears after the name of the application on the command line.  For example:

myapp  cmdlineargs

In the code window, you can change the text returned by Command[$] by choosing Project from the Options menu.


Command, Command$ Functions Example

The example uses Command to display the arguments on the command line.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variable.

If Command = "" Then	' If no command line.

Msg = "There is currently no command-line string."

Else	' Put command line into message.

Msg = "The command-line string is: '" & Command & "'"

End If

MsgBox Msg	' Display message.

End Sub


CurDir, CurDir$ Function

See Also	Example

Returns the current path for the specified drive.

Syntax

CurDir[$] [(drive)]

Remarks

CurDir returns a Variant; CurDir$ returns a String.

The argument drive is a string expression that specifies a drive in the range A to lastdrive, where lastdrive is the maximum drive letter you set in your CONFIG.SYS file.

If no drive is specified or if drive is zero-length, CurDir[$] returns the path for the current drive.  This is similar to using the CHDIR command at the system prompt without specifying a path.

An error occurs if the first character in drive lies outside the range A to lastdrive.  An error also occurs if the first character in drive is not a letter, or if it corresponds to a drive that doesn't exist.


See Also

ChDir Statement

ChDrive Statement

MkDir Statement

RmDir Statement


CurDir, CurDir$ Functions Example

The example uses CurDir to return the name of the current directory.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL	' Declare variables.

NL = Chr(10)	' Define newline.

Msg = "The current directory is: "

Msg = Msg & NL & CurDir	' Get current directory.

MsgBox Msg	' Display message.

End Sub


Dir, Dir$ Functions

See Also	Example

Returns the name of a file or directory that matches a specified pattern and file attribute.  Also can return the volume label of a drive.

Syntax

Dir[$] [(filespec [,attrmask])]

Remarks

Dir returns a Variant; Dir$ returns a String.

The Dir[$] function has these parts:

Part	Description

filespec	String expression that specifies a path or file name.  The path and file name can include a drive specification and any valid wildcard characters.

attrmask	Specifies the attributes (Hidden, System, and so on) of the file names you want returned.  If attrmask is not specified, Dir[$] returns all normal files (those without hidden, system, directory, or volume label attributes) that match filespec.  You can add to the list of file names returned by Dir[$] by specifying a value for attrmask that includes directories, and hidden or system files.  In addition, you can specify that Dir[$] return the label of the volume whose drive is specified as part of filespec, or the currently selected drive if no drive is explicitly specified.  If attrmask specifies the volume label, all other attributes are ignored.  The attrmask is created by summing the values, shown in the table below, to identify the particular file attribute(s) you want included.

Symbolic Constant	Value	Meaning
ATTR_NORMAL	0	Normal files
ATTR_HIDDEN	2	Hidden files
ATTR_SYSTEM	4	System files
ATTR_VOLUME	8	Volume label
ATTR_DIRECTORY	16	Directory
Note	Symbolic constants for attribute definitions can be found in the Visual Basic file CONSTANT.TXT.  When placed in any module in a project, the symbolic names can be used in all your form and code modules.

You must specify filespec the first time you call the function, or an error occurs.  If you also specify file attributes, attrmask can only be included in the same call to Dir[$] where filespec is included.  Dir[$] returns the first file name that matches filespec.  To get any additional file names that match filespec, call Dir[$] again with no arguments.  When no more file names match, Dir[$] returns a zero-length String or Variant of VarType 8.  Once a zero-length String or Variant has been returned, you must again use a filespec argument in subsequent calls or an error occurs.

Note	You can change to a new filespec without retrieving all of the file names that match the current filespec.  However, you cannot recursively call the Dir[$] function.

Tip	Because file names are retrieved in no particular order, you may want to store returned file names in an array and then sort the array.


See Also

ChDir Statement

CurDir, CurDir$ Functions


Dir, Dir$ Functions Example

The example uses Dir to determine all the subdirectories on drive C.  To try this example, paste the code into the Declarations section of a form containing a list box named List1.  Then press F5 and click the form.

Const ATTR_DIRECTORY = 16	' Declare form constant.

Sub Form_Click ()

ListSubDirs "C:\"	' Call ListSubDirs

End Sub

Sub ListSubDirs (Path)

Dim Count, D(), I, DirName	' Declare variables.

DirName = Dir(Path, ATTR_DIRECTORY)	' Get first directory name.

'Iterate through PATH, caching all subdirectories in D()

Do While DirName <> ""

If DirName <> "." And DirName <> ".." Then

If GetAttr(Path + DirName) And ATTR_DIRECTORY = ATTR_DIRECTORY Then

If (Count Mod 10) = 0 Then

ReDim Preserve D(Count + 10)	' Resize the array.

End If

Count = Count + 1	' Increment counter.

D(Count) = DirName

End If

End If

DirName = Dir	' Get another directory name.

Loop

' Now recursively iterate through each cached subdirectory.

For I = 1 To Count

List1.AddItem Path & D(I)	' Put name in list box.

ListSubDirs Path & D(I) & "\"

Next I

End Sub


Environ, Environ$ Function

Example

Returns the string associated with an operating system environment variable.

Syntax 1

Environ[$](environmentstring)

Syntax 2

Environ[$](n)

Remarks

Environ returns a Variant; Environ$ returns a String.

The Environ[$] function has these parts:

Part	Description

environmentstring	String expression containing the name of an environment variable.

n	Numeric expression corresponding to the nth string of the environment-string table. The argument n can be any numeric expression, but it is rounded to an integer before it is evaluated.

If the environment variable name you specify cannot be found in the environment-string table, a zero-length String or Variant of VarType 8 is returned.  Otherwise, Environ[$] returns the text assigned to the specified environment variable (the text following the equal sign in the environment-string table for that environment variable.)

If you specify a numeric argument (n), the nth string of the environment-string table is returned.  In this case, Environ[$] returns all of the text, including environmentstring.  If the nth string doesn't exist, Environ[$] returns a zero-length String or Variant of VarType 8.


Environ, Environ$ Functions Example

The example uses Environ to supply the entry number and length of the PATH statement from the environment-string table.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim EnvString, Indx, Msg, PathLen	' Declare variables.

Indx = 1	' Initialize index to 1.

Do

EnvString = Environ(Indx)	' Get environment variable.

If Left(EnvString, 5) = "PATH=" Then	' Check PATH entry.

PathLen = Len(Environ("PATH"))	' Get length.

Msg = "PATH entry = " & Indx & " and length = " & PathLen

Exit Do

Else

Indx = Indx + 1	' Not PATH entry, so increment.

End If

Loop Until EnvString = ""

If PathLen > 0 Then

MsgBox Msg	' Display message.

Else

MsgBox "No PATH environment variable exists."

End If

End Sub


Kill Statement

See Also	Example

Deletes files from a disk.

Syntax

Kill filespec

Remarks

The Kill statement is similar to the operating system commands ERASE and DEL.

Kill only deletes disk files.  To delete directories, use the Visual Basic RmDir statement.

Using Kill to delete a file that is currently open by Visual Basic produces an error.

Caution	Be extremely careful using wildcard characters with Kill.  You can delete more files than you intended.


See Also

RmDir Statement


Kill Statement Example

The example uses Kill to remove a file the user specifies.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Ansr, DelFile, Msg	' Declare variables.

On Error GoTo Errhandler	' Set up error handler.

DelFile = UCase(InputBox("Enter file name you want deleted."))

If Len(DelFile) Then	' Check for entry.

Ansr = MsgBox("Sure you want to delete " & DelFile & "?", 4)

If Ansr = 6 Then	' User chose "Yes."

Msg = "Deleting " & DelFile & " from your disk."

Kill DelFile	' Delete file from disk.

Else

Msg = DelFile & " was not deleted."

End If

Else

Msg = "You didn't enter a file name."

End If

MsgBox Msg	' Display message.

End

Errhandler:

If Err = 53 Then	' Error 53 is "File not Found".

Msg = "Sorry, the file you named could not be found."

Else

Msg = "Sorry, unable to delete file."

End If

Resume Next

End Sub


MkDir Statement

See Also	Example

Creates a new directory.

Syntax

MkDir pathname

Remarks

The argument pathname is a string expression that specifies the name of the directory to be created.  This argument must contain fewer than 128 characters and has the following syntax:

[drive:] [ \ ]directory[\directory] . . .

The argument drive is an optional drive specification; the argument directory is a directory name.

The MkDir statement works like the operating system command MKDIR, except that it cannot be abbreviated to MD like the system command.

If you use MkDir to create a directory whose name contains an embedded space, you may be able  to access it with some applications, but you can't remove it using standard operating system commands.  To remove such a directory, use the RmDir statement from within Visual Basic or a Visual Basic application.


See Also

ChDir Statement

CurDir, CurDir$ Functions

RmDir Statement


MkDir Statement Example

The example uses the MkDir statement  to create a \TMP subdirectory off the root directory of the currently logged drive.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Ansr, CurDrv, Msg, TmpPath	' Declare variables.

On Error Resume Next	' Set up error handler.

CurDrv = Left(CurDir, 2)	' Get current drive letter.

TmpPath = UCase(CurDrv + "\tmp")	' Make path specification.

MkDir TmpPath	' Make new directory.

If Err = 75 Then	' Check if directory exists.

Msg = TmpPath & " directory already exists."

Else

Msg = TmpPath & " directory created."

End If

Msg = Msg & " Do you want it removed?"

Ansr = MsgBox(Msg, 4)	' Display message and get

If Ansr <> 7 Then RmDir TmpPath	' user response.

End Sub


Name Statement

See Also	Example

Changes the name of a disk file or directory.

Syntax

Name oldfilespec As newfilespec

Remarks

The Name statement is similar to the operating system RENAME command, but Name can also be used to change the name of a directory.  Using Name, you can move a file from one directory to another, but you can't move a directory.

The arguments oldfilespec and newfilespec are string expressions, each of which contains a file name and an optional path.  If the path in newfilespec exists and is different from the path in oldfilespec, the Name statement moves the file to the new directory and renames the file if necessary.  If newfilespec and oldfilespec have different paths and the same file name, Name moves the file to the new directory and leaves the file name unchanged.

The file specified by oldfilespec must exist and the file specified by newfilespec cannot already exist.  Both newfilespec and oldfilespec must be on the same drive.

Using Name on a file currently open by Visual Basic produces an error.  You must close an open file before renaming it.


See Also

Kill Statement


Name Statement Example

The example moves a file from one directory to another and renames it at the same time.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim FName1, FName2, Msg, NL, TestDir	' Declare variables.

NL = Chr(10)	' Define newline.

FName1 = "NMSTMTX.DAT"	' Define filenames.

FName2 = "NMSTMTY.DAT"

TestDir = "\TEST.DIR"	' Test directory name.

Open FName1 For Output As #1	' Create a test file.

Print #1, "test data"	' Put something in file.

Close #1

MkDir TestDir	' Make test directory.

Name FName1 As TestDir & "\" & FName2	' Move and rename.

Msg = "A new file, " & FName1 & " has been created "

Msg = Msg & "in " & CurDir$ & ". Once created, it was "

Msg = Msg & "moved to " & TestDir & " and renamed "

Msg = Msg & FName2 & "." & NL & NL

Msg = Msg & "Choose OK to remove the test data file and "

Msg = Msg & "directory."

MsgBox Msg	' Display message.

Kill TestDir & "\" & FName2	' Remove file from disk.

RmDir TestDir	' Remove test directory.

End Sub


RmDir Statement

See Also	Example

Removes an existing directory.

Syntax

RmDir path

Remarks

The argument path is a string expression that specifies the name of the directory to be removed.  This argument must have fewer than 128 characters and has the following syntax:

[drive:] [ \ ]directory[\directory] . . .

The argument drive is an optional drive specification; the argument directory is a directory name.

The RmDir statement works like the operating system command RMDIR, except that it cannot be abbreviated to RD like the system command.  If the directory to be removed contains anything except the working directory ( '.' ) and the parent directory ( '..' ), an error occurs.


See Also

ChDir Statement

CurDir, CurDir$ Functions

MkDir Statement


RmDir Statement Example

The example uses the RmDir statement to remove a previously created directory at the user's request.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Const MB_YESNO = 4	' Yes and No buttons

Const IDNO = 7	' No response

Dim Ansr, CurDrv, Msg, TmpPath	' Declare variables.

On Error Resume Next	' Set up error handler.

CurDrv = Left(CurDir, 2)	' Get current drive letter.

TmpPath = UCase(CurDrv + "\tmp")	' Make path specification.

MkDir TmpPath	' Make new directory.

If Err = 75 Then	' Check if directory exists.

Msg = TmpPath & " directory already exists."

Else

Msg = TmpPath & " directory created."

End If

Msg = Msg & " Do you want it removed?"

Ansr = MsgBox(Msg, MB_YESNO)	' Display message box and get

If Ansr <> IDNO Then RmDir TmpPath	' user response.

End Sub


Err, Erl Functions

See Also	Example

Returns error status.

Syntax

Err

Erl

Remarks

After an error occurs, the Err function returns an Integer run-time error code identifying the error.  The Erl function returns a Long that is the line number of the line in which the error occurred or the line most closely preceding it.

Because Err and Erl return meaningful values only after an error has occurred, they are usually used in error-handling routines to determine the error and the corrective action.  Both Err and Erl are reset to 0 after any form of the Resume or On Error statement and after an Exit Sub or Exit Function statement within an error-handling routine.

Caution   If you set up an error handler using On Error GoTo and that error handler calls another procedure, the value of Err and Erl may be reset to 0.  To make sure that the value doesn't change, assign the values of Err or Erl to variables before calling another procedure or before executing Resume, On Error, Exit Sub, or Exit Function.

You can directly set the value returned by the Err function using the Err statement.  You can set the values for both Err and Erl indirectly using the Error statement.

The Erl function returns only a line number, not a line label, located at or before the line producing the error.  Line numbers greater than 65,529 are treated as line labels and can't be returned by Erl.  If your procedure has no line numbers, or if there is no line number before the point at which an error occurs, Erl returns 0.


See Also

Err Statement

Error Statement

On Error Statement

Resume Statement

Trappable Errors


Err, Erl Functions Example

The example shows an error-handling routine.  If there are no additional errors, Err returns error number 11 (Division by zero) and Erl returns line 1030.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

1000  Dim A, B, C	' Declare variables.

1010  On Error GoTo ErrHandler	' Set up an error handler.

1020  B = 1

1030  A = B \ C	' Cause a "Division by zero" error.

1040  Exit Sub

ErrHandler:	' Error handler line label.

MsgBox "Error number " & Err & " occurred at line " & Erl

Resume Next

End Sub


Err Statement

See Also	Example

Sets Err to a specific value.

Syntax

Err = n

Remarks

The argument n is either an integer between 1 and 32,767, inclusive, that specifies a run-time error code or 0, which means no run-time error has occurred.

When running an application, Visual Basic uses Err to record whether or not a run-time error has occurred and what the error was.

Use the Err statement to set Err to a nonzero, integer value to communicate error information between procedures.  For example, you might use one of the run-time error codes not used by Visual Basic as an application-specific error code.  To determine which error codes are being used, use the Error[$] function and/or the Error statement.  You can create application-specific user-defined errors by working down from error code 32,767.

You can also set Err to 0 by using any form of the Resume or On Error statement or by executing an Exit Sub or Exit Function statement within an error handler.  In addition, the Error statement can set Err to any value to simulate any run-time error.


See Also

Err, Erl Functions

Error, Error$ Functions

Error Statement


Err Statement Example

As the example shows, with On Error Resume Next, errors are often handled in the lines of code immediately following the line where an error can occur.  Once the error has been handled, the Err statement clears the error by setting Err to 0 so subsequent error-handling code isn't inadvertently executed for an earlier error.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim FileName	' Declare variable.

On Error Resume Next	' Set up error handler.

FileName = InputBox("Enter a file name: ")	' Get file name.

Do

Err = 0	' Clear any error.

Open FileName For Input As #1 	' Open file.

Select Case Err	' Handle error, if any.

Case 0	' No error.

MsgBox UCase(FileName) & " was found."	' File found.

Case 53, 75, 76	' Assorted file errors.

FileName = InputBox("File was not found. Try again.")

Case 52, 64	' Bad file name or number.

FileName = InputBox("File name was invalid. Try again.")

Case 68	' Device unavailable.

FileName = InputBox("Device is not available. Try again.")

Case 71	' Drive not ready.

MsgBox "Close the drive door."

Case Else	' Handle other cases.

MsgBox "ERROR: Cannot continue!"	' All fatal errors.

Stop

End Select

Loop Until Err = 0

Close #1

End Sub


Error, Error$ Function

See Also	Example

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

Syntax

Error[$][(errorcode)]

Remarks

Error returns a Variant; Error$ returns a String.

The argument errorcode must be an integer between 1 and 32,767, inclusive.  If errorcode is omitted, the message string corresponding to the most recent run-time error is returned.  If errorcode is not defined in Visual Basic, the returned message string is User-defined error.

Some error messages use internal variables to provide specific information about an error.  When an error occurs, words appropriate to the context of the error are substituted in the error message string.  Under normal circumstances, the following error message appears with a control array element index number inserted between the single quotation marks:

Control array element '11' doesn't exist

However, when you use Error[$] to return an error message for a specified error code, there is no context for that error message and the appropriate text can't be inserted.  As a result, the message string returned by Error[$] contains no context-specific information between the single quotation marks.  A space is inserted in lieu of the actual context information.

If Error[$] is called with no argument, it returns the message string for the most recent run-time error.  If a run-time error has occurred, the returned message string includes substitutions appropriate to the context of the error.  If no run-time error has occurred, Error[$] returns a zero-length string ("").

The Err function returns the error code for the most recent run-time error.  Therefore, the following lines are equivalent except that in the first case, the text placed in A includes appropriate substitutions, and in the second case, no substitutions are made.

A = Error

A = Error(Err)


See Also

Err, Erl Functions

Error Statement

Trappable Errors


Error, Error$ Functions Example

The example uses the Error function to display error messages associated with user-input error numbers.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL, UserError	' Declare variables.

On Error GoTo ErrorHandler	' Set up error handler.

NL = Chr(10)	' Define newline.

Msg = "Please enter an error number to see the associated error"

Msg = Msg & " message."

UserError = InputBox(Msg)

Error UserError	' Simulate error occurrence.

Exit Sub

ErrorHandler:	' Error handler line label.

Msg = "The error message for error number "

Msg = Msg & Err & " is:" & NL & NL

Msg = Msg & """" & Error(Err) & """"

MsgBox Msg	' Display message.

Resume Next

End Sub


Error Statement

See Also	Example

Simulates the occurrence of an error; can be used to generate a user-defined error.

Syntax

Error errorcode

Remarks

The argument errorcode must be an integer between 1 and 32,767, inclusive.  If errorcode is an error code defined by Visual Basic, the Error statement simulates the occurrence of that error; that is, it sets the value of Err to errorcode.

To define your own error code, use a value that is greater than any used by the standard Visual Basic error codes.  You can create application-specific user-defined errors working down from error code 32,767.

If an Error statement is executed when no error-handling routine is enabled, Visual Basic displays an error message and stops program execution.  If the Error statement specifies an error code that is not used by Visual Basic, the message User-defined error is displayed.


See Also

Err, Erl Functions

On Error Statement

Resume Statement

Trappable Errors


Error Statement Example

The example uses the Error statement to simulate the occurrence of an error so that the error handler is invoked and the associated error message is displayed.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL, UserError	' Declare variables.

On Error GoTo ErrorHandler	' Set up error handler.

NL = Chr(10)	' Define newline.

Msg = "Please enter an error number to see the associated error"

Msg = Msg & " message."

UserError = InputBox(Msg)

Error UserError	' Simulate error occurrence.

Exit Sub

ErrorHandler:	' Error handler line label.

Msg = "The error message for error number "

Msg = Msg & Err & " is:" & NL & NL

Msg = Msg & """" & Error(Err) & """"

MsgBox Msg	' Display message.

Resume Next

End Sub


On Error Statement

See Also	Example

Enables an error-handling routine and specifies the location of the routine within a procedure; can be used to disable an error-handling routine.

Syntax

On Error { GoTo line | Resume Next | GoTo 0 }

Remarks

If you don't use an On Error statement, any run-time error that occurs is fatal; that is, Visual Basic generates an error message and stops program execution.

The On Error statement has these parts:

Part	Description

GoTo line	Enables the error-handling routine that starts at line (a line label or a line number).  Thereafter, if a run-time error occurs, program control branches to line.  The specified line must be in the same procedure as the On Error statement.  If it isn't, a compile-time error occurs.

Resume Next	Specifies that when a run-time error occurs, control goes to the statement immediately following the statement in which the error has occurred. In other words, the code continues to execute.  You can use the Err function in subsequent lines of code to obtain the run-time error number.

GoTo 0	Disables any enabled error handler in the current procedure.

An error handler is enabled when it is referred to by an On Error GoTo line statement.  Once an error handler is enabled, any run-time error causes program control to jump to the enabled error-handling routine and makes the error handler active.  An error handler remains active from the time a run-time error has been trapped until a Resume, Exit Sub, or Exit Function statement is executed in the error handler.

If an error occurs while an error handler is active (between the occurrence of the error and the execution of a Resume, Exit Sub, or Exit Function statement), the current procedure's error handler cannot handle the error.  If the calling procedure has an enabled error handler, control is returned to the calling procedure and its error handler is activated to handle the error.  If the calling procedure's error handler also is active, control is passed back through any previous calling procedures until an inactive error handler is found.  If no inactive 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 the calling procedure, that procedure becomes the current procedure.  Once an error is handled by an error handler in any procedure, program execution resumes in the current procedure at the point designated by the Resume statement.

Notice that an error-handling routine is not a Sub or Function procedure. It is a block of code marked by a line label or line number.

Error-handling routines rely on the value in Err to determine the cause of the error.  The error-handling routine should test or save this value before any other error can occur or before a procedure that could cause an error is called.  The value in Err reflects only the most recent error.  You can use the Error[$] function to return the error message associated with any given run-time error number returned by Err.

On Error Resume Next causes program execution to continue with the statement immediately following the statement that caused the run-time error.  This allows your program to continue despite a run-time error and then check for the cause of the error.  This also lets you build the error-handling routine in line with the procedure rather than transferring control to another location within the procedure.

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 executing when no error has occurred, place an Exit Sub or Exit Function statement immediately ahead of the error-handling routine, as in the following example:

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 partition it from the normal execution flow of the procedure.  This is by no means the only solution.  Error-handling code can be placed anywhere in a procedure.


See Also

Err, Erl Functions

Error, Error$ Functions

Resume Statement

Trappable Errors


On Error Statement Example

The example uses the On Error statement to set up error handling in a procedure.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Drive, Msg	' Declare variables.

On Error GoTo ErrorHandler	' Set up error handler.

Msg = "This demo attempts to open a file that does not exist on a "

Msg = Msg & "drive that may not exist. When the operation fails, "

Msg = Msg & "the ErrorHandler routine will display a message box "

Msg = Msg & "that indicates what error occurred."

MsgBox Msg	' Display opening message.

Drive = Chr(Int((26) * Rnd + 1) + 64)	' Make random drive letter.

Open Drive & ":\TEST\X.DAT" For Input As #1	' Try to open file.

Close #1	' Close the file.

Exit Sub	' Exit before entering

' error  handler.

ErrorHandler:	' Error handler line label.

Select Case Err

Case 53: Msg = "ERROR 53: That file doesn't exist."

Case 68: Msg = "ERROR 68: Drive " & Drive & ": not available."

Case 76: Msg = "ERROR 76: That path doesn't exist."

Case Else: Msg = "ERROR " & Err & " occurred."

End Select

MsgBox Msg	' Display error message.

Resume Next	' Resume procedure.

End Sub


Resume Statement

See Also	Example

Resumes program execution after an error-handling routine is finished.

Syntax

Resume { [0] | Next | line}

Remarks

The various forms of the Resume statement redirect program flow as described below:

Statement	Description

Resume [0]	Program execution resumes with the statement that caused the error or at the most recently executed call out of the procedure containing the error-handling routine.

Resume Next	Execution resumes with the statement immediately following the one that caused the error or with the statement immediately following the most recently executed call out of the procedure containing the error-handling routine.

Resume line	Execution resumes at line, which is a line label or line number.  The argument line must be in the same procedure as the error handler.

Where execution resumes is determined by the location of the error handler in which the error is trapped, not necessarily by the location of the error itself.

The following table summarizes where a program resumes execution when the Resume [0] statement is used:

Where error occurs	Where program resumes

Same procedure as error handler	Statement that caused the error

Different procedure from error handler	Statement that last called out of the procedure containing the error handler

If you use a Resume statement anywhere except in an error-handling routine, an error occurs.

When an error-handling routine is active and the end of the procedure (an End Sub or End Function statement) is encountered before a Resume statement is executed, an error occurs because a logical error is presumed to have been made inadvertently.  However, if an Exit Sub or Exit Function statement is encountered while an error handler is active, no error occurs because it is considered a deliberate redirection of program flow.


See Also

On Error Statement

Trappable Errors


Resume Statement Example

The example uses Resume Next  to end error handling in a procedure.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Drive, Msg	' Declare variables.

On Error GoTo ErrorHandler	' Set up error handler.

Msg = "This demo attempts to open a file that does not exist on a "

Msg = Msg & "drive that may not exist. When the operation fails, "

Msg = Msg & "the ErrorHandler routine will display a message box "

Msg = Msg & "that indicates what error occurred."

MsgBox Msg	' Display opening message.

Drive = Chr(Int((26) * Rnd + 1) + 64)	' Make random drive letter.

Open Drive & ":\TEST\X.DAT" For Input As #1	' Try to open file.

Close #1	' Close the file.

Exit Sub	' Exit before entering

' error  handler.

ErrorHandler:	' Error handler line label.

Select Case Err

Case 53: Msg = "ERROR 53: That file doesn't exist."

Case 68: Msg = "ERROR 68: Drive " & Drive & ": not available."

Case 76: Msg = "ERROR 76: That path doesn't exist."

Case Else: Msg = "ERROR " & Err & " occurred."

End Select

MsgBox Msg	' Display error message.

Resume Next	' Resume procedure.

End Sub


Close Statement

See Also	Example

Concludes input/output (I/O)to a file.

Syntax

Close [[#]filenumber] [,[#]filenumber] . . .

Remarks

The argument filenumber is the number used in the Open statement to open the file.  You can use any numeric expression as long as it evaluates to the number of an open file.

A Close statement with no arguments closes all open files..

The association of a file with filenumber ends when a Close statement is executed.  You then can reopen the file using the same or a different file number, or you can reuse the file number to open a different file.

Using a Close statement for a file that was opened for Output or Append writes the final buffer of output to the operating system buffer for that file.  Close releases all Visual Basic buffer space associated with the closed file.

The Close statement complements the Open statement.


See Also

End Statement

Open Statement

Reset Statement

Stop Statement


Close Statement Example

The example uses Close to close all three files opened for Output.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variable.

Make3Files	' Create data files.

Msg = "Several test files have been created on your disk. "

Msg = Msg & "Choose OK to remove the test files."

MsgBox Msg

Kill "TEST?"	' Remove data files from disk.

End Sub

Sub Make3Files ()

Dim I, FNum, FName	' Declare variables.

For I = 1 To 3

FNum = FreeFile	' Determine next file number.

FName = "TEST" & FNum

Open FName For Output As FNum	' Open file.

Print #I, "This is a test."	' Write string to file.

Next I

Close	' Close all files.

End Sub


FileAttr Function

See Also	Example

Returns file mode or operating system file handle information about an open file.

Syntax

FileAttr(filenumber, attribute)

Remarks

The FileAttr function has these parts:

Part	Description

filenumber	Number used in the Open statement to open the file.  It can be any numeric expression that evaluates to the number of an open file.

attribute	Number that indicates the type of information to return about the file.  Use 2 to return the operating system handle for the file.  Use 1 to return one of the following values used to indicate the file's mode:

Return value	Mode

1	Input

2	Output

4	Random

8	Append

32	Binary


See Also

GetAttr Function

Open Statement

SetAttr Statement


FileAttr Function Example

The example uses FileAttr to report the file handle and mode of an open file.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim FileNum, Handle, Mode, Msg	' Declare variables.

FileNum = FreeFile	' Get available file number.

Open "TESTFILE" For Append As FileNum	' Create sample data file.

Handle = FileAttr(FileNum,2)	' Get file handle.

Select Case FileAttr(FileNum,1)	' Determine mode.

Case 1 : Mode = "Input"

Case 2 : Mode = "Output"

Case 4 : Mode = "Random"

Case 8 : Mode = "Append"

Case 32 : Mode = "Binary"

End Select

Close FileNum	' Close file.

Msg = "The file using DOS file handle " & Handle

Msg  = Msg & " was opened for " & Mode

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Delete zero-length file.

End Sub


FreeFile Function

See Also	Example

Returns the next valid unused file number.

Syntax

FreeFile [( )]

Remarks

Use FreeFile when you need to supply a file number and you want to ensure that the file number is not already in use.


See Also

Open Statement


FreeFile Function Example

The example uses the FreeFile function to return the next available file number.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim NL, FileNum, Msg	' Declare variables.

NL = Chr(10)	' Define newline.

FileNum = FreeFile	' Get unused file number.

Open "TESTFILE" For Output As FileNum	' Create sample data file.

Close FileNum	' Close file.

Msg = "The file number returned by the FreeFile function was "

Msg = Msg & FileNum & "." & NL & NL

Msg = Msg & "Choose OK to remove the created test file."

MsgBox Msg	' Display results.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Get Statement

See Also	Example

Reads from a disk file into a variable.

Syntax

Get [#] filenumber,[recordnumber],variablename

Remarks

The Get statement has these parts:

Part	Description

filenumber	Number used in the Open statement to open the file.  It can be any numeric expression that evaluates to the number of an open file.

recordnumber	The largest possible recordnumber is 2^31 - 1, or 2,147,483,647.  For files opened in Random mode, recordnumber is the number of the record to be read.  For files opened in Binary mode, recordnumber is the byte position at which reading starts.  The first byte in a file is at position 1, the second byte is at position 2, and so on.  If you omit recordnumber, the next record or byte (the one following the last Get or Put statement or the one pointed to by the last Seek function) is read from.  If you omit recordnumber, you must still include the commas.  For example:
Get #4,,FileBuffer

variablename	Name of the variable used to receive input from the file.  Any variable can be used except object variables and array variables (variables that describe an entire array).  However, you can use a variable that describes a single element of an array.

For files opened in Random mode, these 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 still 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 record length match the length of the data being written.

If the variable being read into is a variable-length string, Get reads a 2-byte descriptor containing string length and then reads the data that goes into the variable.  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 numeric Variant (VarType 0-7), Get reads 2 bytes identifying the VarType of the Variant and then reads the data that goes into the variable.  For example, when reading a Variant of VarType 3, Get reads 6 bytes: 2 bytes identifying the Variant as VarType 3 (Long) and 4 bytes containing the Long 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 read into is a String Variant (VarType 8), Get reads 2 bytes identifying the VarType, then reads 2 bytes indicating the length of the string, and then reads 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.

If the variable being read into is any other type of variable (not a variable-length string or a Variant), 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.

Elements of user-defined types are read using Get as if each were being read individually except that there is no padding between elements.  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 individual elements.

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

In Binary mode, the Len clause in the Open statement has no effect.  Get reads all variables from disk contiguously, that is, with no padding between records.

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$


See Also

Open Statement

Put Statement

Type Statement


Get Statement Example

The example uses the Get statement to read data from a disk file into a variable.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Clientname As String * 20	' Declare variables.

Dim Indx, Max, Msg, NL

NL = Chr(10)	' Define newline.

' Make a sample random-access file using the Put statement.

Msg = "Enter a name, using whatever form you like." & NL & NL

Msg = Msg & "Press 'Enter' with no name to conclude entry."

Open "TESTFILE" For Random As #1 Len = Len(ClientName)

ClientName = InputBox(Msg)	' Get user input.

Do While ClientName <> String(20, " ")

Put #1, , ClientName	' Write to file.

ClientName = InputBox(Msg)	' Get user input.

Loop

' Read the sample random-access file using the Get statement.

Max = Loc(1)

If Max = 0 Then	' Check if records exist.

Msg = "Your file contains no names." & NL

Else

Msg = "Your file contains the following names:" & NL & NL

End If

For Indx = 1 To Max

Get #1, Indx, ClientName	' Read from file.

Msg = Msg & ClientName & NL

Next Indx

Close #1	' Close file.

Msg = Msg & NL & "Choose OK to remove the created test file."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Input # Statement

See Also	Example

Reads data from a sequential file and assigns the data to variables.

Syntax

Input # filenumber, variablelist

Remarks

The Input statement has these parts:

Part	Description

filenumber	Number used to open the file with the Open statement.  It can be any numeric expression that evaluates to the number of an open file.  Note that the number sign (#) preceding filenumber is required.

variablelist	Comma-delimited list of the variables that are assigned values read from the file.

A variable in variablelist can't be an array variable but can be a variable that describes an element of an array.  A variable also can't be a user-defined type variable but can be an element.  All other variables are allowed, except object variables.

Data items in a file must appear in the same order as the variables in variablelist.  Be sure to match data in the file with variables of the proper data type: string data into String or Variant variables, numeric data into numeric or Variant variables, and uniquely Variant data (dates and Null values) into Variant variables.  Failure to match the data with a variable of the correct data type may produce unpredictable results.

When a variable in variablelist is numeric, the first nonspace character encountered is assumed to be the start of a number.  The end of the number is assumed when a space, a comma, or the end of a line is encountered.  Blank lines are input as zero.  If the data is not valid numeric data, zero is the value assigned to the variable.

When a variable in variablelist is a String, the first nonspace character encountered is assumed to be the start of a character string.  If that first character is a double quotation mark ("), it is ignored, but all characters following it (including spaces and commas) up to the next double quotation mark are input into the String variable.  For strings not delimited by double quotation marks, the end of a string is assumed when a comma, a space, or the end of a line is encountered.  Blank lines are input as zero-length strings.

When the variablelist variable is a Variant, the first nonspace character is assumed to be the start of the data.  The following rules determine how the actual data is treated:

If the input data is a valid number, the Variant is set to an appropriate numeric VarType.

If the input data consists of no data, only a delimiting comma or a blank line, the Variant is assigned VarType 0 (Empty).

If the input data is the literal #NULL#, the Variant is assigned VarType 1 (Null).

If the input data is a date literal (a date of the form #yyyy-mm-dd hh:mm:ss#), the Variant is assigned VarType 7 (Date).  Note that when either the date portion or the time portion is present, the other portion is optional.

If the input data is not a valid number, is not Empty or Null, and is not a valid date, it is input as a String and the Variant is assigned VarType 8.

If the end of file is reached while a data item is being input, the input is terminated and an error occurs.


See Also

Input, Input$ Function

Write # Statement


Input # Statement Example

In this example, the Input # statement reads a non-numeric value from a file into a variable.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim FileData, Msg, NL	' Declare variables.

NL = Chr(10)	' Define newline.

MakeDataFile	' Create sample data file.

Open "TESTFILE" For Input As #1	' Open to read file.

Do While Not EOF(1)

Input #1, FileData	' Read line of data.

Msg = Msg & FileData & NL	' Construct message from data.

Loop

Close #1	' Close file.

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove file from disk.

End Sub

Sub MakeDataFile

Open "TESTFILE" For Output As #1	' Open to write file.

Write #1, "This is test line 1."	' Print some data.

Write #1, "This is test line 2."

Close #1	' Close file.

End Sub


Input, Input$ Function

See Also	Example

Returns characters read from a sequential file.

Syntax

Input[$](n,[#]filenumber)

Remarks

Input returns a Variant; Input$ returns a String.

The Input[$] function has these parts:

Part	Description

n	Number of characters (bytes) to read from the file.  Must be less than 65,535.

filenumber	Number used in the Open statement to open the file.  It can be any numeric expression that evaluates to the number of an open file.

The Input[$] function can only be used with files opened in Input or Binary mode.

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


See Also

Input # Statement


Input, Input$ Functions Example

The example uses the Input function to read one character at a time from a file.  When an ANSI character code 10 (linefeed) is encountered, the entire line of text is displayed in a message box.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Char, FileName, TextData	' Declare variables.

FileName = InputBox("Enter filename.")	' Get file name.

If Len(FileName) Then

Open FileName For Input As #1	' Open file.

Do While Not EOF(1)

Char = Input(1, #1)	' Get one character.

If Char <> Chr(10) Then	' If not linefeed.

TextData = TextData & Char

Else	' If linefeed,

MsgBox TextData	' display line.

TextData = ""	' Clear line.

End If

Loop	' Loop if not end of file.

Close # 1	' Close file.

End If

End Sub


Line Input # Statement

See Also	Example

Reads a line from a sequential file into a String or Variant variable.

Syntax

Line Input # filenumber, variablename

Remarks

The Line Input # statement has these parts:

Part	Description

filenumber	Number used in the Open statement to open the file.  It can be any numeric expression that evaluates to the number of an open file.  Note that the number sign (#) preceding filenumber is required.

variablename	Name of the variable used to receive a line of text from the file.

The Line Input # statement reads all characters in a sequential file up to a carriage return.  It then skips over the carriage-return/linefeed sequence.

Line Input # reads a text file one line at a time.


See Also

Input # Statement


Line Input # Statement Example

The example uses the Line Input # statement to read and display the first line in the CONFIG.SYS file.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Drive, FileName, Msg, NL, TextLine	' Declare variables.

NL = Chr(10)	' Define newline.

Msg = "Which drive does your operating system boot from?"

Drive = UCase(Left(InputBox(Msg), 1))	' Get user input.

If Drive = "C" or Drive = "A" Then

FileName = Drive & ":\CONFIG.SYS"

If Dir(FileName) <> "" Then	' Check if file exists.

Open FileName For Input As #1	' If it does, open it.

Line Input #1, TextLine	' Get complete line.

Close #1	' Close file.

Msg = "The first line of your CONFIG.SYS file is:"

Msg = Msg & NL & TextLine & "."

Else	' No CONFIG.SYS.

Msg = "Could not find a CONFIG.SYS file on drive "

Msg = Msg & Drive & ":"

End If

Else

Msg = "You did not provide a valid boot drive. Systems "

Msg = Msg & "normally boot from either A: or C: drive."

End If

MsgBox Msg	' Display message.

End Sub


Loc Function

See Also	Example

Returns the current position within an open file.

Syntax

Loc(filenumber)

Remarks

The argument filenumber is the number used in the Open statement to open the file.  You can use any numeric expression that evaluates to the number of an open file.  For Random files, the Loc function returns the number of the last variable read from or written to the file.  For sequential files, Loc returns the current byte position in the file divided by 128.  For Binary mode files, Loc returns the position of the last byte read or written.


See Also

EOF Function

LOF Function

Open Statement


Loc Function Example

The example uses the Loc function to report the current position within an open data file.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, Msg, NL, PresentLoc, Tmp	' Declare variables

NL = Chr(10)	' Define newline.

MakeDataFile	' Create sample data file.

Open "TESTFILE" For Input As #1	' Open file just created.

For I = 1 To 50

Input #1, Tmp	' Read some data, and discard.

Next I

PresentLoc = Loc(1)	' Get location within file.

Close #1	' Close file.

Msg = "50 data elements have been read from a file of 500. "

Msg = Msg & "The present location within the TESTFILE file is "

Msg = Msg & PresentLoc & "." & NL & NL

Msg = Msg & "Choose OK to remove the sample data file."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Delete file from disk.

End Sub

Sub MakeDataFile ()

Dim I	' Declare variable.

Open "TESTFILE" For Output As #1	' Open file for output.

For I = 1 To 500	' Generate random values.

Print #1, Int(501 * Rnd)	' Put data in file.

Next I

Close #1	' Close file.

End Sub


Lock, Unlock Statements

See Also	Example

Control access by other processes to all or part of an opened file.

Syntax

Lock [#]filenumber [,{record | [start] To end} ]
. . .

Unlock [#]filenumber [,{record | [start] To end} ]

Remarks

The Lock and Unlock statements are used in networked environments in which several processes might need access to the same file.  The arguments to Lock and Unlock must match exactly.  The Lock and Unlock statements have these parts:

Part	Description

filenumber	Number used in the Open statement to open the file.  It can be any numeric expression that evaluates to the number of an open file.

record	Number of the record or byte to lock.  It can be any number from 1 through 2,147,483,647 (equivalent to 2^31-1).  A record can be up to 65,535 bytes long.

start	Number of the first record or byte to lock.

To	Separates start from end.

end	Number of the last record or byte to lock.

For Binary mode files, record, start, and end represent the number of a byte relative to the beginning of a file.  The first byte in a file is byte 1.

For Random files, record, start, and end represent the number of a record relative to the beginning of a file.  The first record is record 1.

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.

Lock and Unlock statements are always used in pairs.  The arguments to Lock and Unlock must match exactly.

If you specify just one record, then only that record is locked or unlocked.  If you specify a range of records and omit a starting record (start), all records from the first record to the end of the range (end) are locked or unlocked. Using Lock without record locks the entire file; using Unlock without record unlocks the entire file.

If you are using a version of MS-DOS that supports networking (MS-DOS version 3.1 or later), you must run the SHARE.EXE program to enable locking operations.  You can't use Lock and Unlock with earlier versions of MS-DOS.

Note   Be sure to remove all locks with an Unlock statement before closing a file or terminating your program.  Failure to remove locks produces unpredictable results.


See Also

Open Statement


Lock, Unlock Statements Example

The example illustrates the use of the Lock and Unlock statements.  While a record (RecNum) is being updated, access to it on a network is locked to other users until the update is complete.  To try this example, paste the user-defined type declaration into the Declarations section of a module.  Paste the remaining code into the Declarations section of a form.  Then press F5 and click the form.

Type AccountRec	' Define user-defined type.

Payer As String * 20

Address As String * 20

Place As String * 20

Owe As Single

End Type

Sub Form_Click ()

Dim CustRec As AccountRec	' Declare variables

Dim Change, Msg, NL, RecNum

NL = Chr(10)	' Define newline.

On Error GoTo ErrorHandler	' Set up error handler.

MakeDataFile	' Create sample data file.

Open "TESTFILE" For Random Shared As #1 Len = Len(CustRec)

Do

RecNum = 1	' Since there is only 1 record,

Lock #1, RecNum 	' lock the current record.

Get #1, RecNum, CustRec	' Read a record.

Msg = "Customer " & CustRec.Payer

Msg = Msg & " currently owes: "

Msg = Msg & Format(CustRec.Owe, "$#,##0.00") & NL & NL

Msg = Msg & "Please input net change (+ or - )"

Change = InputBox(Msg)	' Show data and get change.

If Len(Change) = 0 Then Change = 0

CustRec.Owe = CustRec.Owe + Change

Put #1, RecNum, CustRec	' Update record.

Unlock #1, RecNum	' Unlock the record.

Loop Until Change = 0

Close #1	' Close the file.

Cleanup:

Msg = "Transaction complete. Choose OK to remove the sample "

Msg = Msg & "data file."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove file from disk.

Exit Sub

ErrorHandler:

If Err = 70 Then	' Permission denied error.

Msg = "You must run SHARE.EXE before running this example. Exit "

Msg = Msg & "Visual Basic, Exit Windows, run SHARE.EXE, and "

Msg = Msg & "reenter Visual Basic to run this example. Do not "

Msg = Msg & "shell to DOS and run SHARE.EXE or you may not be "

Msg = Msg & "able to run other programs until you reboot."

Else	' Some other error occurred.

Msg = "Error " & Err & " occurred."

End If

MsgBox Msg	' Display error message.

Reset	' Close files, flush buffers.

Resume Cleanup	' Do an orderly exit.

End Sub

Sub MakeDataFile ()

Dim CustRec As AccountRec	' Declare variables.

Open "TESTFILE" For Random Shared As #1 Len = Len(CustRec)

CustRec.Payer = "John Smith"	' Put information in

CustRec.Address = "1 Maple Street" 	' each field of the record.

CustRec.Place = "New York, NY"

CustRec.Owe = 12!	' Initialize owed amount.

Put #1, 1, CustRec	' Put record in file.

Close #1	' Close the file.

End Sub


LOF Function

See Also	Example

Returns the size of an open file in bytes.

Syntax

LOF(filenumber)

Remarks

The argument filenumber is the number used in the Open statement to open the file.  You can use any numeric expression that evaluates to the number of an open file.

LOF can be used only on disk files.

To obtain the length of a file that is not open, use the FileLen function.


See Also

EOF Function

FileLen Function

Loc Function

Open Statement


LOF Function Example

The example uses LOF to determine the size of an open disk file.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL	' Declare variables.

NL = Chr(10)	' Define newline.

MakeDataFile	' Create sample data file.

Open "TESTFILE" For Input As #1	' Open file just created.

FileLength = LOF(1)	' Get length of file.

Close #1	' Close file.

Msg = "The length of the TESTFILE file just created is "

Msg = Msg & FileLength & " bytes." & NL & NL

Msg = Msg & "Choose OK to remove the sample data file."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Delete file from disk.

End Sub

Sub MakeDataFile ()

Dim I	' Declare variable.

Open "TESTFILE" For Output As #1	' Open file for output.

For I = 0 To 200	' Generate random values.

Print #1, Int(501 * Rnd)

Next I

Close #1	' Close file.

End Sub


Open Statement

See Also	Example

Enables input/output (I/O) to a file.

Syntax

Open file [For mode] [Access access] [lock] As [#]filenumber [Len = reclen]

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 used with the buffer.

The Open statement has these parts:

Part	Description

file	File name or path.

mode	Reserved word that specifies the file mode:  Append, Binary, Input, Output, Random.

access	Reserved word that specifies which operations are permitted on the open file:  Read, Write, Read Write.

lock	Reserved word that specifies which operations are permitted on the open file by other processes: Shared, Lock Read, Lock Write, Lock Read Write.

filenumber	Integer expression with a value between 1 and 255, inclusive.  When an Open statement is executed, filenumber is associated with the file as long as it is open.  Other I/O statements can use the number to refer to the file.

reclen	For files opened for random access, the record length; for sequential files, the number of characters buffered.  The argument reclen is a positive integer expression less than or equal to 32,767 bytes.

If file doesn't exist, it is created when a file is opened for Append, Binary, Output, or Random modes.

The argument mode is a reserved word that specifies one of the following file modes.

Mode	Description

Random	Random-access file mode (default).  In this mode, if no Access clause is present, three attempts are made to open the file when the Open statement is executed.  Access is attempted in the following order:

1st.	Read and write
2nd.	Write only
3rd.	Read only

Binary	Binary file mode.  In Binary mode, you can read and write information to any byte position in the file using Get and Put statements.  If no Access clause is present, three attempts are made to open the file, following the same order as for Random files.

Input	Sequential input mode.

Output	Sequential output mode.

Append	Sequential output mode.  Append sets the file pointer to the end of the file.  A Print # or Write # statement then extends (appends to) the file.

If the argument mode is omitted, the default mode (Random) is used.

The argument access is a reserved word that specifies the operations that can be performed on the opened file.  If the file is already opened by another process and the specified type of access is not allowed, the Open operation fails and a Permission denied error occurs.

The Access clause works only if you are using a version of MS-DOS that supports networking (MS-DOS version 3.1 or later). You (or the network startup program) must also run the SHARE.EXE program to enable locking operations.  If you use the Access clause with a version of MS-DOS that doesn't support networking, a Feature unavailable error occurs.

The argument access can be one of the following reserved words.

Access type	Description

Read	Opens the file for reading only.

Write	Opens the file for writing only.

Read Write	Opens the file for both reading and writing.  This mode is valid only for Random and Binary files and files opened for Append mode.

The lock clause works in a multiuser or multiprocessing environment to restrict access by other processes or users to an open file.  The argument can be one of the following reserved words.

Lock type	Description

Shared	Any process on any machine can read from or write to this file.

Lock Read	No other process is granted read access to this file.  This lock is applied only if no other process has a previous read access to the file.

Lock Write	No other process is granted write access to this file.  This lock is applied only if no other process has a previous write access to the file.

Lock Read Write	No other process is granted either read or write access to this file.  This access is granted only if read or write access has not already been granted to another process, or if a Lock Read or Lock Write is not already in place.

If you don't specify a lock type, the file can be opened for reading and writing any number of times by the statement, but other operations are denied access to the file while it is open.

When Open is restricted by a previous process, a Permission denied error occurs.

The argument reclen is an integer expression less than or equal to 32,767 bytes.  It specifies settings for Random and sequential files.

For Random files, the argument reclen sets the record length (the number of characters in a record).  The default record length is 128 bytes.

For sequential files, the argument reclen specifies the number of characters to be loaded into the buffer before the buffer is written to or read from the disk.  A larger buffer uses more memory but provides faster file I/O.  Conversely, a smaller buffer leaves more room in memory but slows I/O.  The default buffer size is 512 bytes.

The Len clause and reclen are ignored if mode is Binary.  For sequential files, reclen need not correspond to an individual record size, because a sequential file may have records of different sizes.

Note	In Binary, Input, and Random modes, you can open a file using a different file number without first closing the file.  In Append and Output modes, you must close a file before opening it with a different file number.


See Also

Close Statement

FreeFile Function


Open Statement Example

This example uses Open to open a file for output.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim FName, FNum, I, Msg, TestString	' Declare variables.

TestString = "The quick brown fox"	' Create test string.

For I = 1 To 5

FNum = FreeFile	' Determine file number.

FName = "TEST" & FNum & ".DAT"

Open FName For Output As FNum	' Open file.

Print #I, TestString	' Write string to file.

Next I

Close	' Close all files.

Msg = "Several test files have been created on your disk. "

Msg = Msg & "Choose OK to remove the test files."

MsgBox Msg

Kill "TEST?.DAT"	' Remove test files.

End Sub


Print # Statement

See Also	Example

Writes data to a sequential file.

Syntax

Print # filenumber, [ [{Spc(n) | Tab(n)}][ expressionlist] [{; | ,}] ]

Remarks

The Print # statement has these parts:

Part	Description

filenumber	Number used in an Open statement to open a sequential file.  It can be any numeric expression that evaluates to the number of an open file.  Note that the number sign (#) preceding filenumber is not optional.

Spc(n)	Name of the Basic function optionally used to insert n spaces into the printed output.  Multiple use is permitted.

Tab(n)	Name of the Basic function optionally used to tab to the nth column before printing expressionlist.  Multiple use is permitted.

expressionlist	Numeric and/or string expressions to be written to the file.

{;|,}	Character that determines the position of the next character printed. A semicolon means the next character is printed immediately after the last character; a comma means the next character is printed at the start of the next print zone.  Print zones begin every 14 columns.  If neither character is specified, the next character is printed on the next line.

If you omit expressionlist, the Print # statement prints a blank line in the file, but you must include the comma.

Because Print # writes an image of the data to the file, you must delimit the data so it is printed correctly.  If you use commas as delimiters, Print # also writes the blanks between print fields to the file.

Also, remember that spacing of data  displayed on a text screen using monospaced characters may not work well when the data is redisplayed in a graphical environment using proportionally spaced characters.

The Print # statement usually writes Variant data to a file the same way it writes any other Visual Basic data type. However, there are some exceptions:

If the data being written is a Variant of VarType 0 (Empty), Print # writes nothing to the file for that data item.

If the data being written is a Variant of VarType 1 (Null), Print # writes the literal #NULL# to the file.

If the data being written is a Variant of VarType 7 (Date), Print # writes the date to the file using the Short Date format defined in the WIN.INI file.  When either the date or the time component is missing or zero, Print # writes only the part provided to the file.


See Also

Open Statement

Print Method

Spc Function

Tab Function

Write # Statement


Print # Statement Example

The example uses the Print # statement to write data to a test file.  Note the use of the comma and semicolon.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim FileData, Msg, NL	' Declare variables.

NL = Chr(10)	' Define newline.

Open "TESTFILE" For Output As #1	' Open to write file.

Print #1, "This is a test of the Print # statement."

Print #1,	' Print blank line to file.

Print #1, "Zone 1", "Zone 2"	' Print in two print zones.

Print #1, "With no space between" ; "."	' Print two strings together.

Close #1	' Close file.

Open "TESTFILE" for Input As #1	' Open to read file.

Do While Not EOF(1)

Line Input #1, FileData	' Read a line of data.

Msg = Msg & FileData & NL	' Construct message.

Loop

Close #1	' Close file.

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Put Statement

See Also	Example

Writes from a variable to a disk file.

Syntax

Put [#] filenumber, [recordnumber], variablename

Remarks

The Put statement has these parts:

Part	Description

filenumber	Number used in an Open statement to open the file.  It can be any numeric expression that evaluates to the number of an open file.

recordnumber	The largest possible recordnumber is 2^31 - 1, or 2,147,483,647.  For files opened in Random mode (with the Random reserved word), recordnumber is the number of the record to be written.  For files opened in Binary mode (with the Binary reserved word), recordnumber is the byte position at which writing starts.  The first byte in a file is at position 1, the second byte is at position 2, and so on.  If you omit recordnumber, the next record or byte (the one after the last Get or Put statement or the one pointed to by the last Seek function) is written.  And if you omit recordnumber, you must still include the delimiting commas.  For example:

Put #4,, FileBuffer

variablename	Name of the variable to write to the file.  Any variable can be used except object variables and array variables (variables that describe an entire array).  However, you can use a variable that describes a single element of an array.

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 still 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 record length match the length of the data being written.

If the variable being written is a variable-length string, Put writes a 2-byte descriptor containing string length and then the variable.  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 written is a numeric Variant (VarType 0-7), Put writes 2 bytes identifying the VarType of the Variant and then the variable.  For example, when writing a Variant of VarType 3, Put writes 6 bytes: 2 bytes identifying the Variant as VarType 3 (Long) and 4 bytes containing the Long 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 a String Variant (VarType 8), Put writes 2 bytes identifying the VarType, 2 bytes indicating the length of the string, and then 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.

If the variable being written is any other type of variable (not a variable-length string and not a Variant), 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.

Elements of user-defined types are written using Put as if each were written individually except that there is no padding between elements.  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 individual elements.

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

In Binary mode, the Len clause in the Open statement has no effect.  Put writes all variables to disk contiguously, that is, with no padding between records.

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

Get Statement

Open Statement


Put Statement Example

The example uses Put to write data to a disk file.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim ClientName As String * 20	' Declare variables.

Dim Indx, Max, Msg, NL

NL = Chr(10)	' Define newline.

' Make a sample random-access file using the Put statement.

Msg = "Enter a name, using whatever form you like." & NL & NL

Msg = Msg & "Press 'Enter' with no name to conclude entry."

Open "TESTFILE" For Random As #1 Len = Len(ClientName)

ClientName = InputBox(Msg)	' Get user input.

Do While ClientName <> String(20, " ")

Put #1, , ClientName	' Write to file.

ClientName = InputBox(Msg)	' Get user input.

Loop

' Read the sample random-access file using the Get statement.

Max = Loc(1)

If Max = 0 Then	' Check if records exist.

Msg = "Your file contains no names." & NL

Else

Msg = "Your file contains the following names:" & NL & NL

End If

For Indx = 1 To Max

Get #1, Indx, ClientName	' Read from file.

Msg = Msg & ClientName & NL

Next Indx

Close #1	' Close file.

Msg = Msg & NL & "Choose OK to remove the created test file."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Reset Statement

See Also	Example

Closes all disk files.

Syntax

Reset

Remarks

The Reset statement closes all open disk files and writes the contents of all MS-DOS file buffers to disk.  .


See Also

Close Statement

End Statement


Reset Statement Example

The example uses Reset to close open files and flush the contents of MS-DOS file buffers out to disk.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim ClientName As String * 20	' Declare variables.

Dim Indx, Max, Msg, NL

NL = Chr(10)	' Define newline.

' Make a sample random-access file using the Put statement.

Msg = "Enter a name, using whatever form you like." & NL & NL

Msg = Msg & "Press 'Enter' with no name to conclude entry."

Open "TESTFILE" For Random As #1 Len = Len(ClientName)

ClientName = InputBox(Msg)	' Get user input.

Do While ClientName <> String(20, " ")

Put #1, , ClientName	' Write to file.

ClientName = InputBox(Msg)	' Get user input.

Loop

Reset	' Flush buffers, close file.

Open "TESTFILE" For Random As #1 Len = Len(ClientName)

' Read the sample random-access file using the Get statement.

Max = Loc(1)

If Max = 0 Then	' Check if records exist.

Msg = "Your file contains no names." & NL

Else

Msg = "Your file contains the following names:" & NL & NL

End If

For Indx = 1 To Max

Get #1, Indx, ClientName	' Read from file.

Msg = Msg & ClientName & NL

Next Indx

Close #1	' Close file.

Msg = Msg & NL & "Choose OK to remove the created test file."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Seek Function

See Also	Example

Returns the current file position.

Syntax

Seek (filenumber)

Remarks

The argument filenumber is the number used in the Open statement to open the file.  You can use any numeric expression that evaluates to the number of an open file.

Seek returns a value between 1 and 2,147,483,647 (equivalent to 2^31-1), inclusive.  For files open in Random mode, Seek returns the number of the next record read or written.  For files opened in Binary, Output, Append, or Input mode, Seek returns the byte position at which the next operation is to take place.  The first byte in a file is at position 1, the second byte is at position 2, and so on.


See Also

Get Statement

Open Statement

Put Statement

Seek Statement


Seek Function Example

The example uses the Seek statement to set the file position, and the Seek function to return the current file position.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim NameField As String * 20	' Declare form variable.

Dim I, Max, Msg	' Declare variables.

' Create sample data file.

Open "TESTFILE" For Random As #1 Len = Len(NameField)

' Get user input to fill records.

For I = 1 To 3

NameField = InputBox("Enter student name: ")

Put #1, I, NameField	' Put record on disk.

Next I

Close #1	' Close data file.

' Open data file.

Open "TESTFILE" For Random As #1 Len = Len(NameField)

Max = LOF(1) \ Len(NameField)	' Calculate # of records.

For I = Max To 1 Step -1	' Read file backwards.

Seek #1, I	' Set file position.

Get #1, , NameField	' Get record.

Msg = "Record #" & (Seek(1) - 1) & " contains: "

Msg = Msg & NameField

MsgBox Msg	' Display student name.

Next I

Close #1	' Close file.

Msg = "Choose OK to remove the test file."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Seek Statement

See Also	Example

Sets the position in a file for the next read or write.

Syntax

Seek [#]filenumber, position

Remarks

The Seek statement has these parts:

Part	Description

filenumber	Number used in the Open statement to open the file.  It can be any numeric expression that evaluates to the number of an open file.

position	Numeric expression that indicates where the next read or write should occur.  The value of position must be between 1 and 2,147,483,647 (equivalent to 2^31-1), inclusive.

For files opened in Random mode, position is the number of a record in the file.

For files opened in Binary, Input, Output, or Append mode, position is the byte position relative to the beginning of the file.  The first byte in a file is at position 1, the second byte is at position 2, and so on.  After a Seek operation, the next file input/output operation starts at the specified byte.

Note	Record numbers in Get and Put statements override file positioning done by Seek.

Performing a file write after doing 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

Get Statement

Open Statement

Put Statement

Seek Function


Seek Statement Example

The example uses the Seek statement to set the file position, and the Seek function to return the current file position.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim NameField As String * 20	' Declare form variable.

Dim I, Max, Msg	' Declare variables.

' Create sample data file.

Open "TESTFILE" For Random As #1 Len = Len(NameField)

' Get user input to fill records.

For I = 1 To 3

NameField = InputBox("Enter student name: ")

Put #1, I, NameField	' Put record on disk.

Next I

Close #1	' Close data file.

' Open data file.

Open "TESTFILE" For Random As #1 Len = Len(NameField)

Max = LOF(1) \ Len(NameField)	' Calculate # of records.

For I = Max To 1 Step -1	' Read file backwards.

Seek #1, I	' Set file position.

Get #1, , NameField	' Get record.

Msg = "Record #" & (Seek(1) - 1) & " contains: "

Msg = Msg & NameField

MsgBox Msg	' Display student name.

Next I

Close #1	' Close file.

Msg = "Choose OK to remove the test file."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Spc Function

See Also	Example

Skips a specified number of spaces in a Print # statement or Print method.

Syntax

Spc(number)

Remarks

This function can be used only with the Print # statement or the Print method.

The argument number is an integer between 0 and 32,767, inclusive, that determines the number of blank characters to print.

Note that the Spc function does more than move to a new print position.  The number argument specifies how many blank or space characters are printed starting at the current print position.  When you use Spc on a line with other arguments to either the Print # statement or the Print method and you place no separator (a semicolon or comma) after it, a semicolon (;) is assumed except when Spc appears at the end of a line. For example, Print #1, Spc(10) FixLen1$ and Print#1, Spc(10); FixLen1$ are equivalent.

When used with files, Spc behaves in the following way:

If number is less than the output line width, the next print position immediately follows the number of spaces printed.

If number is greater than the output-line width, Spc calculates printposition =  number Mod width and generates the number of spaces indicated by that calculation, starting at the current print position.

If the difference between the current print position and the output-line width is less than number (or number Mod width), the Spc function skips to the beginning of the next line and generates a number of spaces equal to number - (width - currentprintposition).

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.  Make sure your tabular columns are wide enough to accommodate wider letters.


See Also

Print Method

Print # Statement

Space, Space$ Function

Tab Function

Width # Statement


Spc Function Example

The example uses the Spc function to embed 10 spaces in an output file.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variable.

Open "TESTFILE" For Output As #1	' Create sample data file.

Print #1, "This is a test of the "; Spc(10); "Spc function."

Close #1	' Close file.

Open "TESTFILE" For Input As #1	' Reopen the file for input.

Input #1, Msg	' Read the data.

Close #1	' Close file.

MsgBox Msg	' Display file contents.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Tab Function

See Also	Example

Used with the Print # statement and the Print method to move the position at which the next character is printed.

Syntax

Tab(column)

Remarks

This function can be used only with the Print # statement or the Print method.

The argument column is an integer expression that is the column number of the new print position.

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.

When you use Tab on a line with other arguments to either the Print # statement or the Print method and you place no separator (a semicolon or comma) after it, a semicolon (;) is assumed except when Tab appears at the end of a line.

When used with forms and files, Tab behaves in the following way:

If the current print position on the current line is greater than column, Tab skips to column on the next output line.

If column is less than 1, Tab moves the print position to column 1.

When used with files only, Tab displays the following behavior:

If column is greater than the output-line width, Tab calculates
printposition = column Mod width

If the column 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.

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.  Make sure your tabular columns are wide enough to accommodate wider letters.


See Also

Print # Statement

Space, Space$ Function

Spc Function

Width # Statement


Tab Function Example

The example uses the Tab function to move the print position to column 40 in an output data file.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variable.

Open "TESTFILE" For Output As #1	' Create sample data file.

Print #1, "This is a test of the "; Tab(40); "Tab function."

Close #1	' Close file.

Open "TESTFILE" For Input As #1	' Reopen the file for input.

Input #1, Msg	' Read the data.

Close #1	' Close file.

MsgBox Msg	' Display file contents.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Width # Statement

See Also	Example

Assigns an output-line width to a file.

Syntax

Width # filenumber, width

Remarks

The Width # statement has these parts:

Part	Description

filenumber	Number used to open the file with the Open statement.  It can be any numeric expression that evaluates to the number of an open file.  Note that the number sign (#) preceding filenumber is not optional.

width	Numeric expression in the range 0 to 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 line width is 0.

The Width # statement permits output-line width to be changed in files that are already open.


See Also

Open Statement

Print # Statement


Width Statement Example

The example uses the Width statement to set the output-line width for a file.  A test file is created, and the same characters are written to two different line widths.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, Msg, NL, Text	' Declare variables.

NL = Chr(10)	' Define newline.

Open "TESTFILE" For Output As #1	' Create sample data file.

For I = 0 To 9	' Print ASCII characters

Print #1, Chr(48 + I);	' 0-9 to test file

Next I	' all on same line.

Print #1,	' Start new line.

Width #1, 5	' Change line width to 5.

For I = 0 To 9	' Print 0-9 again. This

Print #1, Chr(48 + I);	' time, five characters print

Next I	' before line wraps.

Close #1	' Close file.

Msg = "The effect of the Width statement is as shown below: " & NL

Open "TESTFILE" For Input As #1	' Reopen the file for input.

Do While Not Eof(1)

Input #1, Text	' Get lines from file.

Msg = Msg & NL & Text	' Create message.

Loop

Close #1	' Close file.

Msg = Msg & NL & NL & "Choose OK to remove the test file."

MsgBox Msg	' Display effects of Width.

Kill "TESTFILE"	' Remove test file from disk.

End Sub


Write# Statement

See Also	Example

Writes data to a sequential file.

Syntax

Write # filenumber [, expressionlist]

Remarks

The Write # statement has these parts:

Part	Description

filenumber	Number used in an Open statement to open a sequential file.  It can be any numeric expression that evaluates to the number of an open file.  Note that the number sign (#) preceding filenumber is required.

expressionlist	Comma-delimited numeric and/or string expressions to be written to the file.  If you omit expressionlist, the Write # statement writes a blank line to the file.

The file identified by filenumber must be opened in Output or Append mode.

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.  Write # inserts a newline character after it has written the final character in expressionlist to the file.

Usually, the Write # statement writes Variant data to a file in the same way it writes any other Visual Basic data type. However, there are some exceptions:

If the data being written is a Variant of VarType 0 (Empty), Write # writes nothing to the file for that data item.  However, if multiple items are written to the file, the delimiting commas themselves are written to the file.

If the data being written is a Variant of VarType 1 (Null), Write # writes the literal #NULL# to the file.

If the data being written is a Variant of VarType 7 (Date), Write # writes the date to the file using the fixed date format #yyyy-mm-dd hh:mm:ss#.  When either the date or the time component is missing or zero, Write # writes only the part provided to the file.


See Also

Open Statement

Print # Statement


Write # Statement Example

The example uses Write # to write two variables to a sequential file.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL, UsrAge, UsrName	' Declare variables.

NL = Chr(10)	' Define newline.

' Make a sample data file.

Open "TESTFILE" For Output As 1	' Open file for output.

Msg = "Enter your name."

UsrName = InputBox(Msg)	' Get user name.

Msg = "Enter your age."

UsrAge = InputBox(Msg)	' Get user age.

Write #1, UsrName, UsrAge	' Write data to file.

Close #1	' Close file.

' Read the sample data file

Open "TESTFILE" For Input As #1	' Open file for input.

Input #1, UsrName, UsrAge	' Read data.

Close #1	' Close file.

Msg = "The name '" & UsrName & "' was read from the data file. "

Msg = Msg & "'" & UsrAge & "' is the age you gave."

Msg = Msg & NL & NL & "Choose OK to remove test file."

MsgBox Msg	' Display message.

Kill "TESTFILE"	' Remove file from disk.

End Sub


Circle Method

See Also	Example

Draws a circle, ellipse, or arc on an  object.

Syntax

[object.]Circle [Step](x, y), radius[,[color] [,[start] [,[end] [,aspect] ] ] ]

Remarks

The Circle method has these parts:

Part	Description

object	Object (non-MDI form, picture box, or Printer object) on which the circle is drawn.

Step	Specifies that the center of the circle, ellipse, or arc is relative to the current coordinates, given by the CurrentX and CurrentY properties of object.

(x,y)	Single-precision values indicating the coordinates for the center point of the circle, ellipse, or arc.  The scale properties (ScaleMode, ScaleLeft, ScaleTop, ScaleHeight, and ScaleWidth) of object determine the units of measure used.

radius	Single-precision value indicating the radius of the circle, ellipse, or arc.  The scale properties (ScaleMode, ScaleLeft, ScaleTop, ScaleHeight, and ScaleWidth) of object determine the unit of measure used.

color	Long integer value indicating the RGB color of the circle's outline.  If omitted, the value of the ForeColor property is used.  You can use the RGB function or QBColor function to specify the color.

start, end	Single-precision values.  When a partial circle or ellipse is  drawn, start and end specify (in radians) the beginning and end positions of the arc.  The range for both is -2 Pi radians to 2 Pi radians.  The default value for start is 0 radians; the default for end is 2 * Pi radians.

aspect	Single-precision value indicating the aspect ratio of the circle .  The default value is 1.0, which yields a perfect (non-elliptical) circle on any screen.

To fill a circle, set the FillColor and FillStyle properties of the object where the circle or ellipse is drawn.  Only a closed figure can be filled.  Closed figures include circles, ellipses, or pie slices (arcs with radius lines drawn at both ends).

When drawing a partial circle or ellipse, if start is negative, Circle draws a radius to start, and treats the angle as positive; if end is negative, Circle draws a radius to end and treats the angle as positive.  The Circle method always draws in a counter-clockwise (positive) direction.

The width of the line used to draw the circle, ellipse, or arc depends on the DrawWidth property.  The way the circle is drawn on the background depends on the setting of the DrawMode and DrawStyle properties.

When drawing pie slices, if you need to draw a radius to angle 0 (giving a horizontal line segment to the right), specify a very small negative value for start, rather than zero.

You can omit an argument in the middle of the syntax, but you must include the argument's comma before including the next argument.  If you omit a trailing argument, don't use any commas following the last argument you specify.

When Circle executes, CurrentX and CurrentY are set to the center point specified by the arguments.


See Also

BackColor, ForeColor Properties

CurrentX, CurrentY Properties

DrawMode Property

DrawStyle Property

DrawWidth Property

FillColor Property

FillStyle Property

QBColor Function

RGB Function

ScaleMode Property

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

Shape Control


Circle Method Example

The Circle method draws a number of concentric circles in the center of a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim CX, CY, Radius	' Declare variable.

ScaleMode = 3	' Set scale to pixels.

CX = ScaleWidth / 2	' Set X position.

CY = ScaleHeight / 2	' Set Y position.

If CX > CY Then Limit = CY Else Limit = CX

For Radius = 0 to Limit	' Set radius.

Circle (CX, CY), Radius,RGB(Rnd * 255, Rnd * 255, Rnd * 255)

Next Radius

End Sub


EndDoc Method

See Also	Example

Terminates a document sent to the Printer, releasing it to the print device or spooler.

Syntax

Printer.EndDoc

Remarks

If EndDoc is invoked immediately after NewPage, no additional blank page is printed.


See Also

NewPage Method

Printer Object


EndDoc Method Example

The example uses the EndDoc method to end a document after printing two pages, each with a centered line of text indicating the page number.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim HWidth, HHeight, I, Msg	' Declare variables.

On Error GoTo ErrorHandler	' Set up error handler.

Msg = "This is printed on page"

For I = 1 To 2	' Set up two iterations.

HWidth = Printer.TextWidth(Msg) / 2	' Get half width.

HHeight = Printer.TextHeight(Msg) /2	' Get half height.

Printer.CurrentX = Printer.ScaleWidth / 2 - HWidth

Printer.CurrentY = Printer.ScaleHeight / 2 - HHeight

Printer.Print Msg & Printer.Page & "."	' Print.

Printer.NewPage	' Send new page.

Next I

Printer.EndDoc	' Print done.

Msg = "Two pages, each with a single, centered line of text, "

Msg = Msg & "have been sent to your printer."

MsgBox Msg	' Display message.

Exit Sub

ErrorHandler:

MsgBox "There was a problem printing to your printer."

Exit Sub

End Sub


Line Method

See Also	Example

Draws lines and rectangles on an object.

Syntax

[object.]Line [[Step](x1, y1)] - [Step](x2, y2) [,[color][,B[F]]]

Remarks

The Line method has these parts:

Part	Description

object	Object (non-MDI form, picture box, or Printer object) on which the line or rectangle is to be drawn.

Step	Keyword that specifies that the starting point coordinates are relative to the current graphics position, given by the CurrentX and CurrentY properties.

x1, y1	Single-precision values indicating the coordinates of the starting point for the line or rectangle.  The scale properties (ScaleMode, ScaleLeft, ScaleTop, ScaleHeight, and ScaleWidth) of object determine the unit of measure used.  If omitted, the line begins at the position indicated by CurrentX and CurrentY.

Step	Keyword that specifies that the end point coordinates are relative to the line starting point.

x2, y2	Single-precision values indicating the coordinates of the end point for the line to draw.  These coordinates are required.

color	Long integer value indicating the RGB color used to draw the line.  If omitted, the ForeColor property is used.  You can use the RGB function or QBColor function to specify the color.

B	Option that causes a box to be drawn using the coordinates to specify opposite corners of the box.

F	If the B option is used, the F option specifies that the box is filled with the same color used to draw the box.  You cannot use F without B.  If B is used without F, the box is filled with the current FillColor and FillStyle.  The default value for FillStyle is transparent.

When drawing lines that are connected, lines should be drawn so that subsequent lines begin at the end point of the previous line.

The width of the line drawn depends on the DrawWidth property.  The way a line or box is drawn on the background depends on the setting of the DrawMode and DrawStyle properties.

When Line executes, CurrentX and CurrentY are set to the end point specified by the arguments.


See Also

CurrentX, CurrentY Properties

DrawMode Property

DrawStyle Property

DrawWidth Property

FillColor Property

FillStyle Property

ForeColor Property

Line Control

QBColor Function

RGB Function

ScaleHeight, ScaleWidth Properties

ScaleLeft, ScaleTop Properties

ScaleMode Property

Shape Control


Line Method Example

The Line method example draws concentric boxes on a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim CX, CY, F, F1, F2, I	' Declare variables

ScaleMode = 3	' Set ScaleMode to pixels.

CX = ScaleWidth / 2	' Get horizontal center.

CY = ScaleHeight / 2	' Get vertical center.

DrawWidth = 8	' Set DrawWidth.

For I = 50 To 0 Step -2

F = I / 50	' Perform interim

F1 = 1 - F: F2 = 1 + F	' calculations.

Forecolor = QBColor(I Mod 15)	' Set foreground color.

Line (CX * F1, CY * F1)-(CX * F2, CY * F2), , BF

Next I

DoEvents	' Yield for other processing.

If CY > CX Then	' Set DrawWidth.

DrawWidth = ScaleWidth / 25

Else

DrawWidth = ScaleHeight / 25

End If

For I = 0 To 50 Step 2	' Set up loop.

F = I / 50	' Perform interim

F1 = 1 - F: F2 = 1 + F	' calculations.

Line (CX * F1, CY)-(CX, CY * F1)	' Draw upper-left.

Line -(CX * F2, CY)	' Draw upper-right.

Line -(CX, CY * F2)	' Draw lower-right.

Line -(CX * F1, CY)	' Draw lower-left.

Forecolor = QBColor(I Mod 15)	' Change color each time.

Next I

DoEvents	' Yield for other processing.

End Sub


NewPage Method

See Also	Example

Ends the current page and advances to the next.

Syntax

Printer.Newpage

Remarks

The NewPage method advances to the next printer page and resets the print position to the upper-left corner of the new page.

When invoked, NewPage increments the Printer object's Page property by 1.


See Also

EndDoc Method

Page Property

Printer Object


NewPage Method Example

The example uses the NewPage method to begin a new printer page after printing a single, centered line of text on a page.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim HWidth, HHeight, I, Msg	' Declare variables.

On Error GoTo ErrorHandler	' Set up error handler.

Msg = "This is printed on page"

For I = 1 To 2	' Set up two iterations.

HWidth = Printer.TextWidth(Msg) / 2	' Get half width.

HHeight = Printer.TextHeight(Msg) /2	' Get half height.

Printer.CurrentX = Printer.ScaleWidth / 2 - HWidth

Printer.CurrentY = Printer.ScaleHeight / 2 - HHeight

Printer.Print Msg & Printer.Page & "."	' Print.

Printer.NewPage	' Send new page.

Next I

Printer.EndDoc	' Print done.

Msg = "Two pages, each with a single, centered line of text, "

Msg = Msg & "have been sent to your printer."

MsgBox Msg	' Display message.

Exit Sub

ErrorHandler:

MsgBox "There was a problem printing to your printer."

Exit Sub

End Sub


Point Method

See Also	Example

Returns the RGB color of the specified point on a form or picture box.

Syntax

[object.]Point(x,y)

Remarks

The Point method has these parts:

Part	Description

object	Object (non-MDI form or picture box) where the specified point is located.

x	Single-precision value indicating the horizontal (x-axis) coordinate of the point, in the scale mode of the form or picture box.

y	Single-precision value indicating the vertical (y-axis) coordinate of the point, in the scale mode of the form or picture box.

If the point referred to by the x and y coordinates is outside the object, the Point method returns -1.


See Also

Circle Method

Line Method

Print Method

PSet Method


Point Method Example

The example uses the Point method to determine the color of a specific point on a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim LeftColor, MidColor, Msg, RightColor	' Declare variables.

AutoRedraw = -1	' Turn on AutoRedraw.

Height = 3 * 1440	' Set height to 3 inches.

Width = 5 * 1440	' Set width to 5 inches.

Backcolor = QBColor(1)	' Set background to blue.

Forecolor = QBColor(4)	' Set foreground to red.

Line (0, 0)-(Width / 3, Height), , BF	' Red box.

Forecolor = QBColor(15)	' Set foreground to white.

Line (Width / 3, 0)-((Width / 3) * 2, Height), , BF

LeftColor = Point(0, 0)	' Find color of left box,

MidColor = Point(Width / 2, Height / 2)	' Middle box, and

RightColor = Point(Width, Height)	' Right box.

Msg = "The color number for the red box on the left side of "

Msg = Msg & "the form is " & LeftColor & ". The "

Msg = Msg & "color of the white box in the center is "

Msg = Msg & MidColor & ". The color of the blue "

Msg = Msg & "box on the right is " & RightColor & "."

MsgBox Msg	' Display message.

End Sub


Print Method

See Also	Example

Prints a text string on an object using the current color and font.

Syntax

[object.]Print [{Spc(n) | Tab(n)}][expressionlist][{; | ,}]

Remarks

The Print method has these parts:

Part	Description

object	Object (non-MDI form, picture box, Debug, or Printer object) on which expressionlist is to be printed.

Spc(n)	Name of the Basic function optionally used to insert n spaces into the printed output.  Multiple use is permitted.

Tab(n)	Name of the Basic function optionally used to tab to the nth column before printing expressionlist.  Multiple use is permitted.

expressionlist	Numeric or string expressions to print.  If omitted, Print prints a blank line. Multiple expressions can be separated with a space, a semicolon , or a comma.  A space has the same effect as a semicolon.  Spc and Tab can also be used with each separate expression.

{;|,}	Character that determines the location of the text cursor for the next character displayed: a semicolon means the cursor is placed immediately after the last character displayed; a comma means the cursor is placed at the start of the next print zone.  Print zones begin every 14 columns.  If neither character is specified, the next character is printed on the next line.  The width of each column is an average of the width of all characters in the point size for the chosen font.

The expressionlist is printed on the object starting at the position indicated by CurrentX and CurrentY properties.

Normally, when expressionlist is printed, a carriage return is appended so that the next Print begins printing on the next line.  When a carriage return occurs, CurrentY is increased by the height of expressionlist (same as the value returned by TextHeight) and the CurrentX is set to zero.

When a semicolon follows the expressionlist, no carriage return is appended, and the next Print displays on the same line as the current Print.  The CurrentX and CurrentY are set to the point immediately after the last character printed.  If the expressionlist itself contains carriage returns, each such embedded carriage return sets CurrentX and CurrentY as described above for Print without a semicolon.

When a comma follows expressionlist, CurrentX and CurrentY are set to the next print zone on the same line.

There is no scrolling of lines that cannot fit in the specified position.  The printed string is clipped to fit the object on which it is displayed.

Because the Print method normally prints with proportionally-spaced characters, it is important to remember that 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, whereas a narrow letter, such as an "i", occupies less.  To account for cases where wider than average characters are used, you must ensure that your tabular columns are 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

CurrentX, CurrentY Properties

Printer Object

NewPage Method

PrintForm Method

Spc Function

Tab Function

TextHeight Method


Print Method Example

The example uses the Print method to display some text on a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim CX, I, J, K, L, M, Msg, Offset	' Declare variables.

Cls	' Clear form.

Width = 7200	' Set form width.

Height = 5000	' Set form height.

BackColor = QBColor(1)	' Set background color.

For I = 1 To 3

Select Case I

Case 1	' First time.

ForeColor = QBColor(5)	' Set foreground color.

K = 1: L = 9: M = 1

Msg = "Visual"	' Set message.

CX = 0	' Set position variable.

Case 2	' Second time.

K = 1: L = 9: M = 1

Msg = "Basic"

CX = ScaleWidth

Case 3	' Third time.

ForeColor = QBColor(15)

K = 9: L = 1: M = -1

Msg = "Visual Basic"

CX = ScaleWidth / 2

End Select

For J = K To L Step M

Select Case J	' Change font size.

Case 1: Fontsize = 8

Case 2: Fontsize = 10

Case 3: Fontsize = 12

Case 4: Fontsize = 14

Case 5: Fontsize = 18

Case 6: Fontsize = 20

Case 7: Fontsize = 24

Case 8: Fontsize = 36

Case 9: Fontsize = 48

End Select

If I = 1 Then

Offset = 0	' Text on left.

ElseIf I = 2 Then

Offset = TextWidth(Msg)	' Text on right.

Else

Offset = TextWidth(Msg) / 2	' Text in center.

End If

CurrentX = CX - Offset

Print Msg	' Print message.

Next J

CurrentY = 0	' Reset to top of form.

Next I

End Sub


PrintForm Method

See Also	Example

Sends a bit-for-bit image of a non-MDI form to the printer.

Syntax

[form.]PrintForm

Remarks

The argument form is the non-MDI form to print.  If omitted, the current form is printed.  PrintForm prints all visible controls and bitmaps on the form.  PrintForm also prints graphics added to the form or picture controls on the form at run time if AutoRedraw is True when the graphics are drawn.

The printer used by PrintForm is determined by the Microsoft Windows control panel.


See Also

AutoRedraw Property

Print Method

Printer Object


PrintForm Method Example

The example uses the PrintForm method to print the current form.  To try this example, paste the code into the Declarations section of a form.  Place on the form any controls you want to see in the printed form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variable.

On Error GoTo ErrorHandler	' Set up error handler.

PrintForm	' Print form.

Exit Sub

ErrorHandler:

Msg = "The form could not be printed."

MsgBox Msg	' Display message.

Resume Next

End Sub


PSet Method

See Also	Example

Action

Sets a point on an object to a specified color.

Syntax

[object.]PSet [Step](x, y)[,color]

Remarks

The PSet method has these parts:

Part	Description

object	Object (non-MDI form, picture box, or Printer object) on which point is to be drawn.

Step	Keyword that specifies that the coordinates are relative to the current graphics position given by the CurrentX and CurrentY properties.

x, y	Single-precision values indicating the horizontal and vertical coordinates of the point to set.

color	RGB color specified for point.  If omitted, the current foreground color is used.  You can use the RGB function or QBColor function to specify the color.

The size of the point drawn depends on the DrawWidth property.  When DrawWidth is 1, PSet sets a single pixel to the specified color.  When DrawWidth is greater than 1, the point is centered on the specified coordinates.

The way the point is drawn depends on the setting of the DrawMode and DrawStyle properties.

When PSet executes, CurrentX and CurrentY are set to the point specified by the arguments.

Clear a single pixel with the PSet method by specifying the coordinates of the pixel and using BackColor as the color argument.


See Also

BackColor, ForeColor Properties

CurrentX, CurrentY Properties

DrawMode Property

DrawStyle Property

DrawWidth Property

RGB Function

QBColor Function


PSet Method Example

The PSet method example draws confetti on a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim CX, CY, Msg, XPos, YPos	' Declare variables.

ScaleMode = 3	' Set ScaleMode to pixels.

DrawWidth = 5	' Set DrawWidth.

ForeColor = QBColor(4)	' Set background to red.

FontSize = 24	' Set point size.

CX = ScaleWidth / 2	' Get horizontal center.

CY = ScaleHeight / 2	' Get vertical center.

Cls	' Clear form.

Msg = "Happy New Year!"

CurrentX = CX - TextWidth(Msg) / 2	' Horizontal position.

CurrentY = CY - TextHeight(Msg)	' Vertical position.

Print Msg	' Print message.

Do

XPos = Rnd * ScaleWidth	' Get horizontal position.

YPos = Rnd * ScaleHeight	' Get vertical position.

PSet (XPos, YPos), QBColor(Rnd * 15)	' Draw confetti.

DoEvents	' Yield for other processing.

Loop

End Sub


QBColor Function

See Also	Example

Returns the RGB color code corresponding to a color number.

Syntax

QBColor (qbcolor)

Remarks

The qbcolor argument is an integer in the range 0-15, inclusive, that corresponds to the color values used by other versions of Basic (such as Microsoft Visual Basic for MS-DOS and Basic Compiler). Starting with the least-significant byte, the returned value specifies the red, green, and blue values used to set the appropriate color in the RGB system used by Visual Basic.

The following table shows the possible settings for qbcolor:

Number [image] Color	Number [image] Color
0 [image] Black	8 [image] Gray
1 [image] Blue	9 [image] Light Blue
2 [image] Green	10 [image] Light Green
3 [image] Cyan	11 [image] Light Cyan
4 [image] Red	12 [image] Light Red
5 [image] Magenta	13 [image] Light Magenta
6 [image] Yellow	14 [image] Light Yellow
7 [image] White	15 [image] Bright White


See Also

 RGB Function


QBColor Function Example

The example uses the QBColor function to show the range of colors on a form. To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I	' Declare variable

Cls	' Clear form.

ScaleHeight = 16	' Divide form into 16 parts.

For I = 0 To 15	' Draw a colored box.

Line(0, I)-(ScaleWidth, I + 1), QBColor(I), BF

Next I

End Sub


RGB Function

See Also	Example

Returns a long integer representing an RGB color value.

Syntax

RGB (red, green, blue)

Remarks

The RGB function has these parts:

Part	Description

red	Integer in the range of 0 to 255, inclusive, that represents the red component of the color.

green	Integer in the range of 0 to 255, inclusive, that represents the green component of the color.

blue	Integer in the range of 0 to 255, inclusive, that represents the blue component of the color.

Visual Basic methods and properties that accept a color specification expect that specification to be a long integer representing an RGB color value. An RGB color value specifies the relative intensity of red, green, and blue, which taken together cause a specific color to be displayed.

If the value for any argument to RGB exceeds 255, it is assumed to be 255.

The following table shows the hexadecimal representation for some standard colors, their corresponding RGB values, and the red, green and blue components for each:

Color	RGB value	Red value	Green value	Blue value
Black	&H00	0	0	0
Blue	&HFF0000	0	0	255
Green	&HFF00	0	255	0
Cyan	&HFFFF00	0	255	255
Red	&HFF	255	0	0
Magenta	&HFF00FF	255	0	255
Yellow	&HFFFF	255	255	0
White	&HFFFFFF	255	255	255


See Also

QBColor Function


RGB Function Example

The RGB function example displays a variety of color shades on a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I	' Declare variable.

Cls	' Clear form

ScaleHeight = 128	' Divide form into 128 parts.

For I = 0 To 126 Step 2	' Draw a colored box.

Line (0, I)-(ScaleWidth, I + 2), RGB(I, 64 + I, 128 + I),BF

Next I

End Sub


Scale Method

See Also	Example

Defines the coordinate system for an object.

Syntax

[object.]Scale [(x1, y1) - (x2, y2)]

Remarks

The Scale method has these parts:

Part	Description

object	Object (non-MDI form, picture box, or Printer object) to which the coordinate system is applied.

x1, y1	Single-precision values for the horizontal and vertical coordinates that define the upper-left corner of the object.

x2, y2	Single-precision values for the horizontal and vertical coordinates that define the lower-right corner of the object.

The Scale method allows you to reset the coordinate system to any scale you choose. Scale with no arguments resets the coordinate system to twips. Scale affects the coordinate system for the both the run-time graphics statements and the placement of controls.


See Also

ScaleHeight Property

ScaleLeft Property

ScaleMode Property

ScaleTop Property

ScaleWidth Property


Scale Method Example

The example uses the Scale method to set up a custom coordinate system so that a bar chart can be drawn on a form. To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, OldFontSize	' Declare variables

Width = 8640: Height = 5760	' Set form size in twips.

Move 100,100	' Move form origin.

AutoRedraw = -1	' Turn on AutoRedraw.

OldFontSize = FontSize	' Save old font size.

BackColor = QBColor(7)	' Set background to gray.

Scale (0, 110)-(130, 0)	' Set custom coordinate system.

For I = 100 To 10 Step -10

Line (0, I)-(2, I)	' Draw scale marks every 10 units.

CurrentY = CurrentY + 1.5	' Move cursor position.

Print I	' Print scale mark value on left.

Line (ScaleWidth - 2, I)-(ScaleWidth, I)

CurrentY = CurrentY + 1.5	' Move cursor position.

CurrentX = ScaleWidth - 9

Print I	' Print scale mark value on right.

Next I

' Draw bar chart

Line (10, 0)-(20, 45), RGB(0, 0, 255), BF	' 1st blue bar.

Line (20, 0)-(30, 55), RGB(255, 0, 0), BF	' 1st red bar.

Line (40, 0)-(50, 40), RGB(0, 0, 255), BF

Line (50, 0)-(60, 25), RGB(255, 0, 0), BF

Line (70, 0)-(80, 35), RGB(0, 0, 255), BF

Line (80, 0)-(90, 60), RGB(255, 0, 0), BF

Line (100, 0)-(110, 75), RGB(0, 0, 255), BF

Line (110, 0)-(120, 90), RGB(255, 0, 0), BF

CurrentX = 18: CurrentY = 100	' Move cursor position.

FontSize = 14	' Enlarge font for title.

Print "Widget Quarterly Sales"	' Print title.

FontSize = OldFontSize	' Restore font size.

CurrentX = 27: CurrentY = 93	' Move cursor position.

Print "Planned Vs Actual"	' Print subtitle.

Line (29, 86)-(34, 88), RGB(0, 0, 255), BF	' Print legend.

Line (43, 86)-(49, 88), RGB(255, 0, 0), BF

End Sub


TextHeight Method

See Also	Example

Action

Returns the height of a text string as it would be printed in the current font of an object.

Syntax

[object.]TextHeight(stringexpression)

Remarks

The TextHeight method has these parts:

Part	Description

object	Object (non MDI form, picture box, or Printer object) that determines the font size upon which the text height is based.

stringexpression	Text string for which the text height is determined.

The height is expressed in terms of the Scale coordinate system in effect for object.  Use TextHeight to determine the amount of vertical space required to display the text.  The height returned includes the normal "leading" space above and below the string, so you can use the height to calculate and position multiple lines of text within a form, picture box, or Printer object.  If stringexpression contains embedded carriage returns, TextHeight returns the cumulative height of the lines, including the leading space above and below each line.


See Also

FontSize Property

Scale Method

TextWidth Method


TextHeight Method Example

The TextHeight method is used to center a line vertically on a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim HalfWidth, HalfHeight, Msg	' Declare variable.

AutoRedraw = -1	' Turn on AutoRedraw.

BackColor = QBColor(4)	' Set background color.

ForeColor = QBColor(15)	' Set foreground color.

Msg = "Visual Basic"	' Create message.

Fontsize = 48	' Set font size.

HalfWidth = TextWidth(Msg) / 2 	' Calculate half width.

HalfHeight = TextHeight(Msg) / 2	' Calculate half height.

CurrentX = ScaleWidth / 2 - HalfWidth	' Set X.

CurrentY = ScaleHeight / 2 - HalfHeight	' Set Y.

Print Msg	' Print message.

End Sub


TextWidth Method

See Also	Example

Action

Returns the width of a text string as it would be printed in the current font of an object.

Syntax

[object.]TextWidth(stringexpression)

Remarks

The TextWidth method has these parts:

Part	Description

object	Object (non MDI form, picture box, or Printer object) that determines the font size upon which the text width is based.

stringexpression	Text string for which the text width is determined.

The width is expressed in terms of the Scale coordinate system of object.  Use TextWidth to determine the amount of horizontal space required to display the text.  If stringexpression contains embedded carriage returns, TextWidth returns the width of the longest line.


See Also

FontSize Property

Scale Method

TextHeight Method


TextWidth Method Example

The TextWidth method is used to center a line of text horizontally on a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim HalfHeight, HalfWidth, Msg	' Declare variables.

AutoRedraw = -1	' Turn on AutoRedraw.

BackColor = QBColor(4)	' Set background color.

ForeColor = QBColor(15)	' Set foreground color.

Msg = "Visual Basic"	' Create message.

Fontsize = 48	' Set font size.

HalfWidth = TextWidth(Msg) / 2 	' Calculate half width.

HalfHeight = TextHeight(Msg) / 2	' Calculate half height.

CurrentX = ScaleWidth / 2 - HalfWidth	' Set X.

CurrentY = ScaleHeight / 2 - HalfHeight	' Set Y.

Print Msg	' Print message.

End Sub


IsDate Function

See Also	Example

Returns a value indicating whether or not a Variant argument can be converted to a date.

Syntax

IsDate(variant)

Remarks

The argument variant can be any Variant expression of VarType 7 (Date) or of VarType 8 (String).  The IsDate function returns True if the Variant can legally be converted to a date; otherwise, it returns False.  The range of valid dates is January 1, 100 A.D. through December 31, 9999 A.D.


See Also

CVDate Function

IsEmpty Function

IsNull Function

IsNumeric Function

VarType Function


IsDate Function Example

The example evaluates TestVar to determine whether it can legally be converted to a numeric data type and displays an appropriate message.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim TestVar	' Declare variable.

TestVar = InputBox("Enter a string you'd like displayed as a date.")

If IsDate(TestVar) Then	' Test variable.

MsgBox "The date is: " & Format(CVDate(TestVar),"dddddd")

Else

MsgBox "What you entered doesn't make sense as a date."

End If

End Sub


IsEmpty Function

See Also	Example

Returns a value indicating whether or not a Variant variable has been initialized.

Syntax

IsEmpty(variant)

Remarks

The argument variant can be any Variant expression.  However, because IsEmpty is used to determine whether or not variables are initialized, the argument is most often a single variable name.  The IsEmpty function returns True if the Variant contains the Empty value; otherwise, it returns False.  When an expression contains more than one Variant, IsEmpty always returns False.

The Empty value indicates that a Variant has not been initialized.  Empty is not the same as Null, which indicates that a Variant contains no data.


See Also

IsDate Function

IsNull Function

IsNumeric Function

VarType Function


IsEmpty Function Example

The example uses IsEmpty to determine whether TestVar has been initialized.  If it hasn't been initialized, the user is asked if it should be.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim InitVar, TestVar	' Declare variable.

If IsEmpty(TestVar) Then	' Test variable.

InitVar = MsgBox("TestVar is uninitialized. Initialize now?", 36)

If InitVar = 6 Then	' If Yes,

TestVar = 1.25	' initialize TestVar.

MsgBox "TestVar initialized to " & TestVar

End If

End If

End Sub


IsNull Function

See Also	Example

Returns a value that indicates whether or not a Variant contains the special Null value.

Syntax

IsNull(variant)

Remarks

The argument variant can be any Variant expression.  The IsNull function returns True if the expression contains the Null value; otherwise, it returns False.

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

Caution	Using the IsNull function is the only way from within Visual Basic to determine whether or not a Variant expression contains a Null value.  Expressions that you might expect to evaluate 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

IsDate Function

IsEmpty Function

IsNumeric Function

VarType Function


IsNull Function Example

The example evaluates TestVar to determine whether it contains the Null value and then displays an appropriate message.  The variable TestVar starts as Null but is changed to a zero-length string the first time through the loop.  The second time through the loop, TestVar again becomes Null and the loop exits.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim TestVar	' Declare variable.

TestVar = Null	' Initialize as Null.

Do

If IsNull(TestVar) Then	' Evaluate variable.

MsgBox "TestVar is Null."	' Indicate if Null.

TestVar = "" 	' Make zero-length string.

Else

MsgBox "TestVar is not Null."	' Indicate if not Null.

TestVar = Null	' Make Null.

End If

Loop Until IsNull(TestVar)	' Loop until TestVar is Null.

End Sub


IsNumeric Function

See Also	Example

Returns a value indicating whether or not a Variant variable can be converted to a numeric data type.

Syntax

IsNumeric(variant)

Remarks

The argument variant can be any Variant expression.  The IsNumeric function returns True if the expression can legally be converted to a number; otherwise, it returns False.  Expressions that can legally be converted to a numeric data type include Variant variables of VarType 0 (Empty), of any numeric value (VarType 2-6), of VarType 7 (Date), and of VarType 8 (String) if the String can be interpreted as numeric.


See Also

IsDate Function

IsEmpty Function

IsNull Function

VarType Function


IsNumeric Function Example

The example evaluates TestVar to determine whether it can legally be converted to a numeric data type and displays an appropriate message.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim TestVar	' Declare variable.

TestVar = InputBox("Please enter a number, letter, or symbol.")

If IsNumeric(TestVar) Then	' Evaluate variable.

MsgBox "Entered data is numeric."	' Message if number.

Else

MsgBox "Entered data is not numeric."	' Message if not.

End If

End Sub


VarType Function

See Also	Example

Returns a value that indicates how a Variant is stored internally by Visual Basic.

Syntax

VarType(variant)

Remarks

The argument variant is a variable of the Variant data type.  The VarType function returns a value that provides information about the type of data stored in the Variant.

The value returned by VarType is one of the following:

Symbolic constant	Value	Meaning
V_EMPTY	0	Empty
V_NULL	1	Null
V_INTEGER	2	Integer
V_LONG	3	Long
V_SINGLE	4	Single
V_DOUBLE	5	Double
V_CURRENCY	6	Currency
V_DATE	7	Date
V_STRING	8	String
Note	Symbolic constants for file Variant definitions can be found in the Visual Basic file CONSTANT.TXT.  When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

Data Types

IsDate Function

IsEmpty Function

IsNull Function

IsNumeric Function


VarType Function Example

The example uses VarType to determine whether a Variant argument passed to the function is either a Single or a Double.  True is returned if the argument is one of these types of data, False if it is not.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Num	' Declare variable.

Num = InputBox("Enter a number.")	' Get number from user.

If IsNumeric(Num) Then

Num = CDbl(Num)

Else

MsgBox "You did not enter a number."

Exit Sub

End If

If IsReal(Num) Then

MsgBox "What you entered is a real number."

Else

MsgBox "What you entered is not a real number."

End If

End Sub

Function IsReal(VarArg)

If VarType(VarArg) = 4 Or VarType(VarArg) = 5 Then

IsReal = True	' If Single or Double.

Else

IsReal = False	' If not.

End If

End Function


Beep Statement

Example

Sounds a tone through the computer's speaker.

Syntax

Beep

Remarks

The frequency and duration of the beep depends on hardware, which may vary among computers.


Beep Statement Example

The example uses Beep to sound a tone in the computer speaker if Answer is less than 1 or greater than 3.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Answer, Msg	' Declare variables.

Do

Answer = InputBox("Enter a value from 1 to 3.")

If Answer >= 1 And Answer <= 3 Then	' Check range.

Exit Do	' Exit Do...Loop.

Else

Beep	' Beep if not in range.

End If

Loop

MsgBox "You entered a value in the proper range."

End Sub


InputBox, InputBox$ Functions

See Also	Example

Displays a prompt in a dialog box, wait for the user to input text or choose a button, and returns the contents of the text box.

Syntax

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

Remarks

InputBox returns a Variant of Vartype 8 (String); InputBox$ returns a String.

The InputBox[$] function has these parts:

Part	Description

prompt	String expression displayed as the message in the dialog box.  The maximum length of prompt is approximately 255 characters depending on the width of the characters used.  If prompt will consist of more than one line, be sure to include a carriage return (ANSI character 13) and a linefeed (ANSI character 10) between each line.

title	String expression displayed in the title bar of the dialog box.  If you omit the title, nothing is placed in the title bar.

default	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	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 you omit xpos, you must also omit ypos.  If xpos and ypos are omitted, the dialog box is horizontally centered and vertically positioned approximately one third of the way down the screen.  If you omit either title or default or both but include xpos and ypos, you must still include the commas that separate the arguments.

ypos	Numeric expression that specifies, in twips, the vertical distance of the upper edge of the dialog box from the top of the screen.

If the user chooses the OK button or presses Enter, the InputBox[$] function returns whatever is in the text box.  If the user chooses the Cancel button, the function returns a zero-length string ("").


See Also

MsgBox Function, MsgBox Statement


InputBox, InputBox$ Function Example

The example prompts the user with a message and returns the user-entered value.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Answer, DefVal, Msg, Title	' Declare variables.

Msg = "Enter a value from 1 to 3."	' Set prompt.

Title = "InputBox Demo"	' Set title.

DefVal = "1"	' Set default return value.

Do

Answer = InputBox(Msg, Title, DefVal)	' Get user input.

Loop Until Answer >= 1 And Answer <= 3

MsgBox "You entered " & Answer	' Display message.

End Sub


MsgBox Function, MsgBox Statement

See Also	Example

Displays a message in a dialog box and waits for the user to choose a button.  The MsgBox function returns a value indicating which button the user has chosen; the MsgBox statement does not.

Function Syntax

MsgBox(msg [, [type][, title] ] )

Statement Syntax

MsgBox msg [, [type][, title] ]

Remarks

The MsgBox function and statement both have these parts:

Part	Description

msg	String expression displayed as the message in the dialog box.

type	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.  The following table illustrates the values used and the meaning of each group of values:

Symbolic constant	Value	Meaning

MB_OK	0	Display OK button only.

MB_OKCANCEL	1	Display OK and Cancel buttons.

MB_ABORTRETRYIGNORE	2	Display Abort, Retry, and Ignore buttons.

MB_YESNOCANCEL	3	Display Yes, No, and Cancel buttons.

MB_YESNO	4	Display Yes and No buttons.

MB_RETRYCANCEL	5	Display Retry and Cancel buttons.

MB_ICONSTOP	16

MB_ICONQUESTION	32

MB_ICONEXCLAMATION	48

MB_ICONINFORMATION	64

MB_DEFBUTTON1	0	First button is default.

MB_DEFBUTTON2	256	Second button is default.

MB_DEFBUTTON3	512	Third button is default.

MB_APPLMODAL	0	Application modal.  The user must respond to the message box before continuing work in the current application.

MB_SYSTEMMODAL	4096	System modal.  All applications are suspended until the user responds to the message box.

The first group of values (1-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 argument type, use only one number from each group.  If omitted, the default value for type is 0.

title	String expression displayed in the title bar of the dialog box.  If you omit the argument title, MsgBox uses "Microsoft Visual Basic" as the default title for applications running in the Visual Basic development environment and the application name for executable files created by Visual Basic.

For application modal message boxes, MsgBox displays a maximum of 1024 characters.  Longer messages are truncated after the 1024th character.  Message strings longer than 255 characters with no intervening spaces are truncated after the 255th character.  For system modal message boxes, the number of characters you can display depends on screen resolution and whether or not the string to be displayed is on one or more lines.

MsgBox breaks lines automatically at the right edge of the dialog box.  If you want to set line breaks yourself, place a linefeed (ANSI character 10) before the first character of the text that is to begin each new line.  For system modal message boxes in Microsoft Windows 3.0 only, the linefeed character does not cause a line to wrap.

The value returned by the MsgBox function indicates which button has been selected, as shown in the following table:

Symbolic constant	Value	Meaning

IDOK	1	OK button selected.

IDCANCEL	2	Cancel button selected.

IDABORT	3	Abort button selected.

IDRETRY	4	Retry button selected.

IDIGNORE	5	Ignore button selected.

IDYES	6	Yes button selected.

IDNO	7	No button selected.

If the dialog box displays a Cancel button, pressing the Esc key has the same effect as choosing Cancel.

Note	Symbolic constants for all message box definitions can be found in the Visual Basic file CONSTANT.TXT.  When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

InputBox, InputBox$ Function


MsgBox Function, MsgBox Statement Example

The example uses MsgBox to display a critical-error message in a dialog box with a Yes button and a No button.  The No button is the default response.  The MsgBox function returns a value based on the button chosen by the user.  The MsgBox statement uses that value to display a message that indicates which button was chosen.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Const MB_OK = 0, MB_OKCANCEL = 1	' Define buttons.

Const MB_YESNOCANCEL = 3, MB_YESNO = 4

Const MB_ICONSTOP = 16, MB_ICONQUESTION = 32	' Define Icons.

Const MB_ICONEXCLAMATION = 48, MB_ICONINFORMATION = 64

Const MB_DEFBUTTON2 = 256, IDYES = 6, IDNO = 7	' Define other.

Dim DgDef, Msg, Response, Title	' Declare variables.

Title = "MsgBox Demo"

' Put together a sample message box with all the proper components.

Msg = "This is a sample of a critical-error message."

Msg = Msg & " Do you want to continue?"

DgDef = MB_YESNO + MB_ICONSTOP + MB_DEFBUTTON2	' Describe dialog.

Response = MsgBox(Msg, DgDef, Title)	' Get user response.

If Response = IDYES Then	' Evaluate response

Msg = "You chose Yes."	' and take appropriate

Else	' action.

Msg = "You chose No or pressed Enter."

End If

MsgBox Msg	' Display action taken.

End Sub


SendKeys Statement

See Also	Example

Sends one or more keystrokes to the active window as if they had been entered at the keyboard.

Syntax

 SendKeys keytext [,wait]

Remarks

The SendKeys statement has these parts:

Part	Description

keytext	String expression sent to the active window.

wait	Numeric expression. If wait is True, keystrokes must be processed before control is returned to the procedure.  If wait is False, control is returned to the procedure immediately after the keys are sent.  If wait is omitted, False is assumed as the default.

Each key is represented by one or more characters.  To specify a single keyboard character, use the character itself.  For example, to represent the letter A, use "A" for keytext.  If you want to represent more than one character, append each additional character to the one preceding it.  To represent the letters A, B, and C, use "ABC" for keytext.

The plus sign (+), caret (^), percent sign (%), tilde (~), and parentheses ( ) have special meanings to SendKeys.  To specify one of these characters, enclose it inside braces.  For example, to specify the plus sign, use {+}.  Brackets ([ ]) have no special meaning to SendKeys, but you must enclose them in braces as well, because in other applications for Microsoft Windows, brackets do have special meaning that may be significant when dynamic data exchange (DDE) occurs.  To send brace characters, use {{} and {}}.

To specify characters that aren't displayed when you press a key (such as Enter or Tab) and keys that represent actions rather than characters, use the codes shown below:

Key	Code	Key	Code
Backspace	{BACKSPACE} or {BS} or {BKSP}	Break	{BREAK}
Caps Lock	{CAPSLOCK}	Clear	{CLEAR}
Del	{DELETE} or {DEL}	Down Arrow	{DOWN}
End	{END}	Enter	{ENTER} or ~
Esc	{ESCAPE} or {ESC}	Help	{HELP}
Home	{HOME}	Ins	{INSERT}
Left Arrow	{LEFT}	Num Lock	{NUMLOCK}
Page Down	{PGDN}	Page Up	{PGUP}
Print Screen	{PRTSC}	Right Arrow	{RIGHT}
Scroll Lock	{SCROLLLOCK}	Tab	{TAB}
Up Arrow	{UP}	F1	{F1}
F2	{F2}	F3	{F3}
F4	{F4}	F5	{F5}
F6	{F6}	F7	{F7}
F8	{F8}	F9	{F9}
F10	{F10}	F11	{F11}
F12	{F12}	F13	{F13}
F14	{F14}	F15	{F15}
F16	{F16}
To specify keys combined with any combination of Shift, Ctrl, and Alt keys, precede the regular key code with one or more of the following codes:

Key	Code

Shift	+

Control	^

Alt	%

To specify that Shift, Ctrl, and/or Alt should be held down while several other keys are pressed, enclose the keys' code in parentheses.  For example, to have the Shift key held down while E and C are pressed, use "+(EC)".  To have Shift held down while E is pressed, followed by C being pressed without Shift, use "+EC".

To specify repeating keys, use the form {key number};  you must put a space between key and number.  For example, {LEFT 42} means press the Left Arrow key 42 times; {h 10} means press h 10 times.

Note	SendKeys can't send keystrokes to an application that is not designed to run in Microsoft Windows.  Sendkeys also can't send the Print Screen (PRTSC) key to any application.


See Also

DoEvents Function, DoEvents Statement


SendKeys Statement Example

The example uses Shell to run the Calculator application included with Microsoft Windows; it then uses the SendKeys statement to send keystrokes to either quit the Calculator or add some numbers, depending on the user's choice.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, Msg, X	' Declare variables.

X = Shell("Calc.exe", 1)	' Shell Calculator.

For I = 1 To 100	' Set up counting loop.

SendKeys I & "{+}", True	' Send keystrokes to Calculator

Next I	'  to add each value of I.

SendKeys "=", True	' Get grand total.

AppActivate "Microsoft Visual Basic"	' Return focus to Visual Basic.

Msg = "Choose OK to close Calculator."	' Stop to see results.

MsgBox Msg

AppActivate "Calculator"	' Return focus to Calculator.

SendKeys "%{F4}", True	' Send Alt+F4 to close Calculator.

End Sub


AppActivate Statement

See Also	Example

Activates an application window.

Syntax

AppActivate titletext

Remarks

The argument titletext is a string expression that is the name that appears in the title bar of the application window to activate.  If there is more than one instance of the application, the operating environment arbitrarily selects the one to activate.  The name that appears in the title bar and titletext must match character-for-character, but the comparison is not case sensitive:  "Calculator" and "calculator" appear identical.

The AppActivate statement changes the focus to the named application 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.


See Also

Shell Function

SendKeys Statement


AppActivate Statement Example

The example uses the AppActivate statement to change focus between Visual Basic and the Microsoft Windows Calculator application.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim 	I, Msg, X	' Declare variables.

AppActivate "Microsoft Visual Basic"	' Change focus to Visual Basic.

SendKeys "%{ }{Down 3}{Enter}", True	' Minimize Visual Basic

X = Shell("Calc.exe", 1)	' Shell the Calculator.

For I = 1 To 100	' Set up counting loop.

SendKeys I & "{+}", True	' Send keystrokes to Calculator

Next I	'  to add each value of I.

SendKeys "=", True	' Get grand total.

AppActivate "Microsoft Visual Basic"	' Focus back to Visual Basic.

Msg = "Choose OK to close Calculator."	' Stop to see results.

MsgBox Msg

AppActivate "Calculator"	' Focus back to Calculator.

SendKeys "%{F4}", True	' Alt+F4 to close Calculator.

AppActivate "Microsoft Visual Basic"	' Change focus back to Visual Basic.

SendKeys "%{ }{Enter}", True	' Restore Visual Basic to size.

End Sub


AddItem Method

See Also	Example

Adds a new item to a list box or combo box or adds a new row to a grid control at run time.

Syntax.

control.AddItem item [,index]

Remarks

The AddItem method has these parts:

Part	Description

control	List box, combo box, or grid control.

item	String expression to add to the control. For grid controls only, use the tab character (character code 09) to separate multiple strings you want inserted into each column of a newly added row.

index	Integer representing the position within the control where the new item or row is placed.  For the first item in a list box or combo box, or for the first row in a grid control,  index = 0.

AddItem places item in the list box, combo box, or grid specified by control.  If you supply a valid value for the optional index, item is placed at that position within the control.  If index is omitted, item is added at the proper sorted position (if Sorted property is True), or to the end of the list (if Sorted is False).


See Also

Clear Method

RemoveItem Method


AddItem Method Example

The example uses AddItem to add 100 items to a list box.  To try this example, paste the code into the Declarations section of a form with a list box control named List1.  Then press F5 and click the form.

Sub Form_Click ()

Dim Entry, I, Msg	' Declare variables

Msg = "Choose OK to add 100 items to your list box."

MsgBox Msg	' Display message.

For I = 1 To 100	' Count from 1 to 100.

Entry = "Entry " & I	' Create entry.

List1.AddItem Entry	' Add the entry.

Next I

Msg = "Choose OK to remove every other entry."

MsgBox Msg	' Display message.

For I = 1 To 50	' Determine how to

List1.RemoveItem I	' remove every other

Next I	' item.

Msg = "Choose OK to remove all items from the list box."

MsgBox Msg	' Display message.

List1.Clear	' Clear list box.

End Sub


Clear Method

See Also	Syntax 1 Example	Syntax 2 Example

Clears the contents of a list box or combo box.  Alternatively, clears the contents of the operating environment Clipboard.

Syntax 1

control.Clear

Syntax 2

Clipboard.Clear

Remarks

In Syntax 1, control may either be a list box or a combo box.  In Syntax 2, only the special Clipboard object is allowed.


See Also

AddItem Method

Clipboard Object

RemoveItem Method


Clear Method - Syntax 1 Example

The example uses the Clear method to clear all items from a list box.  To try this example, paste the code into the Declarations section of a form with a list box control named List1.  Then press F5 and click the form.

Sub Form_Click ()

Dim Entry, I, Msg	' Declare variables

Msg = "Choose OK to add 100 items to your list box."

MsgBox Msg	' Display message.

For I = 1 To 100	' Count from 1 to 100.

Entry = "Entry " & I	' Create entry.

List1.AddItem Entry	' Add the entry.

Next I

Msg = "Choose OK to remove every other entry."

MsgBox Msg	' Display message.

For I = 1 To 50	' Determine how to

List1.RemoveItem I	' remove every other

Next I	' item.

Msg = "Choose OK to remove all items from the list box."

MsgBox Msg	' Display message.

List1.Clear	' Clear list box.

End Sub


Clear Method - Syntax 2 Example

The example uses the Clear method to clear the Clipboard.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Const CF_BITMAP = 2	' Define bitmap format.

Dim Msg	' Declare variable.

On Error Resume Next	' Set up error handling.

Msg = "Choose OK to load a bitmap onto the Clipboard."

MsgBox Msg	' Display message.

Clipboard.Clear	' Clear Clipboard.

Clipboard.SetData LoadPicture("PAPER.BMP")	' Get bitmap.

If Err Then

Msg = "Could not find the .BMP file."

MsgBox Msg	' Display error message.

Exit Sub

End If

Msg = "A bitmap is now on the Clipboard. Choose OK to copy "

Msg = Msg & "the bitmap from the Clipboard to the form."

MsgBox Msg	' Display message.

Picture = Clipboard.GetData()	' Copy from Clipboard.

Msg = "Choose OK to clear the picture box."

MsgBox Msg	' Display message.

Picture = LoadPicture()	' Clear picture box.

End Sub


Cls Method

See Also	Example

Clears graphics and text generated at run time from a form or picture.

Syntax

[object.]Cls

Remarks

The object can be a form or picture box control.  If object is omitted, Cls clears text and graphics from the current form.

Cls clears text and graphics generated at run time with graphics and printing statements.  Background bitmaps set using the Picture property and controls placed on the form at design time are not affected by Cls.  Graphics and text placed on a form, image, or picture box control while AutoRedraw property is True are also not affected if AutoRedraw is set to False before Cls is executed.  That is, some degree of permanence can be achieved by carefully manipulating the AutoRedraw property of a form, image, or picture box control.

After Cls is executed, the CurrentX and CurrentY properties of a form, image, or picture box control are reset to 0.


See Also

AutoRedraw Property

CurrentX Property

CurrentY Property


Cls Method Example

The example uses the Cls method to erase printed information on a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variable

AutoRedraw = -1	' Turn on AutoRedraw.

ForeColor = QBColor(15)	' Set foreground to white.

BackColor = QBColor(1) 	' Set background to blue.

FillStyle = 7	' Set diagonal crosshatch.

Line (0, 0)-(ScaleWidth, ScaleHeight), , B	' Put box on form.

Msg = "This is information printed on the form background."

CurrentX = ScaleWidth / 2 - TextWidth(Msg) / 2	' Set X position.

CurrentY = 2 * TextHeight(Msg)	' Set Y position.

Print Msg	' Print message to form.

Msg = "Choose OK to clear the information and background "

Msg = Msg & "pattern just displayed on the form."

MsgBox Msg	' Display message.

Cls	' Clear form background.

End Sub


Drag Method

See Also	Example

Begins, ends, or cancels dragging controls.

Syntax

[control.] Drag [action]

Remarks

The Drag method has the following parts:

Part	Description

control	Control to be dragged.  The Drag method can be used on any control except Line, Menu, Shape, or Timer.

action	Integer value from 0 to 2, inclusive, that indicates the action to perform.  If action is omitted, start dragging control.

Value	Meaning

0	Cancel drag operation..

1	Begin dragging control.

2	End dragging, that is, drop control.

Use of the Drag method to control dragging and dropping is required only when the DragMode property of the control to drag is set to 0 (Manual).  However, you may still use Drag on a control whose DragMode property is 1 (Automatic).

If you want the mouse pointer to change while the control is being dragged, use either the DragIcon property or the MousePointer property to define your pointer.  Note that the MousePointer property is only used if no DragIcon is specified.


See Also

DragDrop Event

DragIcon Property

DragMode Property

DragOver Event

MousePointer Property


Drag Method Example

The example uses the Drag method to drag the file name of a bitmap file to a picture box where the bitmap is displayed.  To try this example, paste all of the code into the Declarations section of a form that contains a drive list box, a directory list box, a file list box, a picture box, and a label.  Use the default names for the controls in all cases.  Size and position all controls so they can be easily seen and used.  The size and position of the label is unimportant as it will be changed at run time.  When the program begins you will be able to browse your file system and load any bitmaps.  Once you've located a bitmap that you want to display, click the file name of that bitmap and drag it to the picture control.

Sub Form_Load ()

Picture1.AutoSize = -1	' Turn on AutoSize.

Label1.Visible = 0	' Make the label invisible.

File1.Pattern = "*.BMP; *.ICO; *.WMF"	' Set file patterns.

End Sub

Sub Dir1_Change ()	' Any change in Dir1

File1.Path = Dir1.Path	' is reflected in File1.

End Sub

Sub Drive1_Change ()	' Any change in Drive1

Dir1.Path = Drive1.Drive	' is reflected in Dir1.

End Sub

Sub File1_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)

Dim DY	' Declare variable.

DY = TextHeight("A")	' Get height of one line.

Label1.Move File1.Left, File1.Top + Y - DY /2, File1.Width, DY

Label1.Drag	' Drag label outline.

End Sub

Sub Dir1_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

If State = 0 Then Source.MousePointer = 12	' Change pointer to no drop.

If State = 1 Then Source.MousePointer = 0	' Use default mouse pointer.

End Sub

Sub Drive1_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

If State = 0 Then Source.MousePointer = 12	' Change pointer to no drop.

If State = 1 Then Source.MousePointer = 0	' Use default mouse pointer.

End Sub

Sub Form_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

If State = 0 Then Source.MousePointer = 12	' Change pointer to no drop.

If State = 1 Then Source.MousePointer = 0	' Use default mouse pointer.

End Sub

Sub File1_DragOver (Source As Control, X As Single, Y As Single, State As Integer)

On Error Resume Next

If State = 0 And Right$(File1.Filename,4) = ".ico" Then

Label1.DragIcon = LoadPicture(File1.Path + "\" + File1.Filename)

If Err Then MsgBox "The icon file could not be loaded."

ElseIf State = 1 Then

Label1.DragIcon = LoadPicture ()	' Use no drag icon.

End If

End Sub

Sub Picture1_DragDrop (Source As Control, X As Single, Y As Single)

On Error Resume Next

Picture1.Picture = LoadPicture(File1.Path + "\" + File1.Filename)

If Err Then MsgBox "The picture file could not be loaded."

End Sub


GetData Method

See Also	Example

Returns a picture from the operating environment Clipboard object.

Syntax

Clipboard.GetData ([format])

Remarks

The argument format specifies one of the following Clipboard formats recognized by Visual Basic:

Symbolic constant	Value	Clipboard format

CF_BITMAP	2	Bitmap (.BMP files)

CF_METAFILE	3	Metafile (.WMF files)

CF_DIB	8	Device-independent bitmap

CF_PALETTE	9	Color palette

If format is 0 or omitted, GetData automatically uses the appropriate format.

If there is no picture on the Clipboard that matches the expected format, a null picture is returned.  If only a color palette is present on the Clipboard, a minimum size (1 x 1) device-independent bitmap is created.

Note	Symbolic constants for Clipboard format definitions can be found in the Visual Basic file CONSTANT.TXT.  When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

Clipboard Object

GetFormat Method

GetText Method

SetData Method


GetData Method Example

The example uses the GetData method to copy a bitmap from the Clipboard to a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Const CF_BITMAP = 2	' Define bitmap format.

Dim Msg	' Declare variable.

On Error Resume Next	' Set up error handling.

Msg = "Choose OK to load a bitmap onto the Clipboard."

MsgBox Msg	' Display message.

Clipboard.Clear	' Clear Clipboard.

Clipboard.SetData LoadPicture("PAPER.BMP")	' Get bitmap.

If Err Then

Msg = "Could not find the .BMP file."

MsgBox Msg	' Display error message.

Exit Sub

End If

Msg = "A bitmap is now on the Clipboard. Choose OK to copy "

Msg = Msg & "the bitmap from the Clipboard to the form "

MsgBox Msg	' Display message.

Picture = Clipboard.GetData()	' Copy from Clipboard.

Msg = "Choose OK to clear the picture box."

MsgBox Msg	' Display message.

Picture = LoadPicture()	' Clear picture box.

End Sub


GetFormat Method

See Also	Example

Returns an integer indicating whether there is an item in the operating environment Clipboard that matches a specified format.

Syntax

Clipboard.GetFormat (format)

Remarks

The argument format specifies one of the following Clipboard formats recognized by Visual Basic:

Symbolic constant	Value	Clipboard format

CF_LINK	&HBF00	DDE conversation information

CF_TEXT	1	Text

CF_BITMAP	2	Bitmap (.BMP files)

CF_METAFILE	3	Metafile (.WMF files)

CF_DIB	8	Device-independent bitmap

CF_PALETTE	9	Color palette

The GetFormat method returns True if there is an item on the Clipboard that matches the specified format.  Otherwise, it returns False.

For CF_DIB and CF_BITMAP formats, any palette on the Clipboard will be used when the picture is displayed.

Note  Symbolic constants for Clipboard format definitions can be found in the Visual Basic file CONSTANT.TXT.  When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

Clipboard Object

GetData Method

GetText Method


GetFormat Method Example

The example uses the GetFormat method to determine the format of data on the Clipboard.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

' Define bitmap formats.

Const CF_TEXT = 1, CF_BITMAP = 2, CF_DIB = 8, CF_PALETTE = 9

Dim ClpFmt, Msg	' Declare variables

On Error Resume Next	' Set up error handling.

If Clipboard.GetFormat(CF_TEXT) Then ClpFmt = ClpFmt + 1

If Clipboard.GetFormat(CF_BITMAP) Then ClpFmt = ClpFmt + 2

If Clipboard.GetFormat(CF_DIB) Then ClpFmt = ClpFmt + 4

Select Case ClpFmt

Case 1

Msg = "The Clipboard contains only text."

Case 2, 4, 6

Msg = "The Clipboard contains only a bitmap."

Case 3, 5, 7

Msg = "The Clipboard contains text and a bitmap."

Case Else

Msg = "There is nothing on the Clipboard."

End Select

MsgBox Msg	' Display message.

End Sub


GetText Method

See Also	Example

Returns a text string from the operating environment Clipboard.

Syntax

Clipboard.GetText ([format])

Remarks

The argument format specifies one of the following Clipboard formats recognized by Visual Basic:

Symbolic constant	Value	Clipboard format

CF_LINK	&HBF00	DDE conversation information

CF_TEXT	1	Text

If format is omitted, CF_TEXT is assumed.

If there is no text string on the Clipboard that matches the expected format, a zero-length string ("") is returned.

Note	Symbolic constants for Clipboard format definitions can be found in the Visual Basic file CONSTANT.TXT.  When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

Clipboard Object

GetData Method

GetFormat Method

SetText Method


GetText Method Example

The example uses the GetText method to copy a text string from the Clipboard to a string variable.  To try this example, paste the code into the Declarations section of a form with a text box named Text1.  Then press F5 and click the form.

Sub Form_Click ()

Const CF_TEXT = 1	' Define bitmap format.

Dim I, Msg, Temp	' Declare variables

On Error Resume Next	' Set up error handling.

Msg = "Type anything you like into the text box below."

Text1.Text = InputBox(Msg)	' Get text from user.

Msg = "Choose OK to copy the contents of the text box "

Msg = Msg & "to the Clipboard."

MsgBox Msg	' Display message.

ClipBoard.Clear	' Clear Clipboard.

Clipboard.SetText Text1.Text	' Put text on Clipboard.

If Clipboard.GetFormat(CF_TEXT) Then

Text1.Text = ""	' Clear the text box.

Msg = "The text is now on the Clipboard. Choose OK "

Msg = Msg & "to copy the text from the Clipboard back "

Msg = Msg & "to the text box."

MsgBox Msg	' Display message.

Temp = Clipboard.GetText(CF_TEXT)	' Get Clipboard text.

For I = Len(Temp) To 1 Step -1	' Reverse the text.

Text1.Text = Text1.Text & Mid(Temp, I, 1)

Next I

Else

Msg = "There is no text on the Clipboard."

MsgBox Msg	' Display error message.

End If

End Sub


Hide Method

See Also	Example

Hides a form, but does not unload it.

Syntax

[form.]Hide

Remarks

The argument form is the name of the form or MDI form to hide.

When a form is hidden, it is removed from the screen and its Visible property is set to False .  A hidden form's controls are not accessible to the user, but they are available to the running Visual Basic program, to other processes that may be communicating with the application through dynamic data exchange (DDE), and to timer events.

When a form is hidden, control does not return to the user until all code in the event procedure that caused the form to be hidden has finished executing.

If the form is not loaded when the Hide method is invoked, it is loaded, but not shown.

While you can use the Hide method to hide an MDI form, you cannot hide an MDI child form.


See Also

Load Statement

Show Method

Unload Statement

Visible Property


Hide Method Example

The example uses the Hide method to hide a form.  To try this example, paste the code into the Declarations section of a non-MDI form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variable

Hide	' Hide form.

Msg = "Choose OK to make the form reappear."

MsgBox Msg	' Display message.

Show	' Show form again.

End Sub


Load Statement

See Also	Example

Loads a form or control into memory.

Syntax

Load object

Remarks

The argument object is a form, MDI form, or control array element to load.

It is not necessary to use the Load statement with forms unless you want to load a form without displaying it.  Any reference to a form (except in a Set or If...TypeOf statement) automatically loads it if it is not already loaded.  For example, the Show method loads an unloaded form before displaying it.  Once the form is loaded, all properties for the form and its controls can be altered by the program, whether or not the form is actually visible.  Under some circumstances, you may want to load all your forms during initialization and display them later as they are needed.

When more than one instance of a form is loaded, each form has its own set of properties and variables that can be changed independently from all other instances of the form.

When Visual Basic loads a form, it sets form properties to their initial values, then performs the Load event procedure.  When an application starts, Visual Basic automatically loads and displays the application's start up form.

If you load an MDI child form before loading the MDI form, the MDI form is automatically loaded before the child form is loaded.  Loading an MDI child form causes it to be visible immediately after the Form_Load event ends because MDI child forms cannot be hidden.

The standard dialog boxes produced by Visual Basic functions such as MsgBox and InputBox do not need to be loaded, shown, or unloaded, but can simply be invoked directly.


See Also

Hide Method

InputBox Function

MsgBox Function

Show Method

Unload Statement


Load Statement Example

The example uses the Load statement to load a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Answer, Msg	' Declare variable.

Unload Form1	' Unload form.

Msg = "Form1 has been unloaded. Choose Yes to load and "

Msg = Msg & "display the form. Choose No to load the form "

Msg = Msg & "and leave it invisible."

Answer = MsgBox(Msg, 4)	' Get user response.

If Answer = 6 Then	' Evaluate answer.

Show	' If Yes, show form.

Else

Load Form1	' If No, just load it.

Msg = "Form1 is now loaded. Choose OK to display it."

MsgBox Msg	' Display message.

Show	' Show form.

End If

End Sub


LoadPicture Function

See Also	Example

Loads a picture into a form, picture box, or image control.

Syntax

LoadPicture([stringexpression])

Remarks

The argument stringexpression is the name of a picture file to be loaded.  Pictures are cleared from forms, picture boxes, and image controls by assigning LoadPicture with no argument.

Picture files recognized by Visual Basic include bitmaps (.BMP), icons (.ICO), run-length encoded files (.RLE), and metafile (.WMF) files.

To load pictures for display in a picture box, image control, or as the background of a form, the return value of LoadPicture must be assigned to the Picture property of the object on which the picture is displayed.  For example:

Picture = LoadPicture("PARTY.BMP")

Picture1.Picture = LoadPicture("PARTY.BMP")

To load icon files (.ICO) to the form icon, the return value of LoadPicture must be assigned to the Icon property of form:

Icon = LoadPicture("MYICON.ICO")

Icons can also be assigned to the DragIcon property of all controls except timers and menus.  For example:

Command1.DragIcon = LoadPicture("MYICON.ICO")

Load a picture file into the operating environment Clipboard using LoadPicture as follows:

Clipboard.SetData LoadPicture("PARTY.BMP")


See Also

DragIcon Property

Icon Property

Picture Property

SavePicture Statement

SetData Method


LoadPicture Function Example

The example uses the LoadPicture function to load a picture into a form and to clear the picture from the form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variables.

On Error Resume Next	' Set up error handling.

Height = 3990: Width = 4890	' Set height and width.

Picture = LoadPicture("PAPER.BMP")	' Load bitmap.

If Err Then

Msg = "Could not find the .BMP file."

MsgBox Msg	' Display error message.

Exit Sub	' Quit if error occurs.

End If

Msg = "Choose OK to clear the bitmap from the form."

Msgbox Msg

Picture = LoadPicture()	' Clear form.

End Sub


Move Method

See Also	Example

Moves a form or control.

Syntax

[object.]Move left[, top[, width[, height] ] ]

Remarks

The Move method has these parts:

Part	Description

object	Form or control to move.  May be any control except timers and menus.

left	Single-precision value indicating the horizontal coordinate for the left edge of object.

top	Single-precision value indicating the vertical coordinate for the top edge of object.

width	Single-precision value indicating the new width of object.

height	Single-precision value indicating the new height of object.

Only the left argument is required.  However, to specify any other arguments, you must specify all arguments that appear in the syntax before the argument you want to specify.  For example, you cannot specify width without specifying left and top.  Any trailing arguments that are unspecified remain unchanged.

For forms and for controls within frames, the coordinate system is always twips.  Moving a form on the screen or moving a control within a frame is always relative to the origin (0,0), which is the upper-left corner.  When moving controls on a form or in a picture control, the coordinate system of the object is used.  The coordinate system is set using ScaleHeight, ScaleWidth, ScaleLeft and ScaleRight properties.


See Also

Height Property

Left Property

ScaleHeight Property

ScaleLeft Property

ScaleMode Property

ScaleWidth Property

Top Property

Width Property


Move Method Example

The example uses the Move method to move a form around on the screen.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim In, Msg	' Declare variables.

Msg = "Choose OK to resize and move this form by "

Msg = Msg & "changing the value of properties."

MsgBox Msg	' Display message.

In = 1440	' Set inch in twips.

Width = 4 * In	' Set width.

Height = 2 * In	' Set height.

Left = 0	' Set left to origin.

Top = 0	' Set top to origin.

Msg = "Now choose OK to resize and move this form "

Msg = Msg & "using the Move Method."

MsgBox Msg	' Display message.

Move Screen.Width - 2 * In, Screen.Height - In, 2 * In, In

End Sub


RemoveItem Method

See Also	Example

Removes an item from a list box or combo box or removes a row from a grid control at run time

Syntax.

control.RemoveItem index

Remarks

The RemoveItem method has these parts:

Part	Description

control	List box, combo box, or grid control.

index	Integer representing the position within the control of the item or row to remove.  For the first item in a list box or combo box, or for the first row in a grid control,  index = 0.


See Also

AddItem Method

Clear Method


RemoveItem Method Example

The example uses RemoveItem to remove entries from a list box.  To try this example, paste the code into the Declarations section of a form with a list box control named List1.  Then press F5 and click the form.

Sub Form_Click ()

Dim Entry, I, Msg	' Declare variables.

Msg = "Choose OK to add 100 items to your list box."

MsgBox Msg	' Display message.

For I = 1 To 100	' Count from 1 to 100.

Entry = "Entry " & I	' Create entry.

List1.AddItem Entry	' Add the entry.

Next I

Msg = "Choose OK to remove every other entry."

MsgBox Msg	' Display message.

For I = 1 To 50	' Determine how to

List1.RemoveItem I	' remove every other

Next I	' item.

Msg = "Choose OK to remove all items from the list box."

MsgBox Msg	' Display message.

List1.Clear	' Clear list box.

End Sub


SavePicture Statement

See Also	Example

Saves a picture from a form, picture box, or image control into a file.

Syntax

SavePicture picture, stringexpression

Remarks

The SavePicture statement has these parts:

Part	Description

picture	Picture or Image property from which the picture file is to be created.

stringexpression	File name of the picture file to save.

If a picture was loaded from file to the Picture property, either at design time or at run time, it is saved using the same format as the original file. Pictures from the Image property are always saved as bitmap (.BMP) files.


See Also

Image Property

LoadPicture Function

Picture Property


SavePicture Statement Example

The example uses the SavePicture statement to save a picture drawn on a form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim CX, CY, Limit, Msg, Radius	' Declare variables.

ScaleMode = 3	' Set scale to pixels.

AutoRedraw = -1	' Turn on AutoRedraw.

Width = Height	' Change width to match height.

CX = ScaleWidth / 2	' Set X position.

CY = ScaleHeight / 2	' Set Y position.

Limit = CX	' Limit size of circles.

For Radius = 0 To Limit	' Set radius.

Circle (CX, CY), Radius, RGB(Rnd * 255, Rnd * 255, Rnd * 255)

DoEvents	' Yield for other processing.

Next Radius

Msg = "Choose OK to save the graphics from this form "

Msg = Msg & "to a bitmap file."

MsgBox Msg

SavePicture Image, "TEST.BMP"	' Save picture to file.

End Sub


SetData Method

See Also	Example

Puts a picture in the operating environment Clipboard using the specified format.

Syntax

Clipboard.SetData data,[ format]

Remarks

The SetData method has these parts:

Part	Description

data	Picture (Image or Picture property) to place on the Clipboard.

format	One of the following Clipboard formats recognized by Visual Basic. If format is 0 or omitted, SetData automatically determines the format.

Symbolic constant	Value	Clipboard format

CF_BITMAP	2	Bitmap (.BMP files)

CF_METAFILE	3	Metafile (.WMF files)

CF_DIB	8	Device-independent bitmap

CF_PALETTE	9	Color palette

For the CF_BITMAP format, any associated color palette will be copied to the Clipboard along with the bitmap.

Note  Symbolic constants for Clipboard format definitions can be found in the Visual Basic file CONSTANT.TXT. When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

Clipboard Object

GetData Method

GetFormat Method


SetData Method Example

The example uses the SetData method to place a bitmap onto the Clipboard.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Const CF_BITMAP = 2	' Define bitmap format.

Dim Msg	' Declare variable.

On Error Resume Next	' Set up error handling.

Msg = "Choose OK to load a bitmap onto the Clipboard."

MsgBox Msg	' Display message.

Clipboard.Clear	' Clear Clipboard.

Clipboard.SetData LoadPicture("PAPER.BMP") ' Get bitmap.

If Err Then

Msg = "Could not find the .BMP file."

MsgBox Msg	' Display error message.

Exit Sub

End If

Msg = "A bitmap is now on the Clipboard. Choose OK to copy "

Msg = Msg & "the bitmap from the Clipboard to the form "

MsgBox Msg	' Display message.

Picture = Clipboard.GetData()	' Copy from Clipboard.

Msg = "Choose OK to clear the picture box."

MsgBox Msg	' Display message.

Picture = LoadPicture()	' Clear picture box.

End Sub


SetFocus Method

See Also	Example

Sets the focus to a form or control.

Syntax

object.SetFocus

Remarks

The object must be a form, MDI form, or control  which can gain the focus.  The SetFocus method can be used on any control except Frame, Image, Line, Menu, Shape and Timer.  After SetFocus is executed, any user input is directed to the specified form or control.

You can only set focus to a visible form or control.  Since a form and controls on a form are not visible until the form's Load event has finished, you cannot use SetFocus to set the focus to the form being loaded in its own Load event unless you also use the Show method to show the form before the completion of the Form_Load procedure.

You also cannot set the focus to a form or control if the Enabled property is set to False.  If the Enabled property has been set to False at design time, you must first set it to True before it can gain the focus using SetFocus.


See Also

Enabled Property

Load Event

Show Method


SetFocus Method Example

The example uses the SetFocus method to change focus between two command buttons.  To try this example, paste the code into the Declarations section of a form named Form1 that has two command buttons.  Use the default names for the command buttons.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg	' Declare variable

Msg = "Choose OK to watch the focus change to the other control."

MsgBox Msg	' Display message.

If Screen.ActiveControl.Caption = "Command1" Then

Command2.SetFocus	' Set focus to button 2.

Else

Command1.SetFocus	' Set focus to button 1.

End If

End Sub


SetText Method

See Also	Example

Puts a text string in the operating environment Clipboard using the specified Clipboard format.

Syntax

Clipboard.SetText data [,format]

Remarks

The SetText method has these parts:

Part	Description

data	String data to be placed on the Clipboard.

format	One of the following Clipboard formats recognized by Visual Basic.  If format is omitted, CF_TEXT is assumed.

Symbolic constant	Value	Clipboard format

CF_LINK	&HBF00	DDE conversation information

CF_TEXT	1	Text

Note  Symbolic constants for Clipboard format definitions can be found in the Visual Basic file CONSTANT.TXT. When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

Clipboard Object

GetFormat Method

GetText Method

SetData Method


SetText Method Example

The example uses the SetText method to copy text from a text box to the Clipboard. To try this example, paste the code into the Declarations section of a form with a text box named Text1. Then press F5 and click the form.

Sub Form_Click ()

Const CF_TEXT = 1	' Define bitmap format.

Dim I, Msg, Temp	' Declare variables.

On Error Resume Next	' Set up error handling.

Msg = "Type anything you like into the text box below."

Text1.Text = InputBox(Msg)	' Get text from user.

Msg = "Choose OK to copy the contents of the text box "

Msg = Msg & "to the Clipboard."

MsgBox Msg	' Display message.

ClipBoard.Clear	' Clear Clipboard.

Clipboard.SetText Text1.Text	' Put text on Clipboard.

If Clipboard.GetFormat(CF_TEXT) Then

Text1.Text = ""	' Clear the text box.

Msg = "The text is now on the Clipboard. Choose OK "

Msg = Msg & "to copy the text from the Clipboard back "

Msg = Msg & "to the text box."

MsgBox Msg	' Display message.

Temp = Clipboard.GetText(CF_TEXT)	' Get Clipboard text.

For I = Len(Temp) To 1 Step -1	' Reverse the text.

Text1.Text = Text1.Text & Mid(Temp, I, 1)

Next I

Else

Msg = "There is no text on the Clipboard."

MsgBox Msg	' Display error message.

End If

End Sub


Unload Statement

See Also	Example

Unloads a form or control from memory.

Syntax

Unload object

Remarks

The argument object is the form or control array element to unload.

Unloading a form or control may be necessary or expedient in some cases where the memory used is needed for something else or when you need to reset properties to their original value.

Before a form is unloaded, the Query_Unload event occurs, followed by the Form_Unload event.  Setting the Cancel argument to True in either of these events keeps the form from being unloaded.  For MDI forms, the MDI form Query_Unload event occurs, followed by the Query_Unload event and Form_Unload event for each MDI child form, and finally the MDI form Form_Unload event

When a form is unloaded, all controls placed on the form at run time are no longer accessible.  Controls placed on the form at design time remain intact, although any run-time changes to those controls and their properties are lost when the form is reloaded.  All changes to form properties are also lost.  Note that when a form is unloaded, only the displayed component is unloaded.  The code associated with the form module remains in memory.

Only control array elements added to a form at run-time can be unloaded with the Unload statement.  The properties of unloaded controls are reinitialized when the controls are reloaded.


See Also

Hide Method

Load Statement

QueryUnload Event

Show Method


Unload Statement Example

The example uses the Unload statement to unload a form.  To try this example, paste the code into the Declarations section of a form named Form1.  Then press F5 and click the form.

Sub Form_Click ()

Dim Answer, Msg	' Declare variables

Unload Form1	' Unload form.

Msg = "Form1 has been unloaded. Choose Yes to load and "

Msg = Msg & "display the form. Choose No to load the form "

Msg = Msg & "and leave it invisible."

Answer = MsgBox(Msg, 4)	' Get user response.

If Answer = 6 Then	' Evaluate answer.

Show	' If Yes, show form.

Else

Load Form1	' If No, just load it.

Msg = "Form1 is now loaded. Choose OK to display it."

MsgBox Msg	' Display message.

Show	' Show form.

End If

End Sub


As

The As reserved word is used in these Visual Basic topics:

Declare Statement

Dim Statement

Function Statement

Global Statement

Name Statement

Open Statement

ReDim Statement

Static Statement

Sub Statement


ByVal

The ByVal reserved word is used in these Visual Basic topics:

Call Statement

Declare Statement

Function Statement

Sub Statement


Else

The Else reserved word is used in these Visual Basic topics:

If...Then...Else Statement

Select Case Statement


Is

The Is reserved word is used in these Visual Basic topics:

If...Then...Else Statement

Is Operator

Select Case Statement


New

The New reserved word is used in these Visual Basic topics:

Dim Statement

Global Statement

Set Statement

Static Statement


Step

The Step reserved word is used in these Visual Basic topics:

Circle Method

For...Next Statement

Line Method

PSet Method


To

The To reserved word is used in these Visual Basic statements:

Dim Statement

For...Next Statement

Global Statement

Lock, Unlock Statements

ReDim Statement

Select Case Statement

Static Statement


Private

The Private reserved word is used in these Visual Basic topics:

Function Statement

Sub Statement


On

The On reserved word is used in these Visual Basic topics:

On Error Statement

On...GoSub, On...GoTo Statements


Next

The Next reserved word is used in these Visual Basic topics:

For...Next Statement

On Error Statement

Resume Statement


Option

The Option reserved word is used in these Visual Basic topics:

Option Base Statement

Option Compare Statement

Option Explicit Statement


True

An intrinsic constant whose value is equal to -1.  Because True is a reserved word, you cannot have any other constant, variable, or procedure whose name is True.


False

An intrinsic constant whose value is equal to 0.  Because False is a reserved word, you cannot have any other constant, variable, or procedure whose name is False.


Me

See Also

Me is a reserved word in Visual Basic that behaves like an implicitly declared variable.  It is automatically available to every procedure (Sub or Function) in a form.  In an environment where you can have more than one instance of a form, Me provides a way to refer to the specific instance of the form where the code is executing.  Using Me is particularly useful when you want to pass information about the current instance of a form 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 the procedure and pass the current instance of the form as an argument using the following statement in one of the procedures in your form:

ChangeFormColor Me

In most cases the form referred to by Me is the same as the form referred to by Screen.ActiveForm.  However, it is possible for the two to be different.  Screen.ActiveForm always refers to the form that has the focus while Me always refers to the form where code is executing.  For example, a Timer event can occur in a form that does not have the focus.  When that happens, Screen.ActiveForm refers to the form with focus, while Me refers to the form where the Timer event occurred.


See Also

ActiveForm Property


Arrange Method

See Also	Example

Arranges the windows or icons within an MDI Form.

Syntax

mdiform.Arrange arrangement

Remarks

The Arrange method has these parts:

Part	Description

mdiform	Name of the MDI form whose child windows or icons are to be arranged.

arrangement	One of the following values that indicate how to arrange windows or icons on an MDI Form:

Symbolic constant	Value	Meaning
CASCADE	0	Cascade all non-minimized MDI child forms.
TILE_HORIZONTAL	1	Tile all non-minimized MDI child forms horizontally.
TILE_VERTICAL	2	Tile all non-minimized MDI child forms vertically.
ARRANGE_ICONS	3	Arrange icons for minimized MDI child forms.
Windows or icons are arranged even if the MDI form is minimized.  Results are visible when the form is next changed from the minimized state

Note	Symbolic constants for arrangement definitions can be found in the Visual Basic file CONSTANT.TXT.  When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

ZOrder Method


Arrange Method Example

The example uses the Arrange method to arrange windows and icons in an MDI form.  To try this example, paste the code into the Declarations section of an MDI Form named MDIForm1 that has an MDI child form (named Form1), and a picture box (named Picture1).  Then press F5 and click anywhere in the picture box to see the effects of the Arrange method.

Const FORMCOUNT = 5

Dim F(1 To FORMCOUNT) As New Form1

Sub MDIForm_Load ()

Dim I	' Declare local variable.

Load Form1	' Load original Form1.

For I = 1 To FORMCOUNT

F(I).Caption = "Form" & I + 1	' Change caption on copies.

Next I

End Sub

Sub Picture1_Click ()

Static ClickCount	' Declare variables.

Dim I, PrevWidth, Start

ClickCount = ClickCount + 1	' Increment click counter.

Select Case ClickCount

Case 1

MDIForm1.Arrange 1	' Tile horizontally.

Case 2

MDIForm1.Arrange 2	' Tile vertically.

Case 3	' Minimize each form.

PrevWidth = MDIForm1.Width	' Get MDIForm width.

MDIForm1.Width = PrevWidth / 2	' Divide it in half.

Form1.WindowState = 1	' Minimize the original.

For I = 1 To FORMCOUNT	' Look at each instance of F.

F(I).WindowState = 1	' Minimize each copy of F.

Next I

Start = Timer

Do

Loop Until Timer = Start + 5

MDIForm1.Width = PrevWidth	' Resize to original size

MDIForm1.Arrange 3	' Arrange icons

End Select

End Sub


FileCopy Statement

See Also	Example

Copies a file.

Syntax

FileCopy srcfile, destfile

Remarks

The FileCopy statement has these parts:

Part	Description

srcfile	Any string expression that contains an unambiguous (no wildcards) file specification for the file to copy.  The file specification may include optional drive and path information.

destfile	Any string expression that contains an unambiguous (no wildcards) file specification for the file where srcfile is to be copied.  The file specification may also include optional drive and path information.

You cannot copy a file that is already opened by Visual Basic for anything but read-only access.


See Also

Kill Statement

Name Statement


FileCopy Statement Example

The example uses FileCopy to copy one file to another.  When you choose the name of a file in the file list box, you are prompted to enter a destination file name.  To try this example, paste the code into the Declarations section of a form that contains a file list box named File1.  Then press F5 to start.

Sub File1_Click ()

Dim DestFile, Msg	' Declare variables.

On Error GoTo ErrHandler

DestFile = InputBox("Copy to where?")

FileCopy File1.FileName, DestFile	' Copy file to destination.

Exit Sub

ErrHandler:

If Err = 55 Then 	' File already open.

MsgBox "Cannot copy an open file. Close it and try again."

Else

MsgBox "You must specify a complete destination file name."

End If

Resume Next

End Sub


FileDateTime Function

See Also	Example

Returns a String that indicates the date and time a specified file was created or last modified.

Syntax

FileDateTime (filename)

Remarks

The argument filename can be any string expression that contains an unambiguous (no wildcards) file specification.  The file specification may include optional drive and path information.


See Also

FileLen Function

GetAttr Function


FileDateTime Function Example

The example uses FileDateTime to get date and time information about when a file was created or last modified.  File date and time information is displayed in a message box anytime you choose the name of a file in the file list box.  To try this example, paste the code into the Declarations section of a form containing a file list box named File1.  Then press F5 to start.

Sub File1_Click ()

Dim Msg, TimeStamp	' Declare variables.

FName = File1.FileName	' Get selected file name.

TimeStamp = FileDateTime(FName)	' Get file date/time info.

Msg = UCase(FName) & " was created or last modified on "

Msg = Msg & Format(TimeStamp, "dddddd") & " at "

Msg = Msg & Format(TimeStamp, "h:mm AM/PM") & ".  Its size is "

Msg = Msg & FileLen(FName) & " bytes."	' Get file size.

MsgBox Msg	' Display message.

End Sub


FileLen Function

See Also	Example

Returns a Long integer that indicates the length of a file in bytes.

Syntax

FileLen (filename)

Remarks

The argument filename can be any string expression that contains an unambiguous (no wildcards) file specification.  The file specification may include optional drive and path information.

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


See Also

FileDateTime Function

GetAttr Function

LOF Function


FileLen Function Example

The example uses FileLen to get file size information about a file.  File size information is displayed in a message box anytime you choose the name of a file in the file list box.  To try this example, paste the code into the Declarations section of a form containing a file list box named File1.  Then press F5 to start.

Sub File1_Click ()

Dim Msg, TimeStamp	' Declare variables.

FName = File1.FileName	' Get selected file name.

TimeStamp = FileDateTime(FName)	' Get file date/time info.

Msg = UCase(FName) & " was created or last modified on "

Msg = Msg & Format(TimeStamp, "dddddd") & " at "

Msg = Msg & Format(TimeStamp, "h:mm AM/PM") & ".  Its size is "

Msg = Msg & FileLen(FName) & " bytes."	' Get file size.

MsgBox Msg	' Display message.

End Sub


GetAttr Function

See Also	Example

Returns an integer that indicates a file, directory, or volume label's attributes.

Syntax

GetAttr (filename)

Remarks

The argument filename can be any string expression that contains an unambiguous file, directory, or volume label specification.  The file specification may include optional drive and path information.

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

Symbolic constant	Value	Meaning
ATTR_NORMAL	0	Normal file
ATTR_READONLY	1	Read-only file
ATTR_HIDDEN	2	Hidden file
ATTR_SYSTEM	4	System file
ATTR_VOLUME	8	Volume label
ATTR_DIRECTORY	16	MS-DOS directory
ATTR_ARCHIVE	32	File has changed since last back-up
To determine which attributes are set, use the And operator to perform a bit-wise 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 Archive attribute is set if the return value of the following And expression is anything but zero, and zero if the Archive attribute is not set:

Result = GetAttr(FName) And ATTR_ARCHIVE

Note	Symbolic constants for file attribute definitions can be found in the Visual Basic file CONSTANT.TXT.  When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

FileAttr Function

SetAttr Statement


GetAttr Function Example

The example uses the GetAttr function to determine the attributes of a file.  Choosing any file in the list box will cause a message box to appear that indicates the files' attributes.  To try this example, paste the code into the Declarations section of a form containing a drive list box, a directory list box, and a file list box, all with default control names.  Set the Hidden and System properties of the file list box to True.  Then press F5 to start.

Sub Drive1_Change ()

Dir1.Path = Drive1.Drive	' Change if drive changes.

End Sub

Sub Dir1_Change ()

File1.Path = Dir1.Path	' Change if directory changes.

End Sub

Sub File1_Click ()

Const ATTR_READONLY = 1, ATTR_HIDDEN = 2	' Declare constants.

Const ATTR_SYSTEM = 4, ATTR_ARCHIVE = 32

Dim Attr, FName, Msg	' Declare variables.

If Right(Dir1.Path,1)="\" Then	' See if root file.

FName = Dir1.Path & File1.FileName	' Get file path.

Else

FName = Dir1.Path & "\" & File1.FileName	' Get file path.

End If

Attr = GetAttr(FName)	' Get attributes.

If Attr > 7 Then Attr = Attr Xor ATTR_ARCHIVE	' Disregard Archive

Select Case Attr	' Look up attributes.

Case 0: Msg = "Normal"

Case ATTR_READONLY: Msg = "Read-Only"

Case ATTR_HIDDEN: Msg = "Hidden"

Case ATTR_HIDDEN + ATTR_READONLY: Msg = "Hidden and Read-Only"

Case ATTR_SYSTEM: Msg = "System"

Case ATTR_READONLY + ATTR_SYSTEM: Msg = "Read-Only and System"

Case ATTR_HIDDEN + ATTR_SYSTEM: Msg = "Hidden and System"

Case ATTR_READONLY + ATTR_HIDDEN + ATTR_SYSTEM: Msg = "Read-Only, Hidden, and System"

End Select

MsgBox UCase(FName) & " is a " & Msg & " file."	' Display message.

End Sub


SetAttr Statement

See Also	Example

Sets attribute information for a file.

Syntax

SetAttr filename, attributes

Remarks

The SetAttr statement has the following parts:

Part 	Description

filename	Any string expression that contains an unambiguous (no wildcards) file specification.  The file specification may include optional drive and path information.

attributes	The sum of any of the following values that characterize file attributes as shown:

Symbolic constant	Value	Meaning
ATTR_NORMAL	0	Normal file
ATTR_READONLY	1	Read-only file
ATTR_HIDDEN	2	Hidden file
ATTR_SYSTEM	4	System file
ATTR_ARCHIVE	32	File has changed since last back-up
If you try to set the attributes of a file that is already opened by Visual Basic for anything but read-only access, a run-time error occurs.

Note	Symbolic constants for file attribute definitions can be found in the Visual Basic file CONSTANT.TXT.  When placed in any module in a project, the symbolic names can be used in all your form and code modules.


See Also

FileAttr Function

GetAttr Statement


SetAttr Statement Example

The example uses the SetAttr statement to set the Archive attribute of a selected file.  Choosing any file in the list box will cause the Archive attribute to be set for that file if it is not already.  To try this example, paste the code into the Declarations section of a form containing a drive list box, a directory list box, and a file list box, all with default control names.  Then press F5 to start.

Sub Drive1_Change ()

Dir1.Path = Drive1.Drive	' Change if drive changes.

End Sub

Sub Dir1_Change ()

File1.Path = Dir1.Path	' Change if directory changes.

End Sub

Sub File1_Click ()

Const ATTR_ARCHIVE = 32	' Declare constants.

Dim Fname	' Declare variables.

If Right(Dir1.Path, 1) = "\" Then	' See if root.

FName = UCase(Dir1.Path & File1.FileName)	' Get path.

Else

FName = UCase(Dir1.Path & "\" & File1.FileName)	' Get path.

End If

If GetAttr(FName) And ATTR_ARCHIVE Then	' Check for Archive.

MsgBox FName & " already has the Archive attribute."

Else

SetAttr FName, ATTR_ARCHIVE	' Set Archive.

MsgBox FName & " now has the Archive attribute."

End If

End Sub


ZOrder Method

See Also	Example

Places a specified form or control at the front or back of the z-order within its graphical level.

Syntax

[object.]ZOrder [position]

Remarks

The ZOrder method has these parts:

Part	Description

object	Form, MDI form, or control to be positioned. For controls, object can be any control except a menu or timer.

position	Integer indicating the position of the control relative to other controls.  If position is 0 or omitted, the control is positioned at the front of the z-order.  If position is 1, the control appears at the back of the z-order.

The z-order of controls can be set at design time using Bring To Front and Send To Back choices on the Edit menu.

Within MDI forms, the ZOrder method sends MDI child forms to either the front or the back of the MDI client area, depending on the value of position.  For forms and MDI forms, ZOrder sends the form to either the front or the back of the screen, depending on the value of position.  As a result, forms may appear in front of or behind other running applications.

Note	There are three graphical layers associated with forms and containers.  The back layer is the drawing space, where the results of the graphics methods appear. Next is the middle layer where graphical controls and labels appear.  The front layer is where all non-graphical controls like command buttons, check boxes, and file controls appear.  Anything in one layer covers anything in the layer behind.  The ZOrder method arranges controls only within the layer where the control appears.


See Also

Arrange Method


ZOrder Method Example

The example uses the ZOrder method to position command buttons on a form.  Choosing each button brings it to the front of the z-order.  To try this example, paste the code into the Declarations section of a form that contains a single command button named Command1 whose Index property is set to 0, indicating a control array.  Then press F5 to start.

Sub Form_Load ()

Dim I	' Declare variable.

For I = 1 To 5

Load Command1(I)	' Load new command button.

Command1(I).Left = Command1(I - 1).Left + 250	' Change position.

Command1(I).Top = Command1(I - 1).Top + 250

Command1(I).Caption = "Command" & I + 1	' Change caption.

Command1(I).Visible = True	' Make visible.

Next I

End Sub

Sub Command1_Click (Index As Integer)

Command1(Index).ZOrder 0	' Position button to front.

End Sub


Operator Precedence

See Also

When several operations occur in an expression, each part is evaluated and resolved in a predetermined order.  That order is known as operator precedence.  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, normal operator precedence is maintained.

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.  Within individual categories, operators are evaluated in the order of precedence shown below:

Arithmetic	Comparison	Logical
Exponentiation (^)	Equality (=)	Not
Negation ( - )	Inequality (<>)	And
Multiplication and division (*, / )	Less than (<)	Or
Integer division (\)	Greater than (>)	Xor
Modulo arithmetic (Mod)	Less than or Equal to (<=)	Eqv
Addition and subtraction (+, -)	Greater than or Equal to (>=)	Imp
String concatenation (&)	Like
	Is
Note	All comparison operators have equal precedence, that is, they are evaluated in the left-to-right order in which they appear.

When multiplication and division occur together in an expression, each operation is evaluated as it occurs from left to right.  Likewise, when addition and subtraction occur together in an expression, each operation is evaluated in order of appearance from left to right.

The string concatenation operator (&) is not really an arithmetic operator, but in precedence it does fall after all arithmetic operators and before all comparison operators.  Similarly, the Like operator, while equal in precedence to all comparison operators, is actually a pattern-matching operator.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Other Operators


Arithmetic Operators

^ Operator

* Operator

/ Operator

\ Operator

Mod Operator

+ Operator

- Operator


Concatenation Operators

& Operator

+ Operator


Other Operators

Is Operator

Like Operator


Logical Operators

And Operator

Eqv Operator

Imp Operator

Not Operator

Or Operator

Xor Operator


^ Operator

See Also	Example

Used to raise a number to the power of an exponent.

Syntax

result = number ^ exponent

Remarks

The number and exponent operands can be any numeric expression.  However, the number operand 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 a Variant (VarType 5).  However, if either number or exponent is a Null expression, result is also a Null.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators

VarType Function


^ Operator Example

The example squares (n^2) a user supplied number.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim N As Double, Result As Double	' Declare variables.

N = InputBox("Enter a number.")	' Get number.

Result = N ^ 2	' Square number.

MsgBox N & " squared is " & Result	' Display result.

End Sub


+ Operator

See Also	Example 1	Example 2

Used to sum two numbers.

Syntax

result = operand1 + operand2

Remarks

Although you can also use the + operator to concatenate two character strings, you should use the & operator for concatenation to eliminate ambiguity and provide self-documenting code.

When you use the + operator, you may not be able to determine whether addition or string concatenation is to occur.  If at least one operand is not a Variant, the following rules apply:

If	Then
Both expressions are numeric data types (Integer, Long, Single, Double, or Currency)	Add.
Both expressions are Strings	Concatenate.
One expression is a numeric data type and the other is a Variant (other than a Null)	Add.
One expression is a String and the other is a Variant (other than a Null)	Concatenate.
One expression is a Variant containing Empty	Return the remaining operand unchanged as result.
One expression is a numeric data type and the other is a String	A Type mismatch error occurs.
If either operand is a Null (VarType 1), result is a Null.

If both operands are Variant expressions, the VarType of the operands determines the behavior of the + operator in the following way:

If	Then
Both Variant expressions are of VarType 2-7 (numeric data types)	Add.
Both Variant expressions are of VarType 8 (String)	Concatenate.
One Variant expression is of VarType 2-7 (a numeric data type) and the other is of VarType 8 (String)	Add.

For simple arithmetic addition involving only operands of numeric data types, the data type of result is usually the same as that of the most precise operand.  The order of precision, from least to most precise, is Integer, Long, Single, Double, Currency.  The following are exceptions to this order:

When a Single and a Long are added together, the data type of result is converted to a Double.

When the data type of result is a Variant of VarType 3 (Long), VarType 4 (Single), or VarType 7 (Date) that overflows its legal range, result is converted to a Variant of VarType 5 (Double).

When the data type of result is a Variant of VarType 2 (Integer) that overflows its legal range, result is converted to a Variant of VarType 3 (Long).

If one or both operands are Null expressions, result is a Null.  If both operands are Empty, result is an Integer.  However, if only one operand is Empty, the other operand is returned unchanged as result.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators

VarType Function


+ Operator Example 1

The example adds a user-supplied number to itself and displays the result  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim N As Double, Result As Double	' Declare variables.

N = InputBox ("Enter a number.")	' Get a number.

Result = N + N	' Add numbers.

MsgBox N & " plus " & N & " is " & (N + N)	' Display result.

End Sub


+ Operator Example 2

The example uses the + operator to concatenate strings.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

MsgBox "Microsoft " + "Visual " + "Basic"	' Display result.

End Sub


- Operator

See Also	Syntax 1 Example	Syntax 2 Example

Used to find the difference between two numbers or to indicate the negative value of an operand.

Syntax 1

result = operand1 - operand2

Syntax 2

-number

Remarks

In Syntax 1, the - operator is the arithmetic subtraction operator used to find the difference between two numbers.  The operands can be any numeric expression.

The data type of result is usually the same as that of the most precise operand.  The order of precision, from least to most precise, is Integer, Long, Single, Currency, Double.  The following are exceptions to this order:

When subtraction involves a Single and a Long, the data type of result is converted to a Double.

When the data type of result is a Variant of VarType 3 (Long), VarType 4 (Single), or  VarType 7 (Date) that overflows its legal range, result is converted to a Variant of VarType 5 (Double).

When the data type of result is a Variant of VarType 2 (Integer) that overflows its legal range, result is converted to a Variant of VarType 3 (Long).

If one or both operands are Null expressions, result is a Null.  If an operand is Empty (VarType 0), it is treated as if it were 0.

In Syntax 2, the - operator is used as the unary negation operator to indicate the negative value of an operand.  As with Syntax 1, the operand can be any numeric constant, variable, expression, or any function that returns a number.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators

VarType Function


- Operator Syntax 1 Example

The example subtracts a user-supplied number from 1000 and displays the result  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim N As Double, Result As Double	' Declare variables.

N = InputBox ("Enter a number.")	' Get a number.

Result = 1000 -N

MsgBox "1000 minus " & N & " is " & Result	' Display result.

End Sub


- Operator Syntax 2 Example

The example uses the - operator to indicate a negative value of a number.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim N As Double, MinusN As Double	' Declare variables.

N = InputBox("Enter a number")	' Get a number.

MinusN = -N	' Use negation operator.

MsgBox "Negative " & N & " is " & MinusN	' Display result.

End Sub


* Operator

See Also	Example

Used to multiply two numbers.

Syntax

result = operand1 * operand2

Remarks

The operands can be any numeric expression.

The data type of result is usually the same as that of the most precise operand.  The order of precision, from least to most precise, is Integer, Long, Single, Double, Currency.  The following are exceptions to this order:

When multiplication involves a Single and a Long, the data type of result is converted to a Double.

When the data type of result is a Variant of VarType 3 (Long), VarType 4 (Single), or VarType 7 (Date) that overflows its legal range, result is converted to a Variant of VarType 5 (Double).

When the data type of result is a Variant of VarType 2 (Integer) that overflows its legal range, result is converted to a Variant of VarType 3 (Long).

If one or both operands are Null expressions, result is a Null.  Any operand that is Empty (VarType 0) is treated as 0.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators

VarType Function


* Operator Example

The example determines tax on a user-supplied value using the * operator to multiply the user-supplied value by the tax rate of 15%.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim N As Double, Tax As Double 	' Declare variables.

N = InputBox("Enter a number.")	' Get tax rate.

Tax = .15 * N	' Calculate tax.

MsgBox "Tax is " & Tax	' Display results.

End Sub


/ Operator

See Also	Example

Used to divide two numbers and return a floating-point result.

Syntax

result = operand1 / operand2

Remarks

The operands can be any numeric expression.

The data type of result is usually a Double or a Variant of VarType 5 (Double).  The following are exceptions to this rule:

When both operands are Integer or Single expressions, result is a Single unless it overflows its legal range, in which case, result is a Double.

When both operands are Variant expressions of VarType 2 (Integer) or VarType 4 (Single), result is a Variant of VarType 4 (Single) unless it overflows its legal range, in which case, result is a Variant of VarType 5 (Double).

If one or both operands are Null expressions, result is a Null.  Any operand that is Empty (VarType 0) is treated as 0.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators

VarType Function


/ Operator Example

The example divides 100,000 by 7 and returns 14,285.7142857143.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Result As Double	' Declare variable.

Result = 100000 / 7	' Divide numbers.

MsgBox "100000 divided by 7 is " & Result	' Display results.

End Sub


\ Operator

See Also	Example

Used to divide two numbers and return an integer result.

Syntax

result = operand1 \ operand2

Remarks

The operands can be any numeric expression.

Before division is performed, the operands are rounded to Integer or Long expressions.

Usually, the data type of result is an Integer, a Long, or a Variant of VarType 2 (Integer) or VarType 3 (Long) regardless of whether or not result is a whole number.  Any fractional portion is truncated.  However, if any operand is a Null, result is also a Null.  Any operand that is Empty (VarType 0) is treated as 0.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators

VarType Function


\ Operator Example

The example divides 100,000 by 7 using integer division and returns 14,285.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Result As Double	' Declare variable.

Result = 100000 \ 7	' Divide numbers.

MsgBox "100000 divided by 7 is " & Result	' Display results.

End Sub


Mod Operator

See Also	Example

Divides two numbers and returns only the remainder.

Syntax

result = operand1 Mod operand2

Remarks

The modulus, or remainder, operator divides operand1 by operand2 (rounding floating-point numbers to integers) and returns only the remainder as result.  For example, in the expression  A = 19 Mod 6.7, A (which is result) equals 5.  The operands can be any numeric expression.

Usually, the data type of result is an Integer, a Long, or a Variant  of VarType 2 (Integer) or VarType 3 (Long).  However, result is a Null (VarType 1) if one or both operands are Null expressions.  Any operand that is Empty (VarType 0) is treated as 0.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators

VarType Function


Mod Operator Example

The example uses the Mod operator to determine if a 4-digit year is a leap year.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim TestYr, LeapStatus	' Declare variables.

TestYr = InputBox("Enter a 4-digit year.")

If TestYr Mod 4 = 0 And TestYr Mod 100 = 0 Then	' Divisible by 4?

If TestYr Mod 400 = 0 Then	' Divisible by 400?

LeapStatus = " is a leap year."

Else

LeapStatus = " is a centesimal year, but not a leap year."

End If

ElseIf TestYr Mod 4 = 0 Then

LeapStatus = " is a leap year."

Else

LeapStatus = " is not a leap year."

End If

MsgBox TestYr & LeapStatus	' Display results.

End Sub


& Operator

See Also	Example

Used to force string concatenation of two operands.

Syntax

result = operand1 & operand2

Remarks

Whenever an operand is a number, it is converted to a Variant of VarType 8 (String).  The data type of result is String if both operands are String expressions; otherwise, result is a Variant of VarType 8 (String).  If both operands are Null (VarType 1), result is also Null.  However, if only one operand is Null, that operand will be treated as a zero-length string when concatenated with the other operand.  Any operand that is Empty (VarType 0) is also treated as a zero-length string.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators


& Operator Example

The example uses the & operator to concatenate a numeric variable (Var1), a string literal containing a space, and a string variable (Var2) that contains "trombones".  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Var1, Var2	' Declare variables.

Var1 = 76

Var2 = "trombones"

MsgBox 76 & " " & Var2	' Concatenate and display.

End Sub


Comparison Operators

See Also	Example

Used to compare two expressions.

Syntax

result = expr1 operator expr2

Remarks

Comparison operators, also known as relational operators, compare two expressions.  The following table contains a list of the comparison operators and the conditions that determine whether result is True, False, or Null:

Operator	Meaning	True if	False if	Null if
<	Less than	expr1 < expr2	expr1 >= expr2	expr1 or expr2 = Null
<=	Less than or equal to	expr1 <= expr2	expr1 > expr2	expr1 or expr2 = Null
>	Greater than	expr1 > expr2	expr1 <= expr2	expr1 or expr2 = Null
>=	Greater than or equal to	expr1 >= expr2	expr1 < expr2	expr1 or expr2 = Null
=	Equal to	expr1 = expr2	expr1 <> expr2	expr1 or expr2 = Null
<>	Not equal to	expr1 <> expr2	expr1 = expr2	expr1 or expr2 = Null
When comparing two expressions, you may not be able to easily determine whether the expressions are being compared as numbers or as strings.  The following table shows how the expressions are compared or what results when either expression is not a Variant:

If	Then
Both expressions are numeric data types (Integer, Long, Single, Double, or Currency)	Perform a numeric comparison.
Both expressions are String	Perform a string comparison.
One expression is a numeric data type and the other is a Variant of VarType 2-7 (a numeric data type) or VarType 8 (String) that can be converted to a number	Perform a numeric comparison.
One expression is a numeric data type and the other is a Variant of VarType 8 (String) that can't be converted to a number	A Type Mismatch error occurs.
One expression is a String and the other is a Variant of any VarType except Null	Perform a string comparison.
One expression is Empty and the other is a numeric data type	Perform a numeric comparison, using 0 as the Empty expression.
One expression is Empty and the other is a String	Perform a string comparison, using a zero-length string as the Empty expression.
One expression is a numeric data type and the other is a Variant of VarType 8 (String)	A Type Mismatch error occurs.
If expr1 and expr2 are both Variant expressions, their VarType determines how they are compared.  The following table shows how the expressions are compared or what results from the comparison, depending on the VarType of the Variant:

If	Then
Both Variant expressions are of VarType 2-7 (numeric data types)	Perform a numeric comparison.
Both Variant expressions are of VarType 8 (String)	Perform a string comparison.
One Variant expression is of VarType 2-7 (a numeric data type) and the other is of VarType 8 (String)	The numeric expression is less than the String expression.
One Variant expression is Empty and the other is of VarType 2-7 (a numeric data type)	Perform a numeric comparison, using 0 as the Empty expression.
One Variant expression is Empty and the other is of VarType 8 (String)	Perform a string comparison, using a zero-length string as the Empty expression.
Both Variant expressions are Empty	The expressions are equal.
Note	If a Currency is compared with a Single or Double, the Single or Double is converted to a Currency.  This causes any fractional part of the Single or Double value less than 0.0001 to be lost and may cause two values to compare as equal when they are not.  Such a conversion can also cause an Overflow error if the magnitude of the Single or Double is too large.  When a Single is compared to a Double, the Double is rounded to the precision of the Single.


See Also

Arithmetic Operators

Concatenation Operators

Like Operator

Logical Operators

Operator Precedence

Option Compare Statement

Other Operators

VarType Function


Comparison Operators Example

The example shows a typical use of a comparison operator to evaluate the relationship between variables A and B.  An appropriate message is displayed depending on whether the A < B, A = B, or A > B.  The other comparison operators can be used in a similar way.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B, Msg	' Declare variables.

A = InputBox("Enter a value for A.")	' Get first variable.

B = InputBox("Enter a value for B.")	' Get second variable.

If A < B Then	' Evaluate relationship.

Msg = "A is less than B."	' Create correct message.

ElseIf A = B Then

Msg = "A is equal to B."

Else

Msg = "A is greater than B."

End If

MsgBox Msg	' Display results.

End Sub


And Operator

See Also	Example

Used to perform a logical conjunction on two expressions.

Syntax

result = expr1 And expr2

Remarks

If, and only if, both expressions evaluate True, result is True.  If either expression evaluates False, result is False.  The following table illustrates how result is determined:

If expr1	And expr2	The result
is	is	is

True	True	True

True	False	False

True	Null	Null

False	True	False

False	False	False

False	Null	False

Null	True	Null

Null	False	False

Null	Null	Null

The And operator also performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in	And bit in	The result
expr1 is	expr2 is	is

0	0	0

0	1	0

1	0	0

1	1	1


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators


And Operator Example

The example displays a message that depends on the value of variables A, B, and C, assuming that no variable is a Null.  If A = 10, B = 8, and C = 6, both expressions evaluate True.  Because both expressions are True, the And expression is also True.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B, C, Msg	' Declare variables.

A = 10: B = 8: C = 6	' Assign values.

If A > B And B > C Then	' Evaluate expressions.

Msg = "Both expressions are True."

Else

Msg = "One or both expressions are False."

End If

MsgBox Msg	' Display results.

End Sub


Eqv Operator

See Also	Example

Used to perform a logical equivalence on two expressions.

Syntax

result = expr1 Eqv expr2

Remarks

If either expression is a Null, result is also a Null.  When neither expression is a Null, result is determined according to the following table:

If expr1	And expr2	The result
is	is	is

True	True	True

True	False	False

False	True	False

False	False	True

The Eqv operator performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in	And bit in	The result
expr1 is	expr2 is	is

0	0	1

0	1	0

1	0	0

1	1	1


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators


Eqv Operator Example

The example displays a message that depends on the value of variables A, B, and C, assuming that no variable is a Null.  If A = 10, B = 8, and C = 6, both expressions evaluate True.  As a result, the Eqv expression also evaluates True.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B, C, Msg	' Declare variables.

A = 10: B = 8: C = 6	' Assign values.

If A > B Eqv B > C Then	' Evaluate expressions.

Msg = "Both expressions are True or both are False."

Else

Msg = "One expression is True and one is False."

End If

MsgBox Msg	' Display results.

End Sub


Imp Operator

See Also	Example

Used to perform a logical implication on two expressions.

Syntax

result = expr1 Imp expr2

Remarks

The following table illustrates how result is determined:

If expr1	And expr2	The result
is	is	is

True	True	True

True	False	False

True	Null	Null

False	True	True

False	False	True

False	Null	True

Null	True	True

Null	False	Null

Null	Null	Null

The Imp operator performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in	And bit in	The result
expr1 is	expr2 is	is

0	0	1

0	1	1

1	0	0

1	1	1


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators


Imp Operator Example

The example displays a message that depends on the value of variables A, B, and C, assuming that no variable is a Null.  If A = 10, B = 8, and C = 6, both expressions evaluate True.  Because both are True, the Imp expression is also True.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B, C, Msg	' Declare variables.

A = 10: B = 8: C = 6	' Assign values.

If A > B Imp B > C Then

Msg = "The left expression implies the right expression."

Else

Msg = "The left expression doesn't imply the right expression."

End If

MsgBox Msg	' Display results.

End Sub


Not Operator

See Also	Example

Used to perform logical negation on an expression.

Syntax

result = Not expr

Remarks

The following table illustrates how result is determined:

If expr is	Then result is

True	False

False	True

Null	Null

In addition, the Not operator inverts the bit values of any variable and sets the corresponding bit in result according to the following truth table:

Bit in expr	Bit in result

0	1

1	0

If an integer variable has the value 0 (False), the variable becomes -1 (True); if it has the value -1, it becomes 0.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence


Not Operator Example

The example displays a message that depends on the value of variables A and B, assuming neither variable is a Null.  If A = 10 and B = 8, the Not expression evaluates True because A is not equal to B.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B, Msg	' Declare variables.

A = 10: B = 8	' Assign values.

If Not A = B Then	' Evaluate expression.

Msg = "A and B aren't equal."

Else

Msg = "A and B are equal."

End If

MsgBox Msg	' Display results.

End Sub


Or Operator

See Also	Example

Used to perform a logical disjunction on two expressions.

Syntax

result = expr1 Or expr2

Remarks

If either or both expressions evaluate True, result is True.  The following table illustrates how result is determined:

If expr1 is	And expr2	The result
is	is	is

True	True	True

True	False	True

True	Null	True

False	True	True

False	False	False

False	Null	Null

Null	True	True

Null	False	Null

Null	Null	Null

The Or operator also performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in	And bit in	The result
expr1 is	expr2 is	is

0	0	0

0	1	1

1	0	1

1	1	1


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators


Or Operator Example

The example displays a message that depends on the value of variables A, B, and C, assuming that no variable is a Null.  If A = 10, B = 8, and C = 11,  the left expression is True and the right expression is False.  Because at least one comparison expression is True, the Or expression evaluates True.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B, C, Msg	' Declare variables.

A = 10: B = 8: C = 11	' Assign values.

If A > B Or B > C Then	' Evaluate expressions.

Msg = "One or both comparison expressions are True."

Else

Msg = "Both comparison expressions are False."

End If

MsgBox Msg	' Display results.

End Sub


XOR Operator

See Also	Example

Used to perform a logical exclusion on two expressions.

Syntax

result = expr1 Xor expr2

Remarks

If only one of the expressions evaluates True, result is True.  If either expression is a Null result is also a Null.  When neither expression is a Null, result is determined according to the following table:

If expr1	And expr2	The result
is	is	is

True	True	False

True	False	True

False	True	True

False	False	False

The Xor operator also performs a bit-wise comparison of identically positioned bits in two numeric expressions and sets the corresponding bit in result according to the following truth table:

If bit in	And bit in	The result
expr1 is	expr2 is	is

0	0	0

0	1	1

1	0	1

1	1	0


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Logical Operators

Operator Precedence

Other Operators


Xor Operator Example

The example displays a message depending on the value of the variables A, B, and C, assuming that no variable is a Null.  If A = 6, B = 8, and C = 10, both expressions evaluate False.  Because both are False, the Xor expression is also False.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A, B, C, Msg	' Declare variables.

A = 6: B = 8: C = 10	' Assign values.

If A > B Xor B = C Then	' Evaluate expressions.

Msg = "Only one comparison expression is True, not both."

Else

Msg = "Both comparison expressions are True or both are False."

End If

MsgBox Msg	' Display results.

End Sub


Like Operator

See Also	Example

Used to compare two string expressions.

Syntax

result = expression Like pattern

Remarks

If expression matches pattern, result is True; if there is no match, result is False; and if either expression or pattern is a Null, result is also a Null.  The case sensitivity and character sort order of the Like operator depend on the setting of the Option Compare statement.  Unless otherwise specified, the default string-comparison method for each module is Option Compare Binary; that is, string comparisons are case-sensitive.

Built-in pattern matching provides a versatile tool for string comparisons.  The pattern-matching features allow you to use wildcard characters, such as those recognized by the operating system, to match strings.  The wildcard characters and what they match are shown in the following table:

Character(s)	Matches in
in pattern	expression

?	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 expression and can include almost any characters in the ANSI character set, including digits.  In fact, the special characters left bracket ([ ), question mark (?), number sign (#), and asterisk (*) can be used to match themselves directly only by enclosing them in brackets.  The right bracket ( ]) cannot be used within a group to match itself, but it can be used outside a group as an individual character.

In addition to a simple list of characters enclosed in brackets, charlist can specify a range of characters by using a hyphen (-) to separate the upper and lower bounds of the range.  For example, [A-Z] in pattern results in a match if the corresponding character position in expression contains any of the uppercase letters in the range A through Z.  Multiple ranges are included within the brackets without any delimiting.  For example, [a-zA-Z0-9]  matches any alphanumeric character.

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 ones in charlist are found in expression.  When used outside brackets, the exclamation point matches itself.

The hyphen (-) can appear either at the beginning (after an exclamation mark 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 ANSI 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 ignored; it is considered to be a zero-length string.

In some languages, there are special characters in the alphabet that actually 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 one of these special characters is specified in the WIN.INI file (sLanguage), an occurrence of the special single character in either pattern or expression matches the equivalent 2-character sequence in the other string.  Similarly, a special single character in pattern enclosed in brackets (by itself, in a list, or in a range), matches the equivalent 2-character sequence in expression.


See Also

Arithmetic Operators

Comparison Operators

Concatenation Operators

Instr Function

Logical Operators

Operator Precedence

Option Compare Statement

StrComp Function


Like Operator Examples

The following examples show how you can use Like to test expressions for different patterns.

Kind of matching	With this pattern	This expression returns True	This expression returns False
Multiple characters	a*a	"aa", "aBa", "aBBBa"	"aBC"
Special character	a[*]a	"a*a"	"aaa"
Multiple characters	ab*	"abcdefg", "abc"	"cab", "aab"
Single character	a?a	"aaa", "a3a", "aBa"	"aBBBa"
Single digit	a#a	"a0a", "a1a", "a2a"	"aaa", "a10a"
Range of characters	[a-z]	"f", "p", "j"	"2", "&"
Outside a range	[!a-z]	"9", "&", "%"	"b", "a"
Not a digit	[!0-9]	"A", "a", "&", "~"	"0", "1", "9"
Combined	a[!b-m]#	"An9", "az0", "a99"	"abc", "aj0"
Single special to double	[Æ]	"ae", "AE", "Æ"	"Ä", "A"


Is Operator

See Also	Example

Used to compare two object reference variables.

Syntax

result = objref1 Is objref2

Remarks

If objref1 and objref2 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:

In the following example, A has been set to refer to the same object as B.

Set A = B

The following example makes A and B refer to the same object as C:

Set A = C

Set B = C


See Also

Set Statement


Is Operator Example

The example uses the Is operator to evaluate if two object reference variables refer to the same form.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Dim A As New Form1	' Declare new instance of form.

Dim B As Form	' Declare new object reference.

Sub Form_Click ()

If A Is B Then	' Do they refer to same form?

Msg = "A and B refer to the same form."

Else

Msg = "A and B do not refer to the same form."

End If

MsgBox Msg	' Display message.

Set B = A	' Set B to same form as A.

If A Is B Then	' Check again.

Msg = "A and B refer to the same form."

Else

Msg = "A and B do not refer to the same form."

End If

MsgBox Msg	' Display message.

End Sub


Chr, Chr$ Functions

See Also	Example

Returns a one-character string whose ANSI  code is the argument.

Syntax

Chr[$](charcode)

Remarks

Chr returns a Variant; Chr$ returns a String.

The argument charcode is an integer between 0 and 255, inclusive.

Applications for Microsoft Windows use the ANSI character set.  ANSI character codes in the range 0 to 31, inclusive, are the same as the standard, nonprintable ASCII codes.  For example, Chr(10) returns a linefeed character.  It can be used to force a new line when message strings are formatted with MsgBox or InputBox.


See Also

Asc Function

Str, Str$ Functions


Chr, Chr$ Function Example

The example uses the Chr function to create a variable that will insert a newline character as well as a variable containing letters from A through Z.  Each time the line containing Chr is executed within the For...Next loop, another letter is appended to the Msg variable.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim I, J, Msg, NL	' Declare variables.

NL = Chr(10)	' Define newline.

For I = 1 to 2	' Set 2 iterations.

For J = Asc("A") To Asc("Z")	' From A through Z.

Msg = Msg & Chr(J)	' Create a string.

Next J

Msg = Msg & NL	' Insert newline.

Next I

MsgBox Msg	' Display results.

End Sub


Format, Format$ Functions

See Also	Example

Formats a number, date, time, or string according to instructions contained in a format expression.

Syntax

Format[$](expression[, fmt] )

Remarks

Format returns a Variant; Format$ returns a String.

The Format[$] function has these parts:

Part	Description

expression	Numeric or string expression to be formatted.

fmt	Format expression [image] a string of  display-format characters that specify how the expression is to be displayed or the name of a commonly used format that has been predefined in Visual Basic.  Different type format expressions (numeric, date/time, or string) cannot be mixed in a single fmt argument.

Note	If fmt is omitted or is zero-length and expression is a numeric expression, Format[$] provides the same functionality as the Str[$] function by converting the numeric value to the appropriate return data type.  Positive numbers converted to strings using Format[$] lack the leading space reserved for displaying the sign of the value, whereas those converted using Str[$] retain the leading space.

To format numbers, you can use the commonly used formats that have been predefined in Visual Basic or you can create user-defined formats with standard characters that have special meaning when used in a format expression.

The following table shows the predefined numeric format names you can use and the meaning of each:

Format name	Description

General Number	Display the number as is, with no thousand separators.

Currency	Display number with thousand separator, if appropriate; display negative numbers enclosed in parentheses; display two digits to the right of the decimal separator.

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, if appropriate; display two digits to the right of the decimal separator.

Percent	Display number multiplied by 100 with a percent sign (%) appended to the right; 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.

The following table shows the characters you can use to create user-defined number formats and the meaning of each:

Character	Meaning

Null string	Display the number with no formatting.

0	Digit placeholder.

Display a digit or a zero.  If there is a digit in the expression being formatted in the position where the 0 appears in the format string, display it; otherwise, display a zero in that position.

If the number being formatted has fewer digits than there are zeros (on either side of the decimal) in the format expression, leading or trailing zeros are displayed.  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, the number is rounded 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, the extra digits are displayed without modification.

#	Digit placeholder.

Display a digit or nothing.  If there is a digit in the expression being formatted 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.

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.  If you want a leading zero to always be displayed with fractional numbers, use 0 as the first digit placeholder to the left of the decimal separator instead.  The actual character used as a decimal placeholder in the formatted output depends on the Number Format specified in the International section of the Microsoft Windows Control Panel.  For some countries, a comma is used as the decimal separator.

%	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.

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 comma surrounded by digit placeholders (0 or #).  Two adjacent commas or a comma 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."  You can scale large numbers using this technique.  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 commas 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 specified in the International section of the Control Panel.  For some countries, a period is used as the thousand separator.

E- E+ e- e+	Scientific format.

If the format expression contains at least one digit placeholder (0 or #) to the right of E-, E+, e-, or e+, the number is displayed in scientific format and E or e is inserted between the number and its exponent.  The number of digit placeholders to the right 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.

:	Time separator.

The time separator separates hours, minutes, and seconds when time values are formatted.  The actual character used as the time separator depends on the Time Format specified in the International section of the Control Panel.

/	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 the formatted output depends on Date Format specified in the International section of the Control Panel.

- + $ ( ) space	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.

Many characters in the format expression have a special meaning and can't be displayed as literal characters unless they are preceded by 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- 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 fmt from within Visual Basic, you must use Chr(34) to enclose the text (34 is the ANSI code for a double quotation mark).

Unless the fmt argument contains one of the predefined formats, a format expression for numbers can have from one to four sections separated by semicolons.

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.

Four sections	The first section applies to positive values, the second to negative values, the third to zeros, and the fourth to Null values.

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"

Some sample format expressions for numbers are shown below. (These examples all assume that Country is set to United States in the International section of the Control Panel.)  The first column contains the format strings.  The other columns contain the output that results if the formatted data has the value given in the column headings.

Format (fmt)	Positive 5	Negative 5	Decimal .5	Null
Null 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	Nil
$#,##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
Numbers can also be used to represent date and time information.  You can format date and time serial numbers using date and time formats or number formats because date/time serial numbers are stored as floating-point values.

To format dates and times, you can use either the commonly used formats that have been predefined in Visual Basic or create user-defined time formats using standard characters that have special meaning when used in a format expression.

The following table shows the predefined data format names you can use and the meaning of each:

Format Name	Description

General Date	Display a date and/or time.  For real numbers, display a date and time. (e.g. 4/3/93 05:34 PM); If there is no fractional part, display only a date (e.g. 4/3/93); if there is no integer part, display time only (e.g. 05:34 PM).

Long Date	Display a Long Date, as defined in the International section of the Control Panel.

Medium Date	Display a date in the same form as the Short Date, as defined in the International section of the Control Panel, except spell out the month abbreviation.

Short Date	Display a Short Date, as defined in the International section of the Control Panel.

Long Time	Display a Long Time, as defined in the International section of the Control Panel. Long Time 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 (e.g. 17:45)

The following table shows the characters you can use to create user-defined date/time formats and the meaning of each:

Character	Meaning

c	Display the date as ddddd and display the time as t t t t t, in that order.  Only date information is displayed if there is no fractional part to the date serial number; only time information is displayed 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 a date serial number as a complete date (including day, month, and year) formatted according to the Short Date setting in the International section of the Windows Control Panel.  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 in the International section of the Control Panel.  The default Long Date  format is mmmm dd, yyyy.

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-53).

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).

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 two-digit number (00-99).

yyyy	Display the year as a four-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 serial number as a complete time (including hour, minute, and second) formatted using the time separator defined by theTime Format in the International section of the Control Panel.  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 PM.

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 PM.

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 PM.

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 PM.

AMPM	Use the 12-hour clock and display the contents of the 1159 string (s1159) in the WIN.INI file with any hour before noon; display the contents of the 2359 string (s2359) with any hour between noon and 11:59 PM.  AMPM can be either uppercase or lowercase, but the case of the string displayed matches the string as it exists in the WIN.INI file.  The default format is AM/PM.

The following are examples of user-defined date and time formats:

Format	Display

m/d/yy	12/7/58

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/yy h:mm	12/7/58 20:50

Strings can also be formatted with Format[$].  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 Null values and zero-length strings.

You can use any of the following characters to create a format expression for strings:

Character	Meaning

@	Character placeholder.

Display a character or a space.  If there is a character in the string being formatted in the position where the @ 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 ! character in the format string.  See below.

&	Character placeholder.

Display a character or nothing.  If there is a character in the string being formatted in the position where the & appears, display it; otherwise, display nothing.  Placeholders are filled from right to left unless there is an ! character in the format string.  See below.

<	Force lowercase.

All characters are displayed in lowercase format.

>	Force uppercase.

All characters are displayed in uppercase format.

!	Force placeholders to fill from left to right instead of right to left.


See Also

Format Property

Str, Str$ Function


Format, Format$ Function Example

The example uses Format to format date and time values according to the setting of entries in the International section of the Microsoft Windows Control Panel.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL	' Declare variables.

NL = Chr(10)	' Define newline.

Msg = "Today's date is " & Format(Now, "ddddd") & "." & NL

Msg = Msg & "The current time is " & Format(Now, "ttttt")

Msg = Msg & "."

MsgBox Msg	' Display date/time formatting.

End Sub


Hex, Hex$ Functions

See Also	Example

Returns a string that represents the hexadecimal value of a decimal argument.

Syntax

Hex[$](number)

Remarks

Hex returns a Variant; Hex$ returns a String.

The argument number can be any numeric expression.  It is rounded to the nearest whole number before being evaluated.  An error occurs if number is a Variant of VarType 1 (Null).

If the argument is an Integer or a Variant of VarType 2 (Integer) or VarType 0 (Empty), up to four hexadecimal characters are returned; if the argument is any other numeric data type, or a Variant of any other type, up to eight hexadecimal characters are returned.

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

Oct, Oct$ Function


Hex, Hex$ Function Example

The example uses Hex to return the hexadecimal representation of a decimal number.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, Num	' Declare variables.

Num = InputBox("Enter a number.")	' Get user input.

Msg = Num & " decimal is &H"

Msg = Msg & Hex(Num) & " in hexadecimal notation."

MsgBox Msg	' Display results.

End Sub


LCase, LCase$ Functions

See Also	Example

Returns a string in which all letters of an argument have been converted to lowercase.

Syntax

LCase[$](strexpr)

Remarks

LCase returns a Variant; LCase$ returns a String.

The argument strexpr can be any string expression.  However, only LCase can accept a Variant of VarType 1 (Null ) as strexpr, in which case, a Null is returned.

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


See Also

UCase, UCase$ Function


LCase, LCase$ Function Example

The example uses LCase to return an all-lowercase version of the argument string.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Lowercase, Msg, Uppercase	' Declare variables.

Uppercase = "ONCE UPON A TIME"	' String to convert.

Lowercase = LCase(UpperCase)	' Convert to lowercase.

Msg = "LCase converts """ & Uppercase & """ to """

Msg = Msg & Lowercase & "."""

MsgBox Msg	' Display message.

End Sub


Left, Left$ Functions

See Also	Example

Returns the leftmost n characters of a string argument.

Syntax

Left[$](strexpr, n)

Remarks

Left returns a Variant; Left$ returns a String.

The Left[$] function has these parts:

Part	Description

strexpr	String expression from which the leftmost characters are returned.  This can be any string expression.  However, only Left can accept a Variant of VarType 1 (Null) as stringexpr, in which case, a Null is returned.

n	Long integer expression indicating how many characters to return.  It must be between 0 and approximately 65,535, inclusive.  If n is 0, the return value is a zero-length string.  If n is greater than or equal to the number of characters in strexpr, the entire string is returned.

To find the number of characters in strexpr, use Len(strexpr).


See Also

Len Function

Mid, Mid$ Function

Right, Right$ Function


Left, Left$ Function Example

The example uses the Left function to return the first of two words input by the user.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim LWord, Msg, RWord, SpcPos, UsrInp	' Declare variables.

Msg = "Enter two words separated by a space."

UsrInp = InputBox(Msg)	' Get user input.

SpcPos = InStr(1, UsrInp, " ")	' Find space.

If SpcPos Then

LWord = Left(UsrInp, SpcPos - 1)	' Get left word.

RWord = Right(UsrInp, Len(UsrInp) - SpcPos)	' Get right word.

Msg = "The first word you entered is """ & LWord

Msg = Msg & "." & """"  & " The second word is """

Msg = Msg & RWord & "." & """"

Else

Msg = "You didn't enter two words."

End If

MsgBox Msg	' Display message.

End Sub


Len Function

See Also	Example

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

Syntax 1

Len(strexpr)

Syntax 2

Len(variablename)

Remarks

If you use the first syntax, Len returns the number of characters in the argument strexpr.

If you use the second syntax, Len returns the number of bytes required to store a variable of the given data type.  If variablename is a Variant, Len always returns the number of bytes required to store the Variant data as a String, regardless of the VarType.

Because Len works with user-defined data types as well as fundamental Visual Basic data types, the second syntax is particularly useful for determining record size when you are performing file input/output with random-access files.  However, if a user-defined data type contains Variant or variable-length String elements, Len may not be able to properly determine the actual number of storage bytes required.

If the argument to Len is Null, the function returns a Null.


See Also

InStr Function


Len Function Example

The example shows how Len can be used to return the number of bytes needed to store each fundamental Visual Basic data type.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim A As Integer, B As Long	' Declare variables.

Dim C As Single, D As Double

Dim E As Currency, F As Variant

Dim Msg, NL

NL = Chr(10)	' Define newline.

A% = 1	' Integer

B& = A%	' Long integer

C! = B&	' Single-precision, floating-point

D# = C!	' Double-precision, floating-point

E@ = D#	' Currency

F = E@	' Variant

Msg = "Integer values are stored in " & Len(A%) & " bytes."

Msg = Msg & NL & "Long integer values are stored in "

Msg = Msg & Len(B&) & " bytes." & NL

Msg = Msg & "Single-precision values are stored in "

Msg = Msg & Len(C!) & " bytes." & NL & "Double-precision "

Msg = Msg & "values are stored in " & Len(D#) & " bytes."

Msg = Msg & NL & "Currency values are stored in " & Len(E@)

Msg = Msg & " bytes." & NL & "This Variant requires " & Len(F)

Msg = Msg & " bytes to store it as a string." & NL

Msg = Msg &  "This message contains "

Msg = Msg & "more than " & Len(Msg) & " characters."

MsgBox Msg	' Display message.

End Sub


LSet Statement

See Also	Example

Left aligns a string within the space of a string variable or copies a variable of one user-defined type to another variable of a different user-defined type.

Syntax 1

LSet stringvar = stringexpr

Syntax 2

LSet variable1 = variable2

Remarks

The LSet statement has these parts:

Part	Description

stringvar	Name of a String variable.

stringexpr	String expression to be left aligned within stringvar.

variable1	Name of the user-defined type variable being copied to.

variable2	Name of the user-defined type variable being copied from.

If stringexpr is shorter than stringvar, LSet left aligns stringexpr within stringvar.  LSet replaces any leftover characters in stringvar with spaces.

If stringexpr is longer than stringvar, LSet places only the leftmost characters, up to the length of the stringvar, in stringvar.  Characters beyond the length of stringvar are truncated from the right.

Use LSet with Syntax 2 to assign one user-defined type variable to another.  The following example copies the contents of RecTwo (a user-defined type variable) to RecOne (a variable of another user-defined type):

Type TwoString

StrFld As String * 2

End Type

Type ThreeString

StrFld As String * 3

End Type

Dim RecOne As TwoString, RecTwo As ThreeString

LSet RecOne = RecTwo

Because RecOne is 2 bytes long, only 2 bytes are copied from RecTwo.  LSet copies only the number of bytes in the shorter of the two user-defined type variables.

You can't use LSet to copy variables of different user-defined types if either contains a variable-length string or a Variant.


See Also

RSet Statement


LSet Statement Example

The example uses LSet to left align text in a 40-character String variable).  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL, OldFont, TmpStr	' Declare variables.

NL = Chr(10)	' Define newline.

OldFont = FontName	' Save old font.

FontName = "Courier"	' Use monospaced font

TmpStr = String(40, "*")	' Create 40-character string.

Msg = "Here are two strings that have been right"

Msg = Msg & NL & "and left justified in a " & Len(TmpStr)

Msg = Msg & "-character string." & NL & TmpStr & NL

RSet TmpStr = "Right->"	' Right justify.

Msg = Msg & TmpStr & NL

LSet TmpStr = "<-Left"	' Left justify.

Msg = Msg & TmpStr & NL

Print Msg	' Display message.

FontName = OldFont	' Restore original font.

End Sub


LTrim, LTrim$, RTrim, RTrim$, Trim, Trim$ Functions
LTrim, LTrim$, RTrim, RTrim$, Trim, Trim$ Function

See Also	Example

Returns a copy of a string with leading (leftmost), trailing (rightmost), or both leading and trailing spaces removed.

Syntax

[L | R]Trim[$](stringexpr)

Remarks

LTrim[$] removes leading spaces from a string; RTrim[$] removes trailing spaces.  Trim[$] removes leading and trailing spaces.

LTrim, RTrim, and Trim each return a Variant; LTrim$, RTrim$, and Trim$ each return a String.

The stringexpr argument can be any string expression.  However, only LTrim, RTrim, and Trim can accept a Variant of VarType 1 (Null) as stringexpr, in which case, a Null is returned.


lanLTrimSee
See Also

Mid, Mid$ Function


LTrim, LTrim$, RTrim, RTrim$, Trim, Trim$ Functions Example

The example uses LTrim and RTrim, to strip leading and trailing spaces from a string variable.  The stripping of both leading and trailing spaces can be more efficiently done using the Trim function.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL, TestStr, TestStr1	' Declare variables.

NL = Chr(10)	' Define newline.

TestStr = "  Test String  "

TestStr1 = LTrim(RTrim(TestStr))	' Strip spaces left and right.

Msg = "The original TestStr """ & TestStr & """ was "

Msg = Msg & Len(TestStr) & " characters long. There were two "

Msg = Msg & "leading spaces and two trailing spaces." & NL & NL

Msg = Msg & "The TestStr returned after stripping the spaces "

Msg = Msg & "is """ & TestStr1 & """ and it contains only "

Msg = Msg & Len(TestStr1) & " characters."

MsgBox Msg	' Display message.

End Sub


Mid, Mid$ Functions
Mid, Mid$ Function

See Also	Example

Returns a string that is part of some other string.

Syntax

Mid[$](stringexpr, start[, length])

Remarks

Mid returns a Variant; Mid$ returns a String.

The Mid[$] function has these parts:

Part	Description

stringexpr	String expression from which another string is created.  This can be any string expression.  However, only Mid can accept a Variant of VarType 1 (Null) as stringexpr, in which case, a Null is returned.

start	Long expression that indicates the character position in stringexpr at which the part to be taken begins.

length	Long expression that indicates the number of characters to return.

The arguments start and length must be between 1 and approximately 65,535, inclusive.  If length is omitted or if there are fewer than length characters in the text (including the character at start), the Mid[$] function returns all characters from the start position to the end of the string.

If start is greater than the number of characters in stringexpr, Mid[$] returns a zero-length string.

Use the Len function to find the number of characters in stringexpr.


See Also

Left, Left$ Function

Len Function

Mid, Mid$ Statement

Right, Right$ Function


Mid, Mid$ Function Example

The example uses the Mid function to return the middle word from a variable containing three words.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim MidWord, Msg, TstStr, SpcPos1, SpcPos2	' Declare variables.

TstStr = "Mid Function Demo"	' Create text string.

SpcPos1 = InStr(1, TstStr, " ")	' Find first space.

SpcPos2 = InStr(SpcPos1 + 1, TstStr, " ")	' Find next space.

WordLen = (SpcPos2 - SpcPos1) - 1	' Calculate 2nd word length.

MidWord = Mid(TstStr, SpcPos1 + 1, WordLen)	' Return 2nd word.

Msg = "The word in the middle of Title is """ & MidWord & """"

MsgBox Msg, 0, TstStr	' Display message.

End Sub


Mid, Mid$ Statements
Mid, Mid$ Statement

See Also	Example

Replaces part of a string with another string.

Syntax

Mid[$](stringvar, start [, length])  =  stringexpr

Remarks

There is no functional difference between Mid and Mid$.  The Mid[$] statement has these parts:

Part	Description

stringvar	String or Variant (VarType 8) variable to modify.

start	Character position in stringvar where the replacement text begins.

length	Number of characters to replace.

stringexpr	String expression that replaces part of stringvar.

The arguments start and length must be between 1 and approximately 65,535, inclusive.  The argument stringvar must be a variable, but stringexpr can be any string expression.

The optional argument length refers to the number of characters from the argument stringexpr that are used in the replacement.  If length is omitted, all of stringexpr is used.  Whether or not length is included, the number of characters replaced is always less than or equal to the number of characters in stringvar.


See Also

Mid, Mid$ Function

Right, Right$ Function

Left, Left$ Function


Mid, Mid$ Statement Example

The example uses the Mid$ statement to substitute "dog" for  "fox" within a string.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Head1, Head2, Orig, Start, Test, Msg	' Declare variables.

Dim NL, TB

NL = Chr(10): TB = Chr(9)	' Define newline, tab.

Head1 = "Original string:"

Head2 = "Replacement string:"

Orig = "The quick brown fox jumped over the wall."

Test = Orig	' Make a copy of Original

Start = Instr(Test,"fox")	' Find where "fox" begins.

Mid(Test, Start, 3) = "dog"	' Replace "fox" with "dog".

Msg = Head1 & NL & TB & Orig

Msg = Msg & NL & Head2 & NL & TB & Test

MsgBox Msg	' Display message

End Sub


Oct, Oct$ Functions

See Also	Example

Returns text that represents the octal value of the decimal argument.

Syntax

Oct[$](number)

Remarks

Oct returns a Variant; Oct$ returns a String.

The argument number can be any numeric expression.  It is rounded to the nearest whole number before being evaluated.  An error occurs if number is a Variant of VarType 1 (Null).

If the argument is an Integer or a Variant of VarType 2 (Integer) or VarType 0 (Empty), up to six octal characters are returned; if the argument is any other numeric data type or a Variant of any other type, up to 11 octal characters are returned.

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

Hex, Hex$ Function


Oct, Oct$ Function Example

The example uses Oct to return the octal representation of a decimal number. To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, Num	' Declare variables.

Num = InputBox("Enter a number.")	' Get user input.

Msg = Num & " decimal is &O"

Msg = Msg & Oct(Num) & " in octal notation."

MsgBox Msg	' Display results.

End Sub


Right, Right$ Functions

See Also	Example

Returns the rightmost n characters of a string argument.

Syntax

Right[$](stringexpr, n)

Remarks

Right returns a Variant; Right$ returns a String.

The Right[$] function has these parts:

Part	Description

strexpr	String expression from which the rightmost characters are returned.  This can be any string expression.  However, only Right can accept a Variant of VarType 1 (Null) as stringexpr, in which case, a Null is returned.

n	Long integer expression indicating how many characters to return.  It must be between 0 and approximately 65,535, inclusive.  If n is 0, the return value is a zero-length string.  If n is greater than or equal to the number of characters in strexpr, the entire string is returned.

To find the number of characters in stringexpr, use Len(stringexpr).


See Also

Instr Function

Left, Left$ Function

Len Function

Mid, Mid$ Function


Right, Right$ Function Example

The example uses the Right function to return the second of two words input by the user.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim LWord, Msg, RWord, SpcPos, UsrInp	' Declare variables.

Msg = "Enter two words separated by a space."

UsrInp = InputBox(Msg)	' Get user input.

SpcPos = InStr(1, UsrInp, " ")	' Find space.

If SpcPos Then

LWord = Left(UsrInp, SpcPos - 1)	' Get left word.

RWord = Right(UsrInp, Len(UsrInp) - SpcPos)	' Get right word.

Msg = "The first word you entered is """ & LWord

Msg = Msg & "." & """"  & " The second word is """

Msg = Msg & RWord & "." & """"

Else

Msg = "You didn't enter two words."

End If

MsgBox Msg	' Display message.

End Sub


RSet Statement

See Also	Example

Right aligns a string within the space of a string variable.

Syntax

RSet stringvar = stringexpr

Remarks

The RSet statement has these parts:

Part	Description

stringvar	Name of a String variable.

stringexpr	String expression to be right aligned within stringvar.

If stringexpr is shorter than stringvar, RSet right aligns stringexpr within stringvar.  RSet replaces any leftover characters in stringvar with spaces, back to its beginning.

If stringexpr is longer than stringvar, RSet places only the leftmost characters, up to the length of stringvar, in stringvar.  Characters beyond the length of stringvar are truncated from the right.

You can't use RSet to assign variables of one user-defined type to those of another.


See Also

LSet Statement


RSet Statement Example

The example uses RSet to right align text in a 40-character String variable).  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL, OldFont, TmpStr	' Declare variables.

NL = Chr(10)	' Define newline.

OldFont = FontName	' Save old font.

FontName = "Courier"	' Use monospaced font.

TmpStr = String(40, "*")	' Create 40-character string.

Msg = "Here are two strings that have been right"

Msg = Msg & NL & "and left justified in a " & Len(TmpStr)

Msg = Msg & "-character string." & NL & TmpStr & NL

RSet TmpStr = "Right->"	' Right justify.

Msg = Msg & TmpStr & NL

LSet TmpStr = "<-Left"	' Left justify.

Msg = Msg & TmpStr & NL

Print Msg	' Display message.

FontName = OldFont	' Restore original font.

End Sub


Space, Space$ Functions
Space, Space$ Function

See Also	Example

Returns a string consisting of a specified number of spaces.

Syntax

Space[$](number)

Remarks

Space returns a Variant; Space$ returns a String.

The argument number specifies the number of spaces you want in the string.  It can be of any numeric data type but is rounded to a Long and must be between 0 and approximately 65,535, inclusive.


See Also

Spc Function

String, String$ Functions


Space, Space$ Function Example

The example uses Space to create a variable containing 10 spaces.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, Pad, UsrInp	' Declare variables.

UsrInp = InputBox("Enter your first name")	' Get user input.

Pad = Space(10)	' Create 10-space pad.

Msg = "Notice the 10-space pad between the first part of this "

Msg = Msg & "and your name.  " & Pad & UsrInp

MsgBox Msg	' Display message.

End Sub


Str, Str$ Functions

See Also	Example

Return a string representation of the value of a numeric expression.

Syntax

Str[$](number)

Remarks

Str returns a Variant; Str$ returns a String.

Use Str[$] to convert simple numeric values to strings.  Use the Format[$] function to convert numeric values you want formatted as dates, times, or currency or in other user-defined formats.

When numbers are converted to text, a leading space is always reserved for the sign of number.  If number is positive, the string returned by Str[$] contains a leading space and the plus sign is implied.  Format[$] doesn't include a leading space.

The Val function complements Str[$] by returning the numeric value of a string.


See Also

Format, Format$ Function

Val Function


Str, Str$ Function Example

The example uses Str to return a string representation of the values contained in two variables.  Note that because the numbers are positive, a space for the implied plus sign precedes the first string character.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Dice1, Dice2, Msg	' Declare variables.

Randomize	' Seed random number generator.

Dice1 = Int(6 * Rnd + 1)	' Generate first die value.

Dice2 = Int(6 * Rnd + 1)	' Generate second die value.

Msg = "You rolled a" & Str(Dice1)

Msg = Msg & " and a" & Str(Dice2)

Msg = Msg & " for a total of"

Msg = Msg & Str(Dice1 + Dice2) & "."

MsgBox Msg	' Display message.

End Sub


String, String$ Functions
String, String$ Function

See Also	Example

Returns a string whose characters all have a given ANSI code or are all the first character of a string expression.

Syntax 1

String[$](number, charcode)

Syntax 2

String[$](number, string)

Remarks

String returns a Variant; String$ returns a String.

Use String[$] to create a string that consists of one character repeated over and over.

The String[$] function has these parts:

Part	Description

number	Numeric expression indicating the length of the returned string.  It must be between 0 and approximately 65,535.

charcode	ANSI code of the character to use to build the return string.  It is a numeric expression that evaluates to an Integer between 0 and 255, inclusive.

string	String expression whose first character is used to build the return string.

If the second argument (charcode or string) in either syntax is a Variant, the underlying data type determines how String[$] uses that argument.  If the argument is a Variant of VarType 8 (String), String[$] uses the first character to create the return string.  If the argument is a Variant of VarType 2-7 (any numeric type), String[$] uses the numeric value as the ANSI code for the character used to create the return String.  A Variant of VarType 1 (Null) produces an error.  To convert numeric values greater than 255 to an ANSI code between 0 and 255, String [$] uses the remainder after the value is divided by 256 (argument Mod 256).


See Also

ANSI Character Set

Space, Space$ Function

Str, Str$ Function


String, String$ Function Example

The example uses the String function to return a Variant consisting of 10 asterisks.  The ANSI code of the asterisk character is 42.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Msg, NL	' Declare variables.

NL = Chr(10)	' Define newline.

Msg = "This demo generates two strings of 10 asterisks.  Both "

Msg = Msg & "forms of String[$] syntax are illustrated.  " & NL

Msg = Msg & NL & "Here is the 1st: " & String(10, "*") & NL

Msg = Msg & "Here is the 2nd: " & String(10, 42)

MsgBox Msg	' Display message.

End Sub


UCase, UCase$ Functions

See Also	Example

Returns a string in which all letters of an argument have been converted to uppercase.

Syntax

UCase[$](stringexpr)

Remarks

UCase returns a Variant; UCase$ returns a String.

The argument stringexpr can be any string expression.  However, only UCase can accept a Variant of VarType 1 (Null) as stringexpr, in which case, a Null is returned.

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


See Also

LCase, LCase$ Function

Asc Function


UCase, UCase$ Function Example

The example uses UCase to return an all-uppercase version of the argument string.  To try this example, paste the code into the Declarations section of a form.  Then press F5 and click the form.

Sub Form_Click ()

Dim Lowercase, Msg, Uppercase	' Declare variables.

Lowercase = "once upon a time"	' String to convert.

Uppercase = UCase(Lowercase)	' Convert to uppercase.

Msg = "UCase converts """ & Lowercase & """ to """

Msg = Msg & Uppercase & "."""

MsgBox Msg	' Display message.

End Sub


'|' is a Read-Only file
<Filename> is a Read-Only file

You asked to save to a file that is read-only.  Readonly files are shown in the Project window with a red lock in the lower-left corner. You cannot save to readonly files. Use Save As instead.


An expression must be selected

A variable, expression, or property reference must be selected before using the Instant Watch command. Note: While in the Code window, it is also possible to place the cursor on the variable and then invoke the Instant Watch command.


An undo error has occurred. Further undo is unavailable

The Undo / Redo mechanism is unable to perform the requested undo or redo operation.  Both undo and redo buffers have been flushed; therefore, old edits cannot be undone or redone.  Edits performed after the message will be recorded and can be undone or redone.


Can't have more than one window List menu

You clicked the Window List check box for more than one menu item and then clicked OK to close the dialog.  For a particular form, only one menu can have the Window List check box checked.  This is done through the Menu Design window.


Can't set formal parameter

You can't use a procedure's formal parameter as the destination of a Set statement.


Cannot destroy active form instance

Error 95

Form instances created with the New keyword cannot be unloaded from the Debug window if there are halted event procedures for that form instance.


Circular references between modules

A cycle between modules prevents Visual Basic from being able to compile your program.   Restructure your code to eliminate the cycle.  Example of a cycle:

Module 1:	Module 2:

  dim  a as t2	type t2

  type t1	x as integer

x as integer	end type

  end type	dim b as t1


Controls without the Align property cannot be placed directly on the MDI form

You tried to double-click on a control to have it placed on the MDI form and the control doesn't support the standard property Align.  A picture box is the only standard control that can be placed on an MDI form.  When an MDI child form is maximized within the parent MDI form, it will not cover any picture boxes.

An example of good usage: Create new MDIform and double-click on picture box

An example of bad usage: Create new MDIform and double-click on text box


Duplicate Option statement

You've defined more than one "Option Compare" or "Option Explicit" statement in your module. Remove the one you don't want.


Duplicate procedure name

You have defined (or are attempting to define) more than one version of a procedure with the same name.  Rename one of the procedures.  Ensure that duplicate Declare statements for the same procedure have the same Alias clause.


For index in use
For index variable already in use

You have nested For loops that are using the same index. For example:

For i% = 1 to 10

For i% = 1 to 20

print i%

next i%

next i%

Change the index on one of the loops to another variable name.


For loop not initialized

Error 92

You've jumped into the middle of a For loop with a variant index. Do not place labels inside a For loop.


Global definition invalid inside form module

You can't have a Type ... End Type block, Global statement, or Global Const statement in a form module.  Data in a form module cannot be referenced by other modules.  Move data that must be global to a non-forms module.


Illegal Watch expression

You tried to enter a watch expression containing one of the following intrinsic functions: LoadPicture, InputBox, MsgBox, DoEvents, Shell, or Input.


Invalid object reference

An object is required here, and you have specified something that is not an object.

Set x% = 1, for example.  Or, you have specified an object where one is not allowed.


Invalid pattern string

Error 93

The pattern string specified in the Like operator of the Search operation is invalid.  A common mistake is an invalid character-list expression, such as [a-b  (missing the right bracket).


Invalid use of Null

Error 94

You are trying to obtain the value of a Variant variable or an expression that is Null.  Null is normally used to signal an error condition, or to indicate that a data item contains no data.


Method not applicable for this object

You are attempting to invoke a method on an object that doesn't support this method.

For example  Clipboard.Print is invalid because the Clipboard object does not support the print method.


New not allowed on this type

Auto-construction is not supported on this type of object.  You can't use the New keyword on it.

Example of good usage: Dim x as new form1

Example of bad usage: Dim x as new Textbox1

In the base product: the keyword New can be used only on specific instances of form types (Form1, etc.).  It cannot be used on the general class form or MDIform or on any control types.  In the Visual Basic Professional Edition, there are some vt objects for which New is allowed.


Object does not have a value

You are trying to get the value of an object that doesn't have a value.   You may be trying to use an object in a place where objects of that type are not allowed or you may have left off a property or control suffix.


Object variable not set

Error 91

You are attempting to use a non-autoinstalling object variable that is not yet pointing to a valid object, or one that has been set to null.


Separator may not be the window List menu

The window menu has to be a menu item that can support being a popup menu (i.e., one that can have subitems).  A separator cannot have subitems.


Type too large

The sum of sizes of the elements of a user-defined type exceeds 64K.  You must reduce the size of this type.  Consider replacing fixed-length strings with variable-length strings.


User functions not allowed in Watch expressions

You have placed a user function in a watch expression. You cannot reference one of your Functions in a watch expression.


Valid Range: [1..32]
Valid range: [1...32]

You attempted to set the Tab Stop Width beyond the permitted range.   A number between 1 and 32 (inclusive) is acceptable for this field.


Valid Range:[24..1188]
Valid range: [24...1188]

You attempted to set the Grid Width or Grid Height beyond the permitted range.   A number between 24 and 1188  (inclusive) is acceptable for this field.


Variable not defined

You've used an Option Explicit statement to require the explicit declaration of variables, and you've used a variable without declaring it. This option protects your application from undeclared variables.


Watch expression too long, expression truncated

Watch expressions are limited to 64 characters.  If you enter a watch expression that expands to greater than 64 characters,  then the expression can still be evaluated, but it is truncated to 64 characters if you attempt to edit the expression.


Errors during load. Refer to "|' for details
Errors during load. Refer to <log file> for details

Something unexpected appeared in the ASCII form file.  Visual Basic has created a log file to provide more detail about the errors.  You should examine the log file to determine the severity of the problem. Sometimes the encountered errors are benign  (e.g., "Version number missing or invalid...") and you can safely ignore them.  Other times, however, the errors could cause the form to not run as expected. (e.g., "Class MyClass in control  MyControl was not a loaded control class")


String value to long to process; form load aborted
String value too long to process; form load aborted

There was a string embedded in the form being loaded.  It was too long to process.


Version number missing or invalid; Visual Basic 2.0 assumed.

Either the version signature was not found or the specified version is not recognized.  Make sure that the first non-blank, non-comment line in the ASCII form reads "Version 2.00."


Line |1: The file |2 could not be loaded.
Line <line number>: The file <filename> could not be loaded.

Syntax errors prevent Visual Basic from parsing and loading, or form name conflicts prevent loading of an ASCII form.  The form will not be loaded and the form name will not be displayed in the Project window.

Make sure that the file that caused this error is a valid ASCII form in the correct format and that there are no conflicts among the different forms in the project.  The correct ASCII form format is:

Version 2.00
Begin {Form | MdiForm} <formname>
prop = value
prop = value
[...]
Begin <control class> <control name>
prop = value
[...]
Begin ...
[...]
End
End
End


'|' could not be loaded
'<item>' could not be loaded

Syntax errors prevent Visual Basic from parsing and loading, or form name conflicts prevent loading of an ASCII form.  The form will not be loaded and the form name will not be displayed in the Project window.

Make sure that the file that caused this error is a valid ASCII form in the correct format, and that there are no conflicts among the different forms in the project.  The correct ASCII form format is:

Version 2.00
Begin {Form | MdiForm} <formname>
prop = value
prop = value
[...]
Begin <control class> <control name>
prop = value
[...]
Begin ...
[...]
End
End
End


Line too long

A line of Visual Basic code cannot contain more than 1023 characters.  Break the line into individual statements or assign some expressions to intermediate variables.


Identifier too long

Identifiers cannot be more than 40 characters long.


Invalid identifier

The names of variables, procedures, forms, and controls cannot be reserved words, must start with a letter, and can be no longer than 40 characters [image] including letters, numbers, and underscores (_).

To reference an object that conflicts with a reserved word, enclose the reference in square brackets.


Identifier can't end with type-declaration character

The following cannot contain a type declaration character:

A Sub procedure name

An identifier declared with a data type using an As clause

The name of a user-defined type

The name of any object or property


Invalid number

A number is inappropriate for its context.

Possible causes:

A type declaration character is used with an incompatible number.  For example, 10.2% is invalid because an Integer type (%) cannot have a fractional part.

A fixed-length string is declared to have length zero.  For example,

Dim X As String 0

will produce this message.


Invalid constant declaration

Possible causes:

An invalid expression has been used to assign a value to a symbolic constant.  Valid expressions are described in the Const topic.

An undefined constant is referred to.  For example, if "D" is not defined, the following produces this error:

Const C = D

Dim X As String * 0


Expected:
Expected: <various>

An expected piece of code was not found.  The error is usually located to the left of the selected item.


Syntax error

Visual Basic can't determine what action to take.

Possible causes:

A keyword or argument is misspelled.

Punctuation is incorrect.

A Sub procedure is not defined.


Invalid outside of Sub or Function

The statement must occur within a Sub or Function procedure.  Executable statements, Static, and ReDim can be used only in a Sub or Function procedure.  In the Declarations section of a form or module you can use only comments and the declarative statements Declare, Deftype, Dim, Option, Global, Global Const, and Type.


Invalid in Sub or Function

The statement cannot occur in a Sub or Function procedure.  The statements Declare, Deftype, Global, Global Const, Option, and Type are not allowed in procedures.


Statement cannot precede Sub/Function definition

Only comments are allowed before a Sub or Function statement.


Sub/Function without End Sub/Function

The terminating statement is missing from the procedure.


Element not defined

An element of a user-defined type is referred to but not defined.  Check the defining Type statement in the application modules to find the element names for this data type.


Type not defined

A variable or argument was declared with an undefined data type.  Use the Type statement in a module to define a new data type.


Must be first statement on the line

Sub and Function must always be the first statement on any line in which they appear.  Additionally, End If, Else (only when used in a block If structure), and ElseIf can be used only when they are the first statements on a line.


End Sub or End Function must be last statement

Nothing can appear in a Code window below the statement terminating the procedure.  Move all lines below the End Sub or End Function statement into the procedure.


End Type without Type

An End Type statement does not have a matching Type statement.


Statement invalid in Type block

Only comments and the As datatype clause are allowed within a Type...End Type pair.


Invalid Declare for procedure
Invalid Declare for Visual Basic procedure

You tried to declare a Visual Basic function in a form.  You can declare a Visual Basic function only in a module, and then only if you want to declare a function that has no arguments so it can be invoked without parentheses.  If this is the case, declare it in the Declarations section of each module where a reference to the function occurs.  You can then refer to the function without parentheses from each module where it is declared.  However, you still need to include the parentheses if you refer to the function from a form or from a module that does not contain an explicit declaration for the function.  Declarations for Visual Basic Sub procedures are not allowed.


Operation requires disk

You are attempting to load from, or save to, a non-disk device such as the printer, keyboard, or communications port.


Breakpoint not allowed on this line

You cannot set a breakpoint in any of the following:

Declarations section of a form or module

Case clause

End Select statement

Blank line


Label definition invalid in Immediate window
Label definition invalid in Immediate pane

You cannot enter a line label or line number in the Immediate pane. A label is a string followed by a colon or a line number.  A number on a line by itself is interpreted as a label.


Invalid in Immediate window
Invalid in Immediate pane

Possible causes:

Declarative statements such as Const, Declare, Deftype, Dim, Function, Global, Option Base, Option Explicit, Option Compare, ReDim, Static, Sub, and Type are not allowed in the Immediate pane.

Multiline statements, such as a block If, are not allowed in the Immediate pane.

You tried to execute some code in the Immediate pane that invalidates the current state of your program and requires reinitializing the program.


File previously loaded

You tried to load a file that has the same name as a loaded file or module.


Tried to load file with duplicate procedure definition
Tried to load file with duplicate procedure definition: <procedure name>

You tried to load a module that contains one or more procedure names already used in the existing procedures.  Use the Find command on the Edit menu to find the duplicated procedure names.


Can't load module; invalid format

You tried to load a module that has an incompatible format or is damaged.


Use Static or ReDim to dimension arrays in this procedure

You are trying to use Dim to create a fixed array (an array having a specific number of elements) at the procedure level.  To create a fixed array, use Dim at the module level or Static at the procedure level.  You may also choose to create a dynamic array at the procedure level using ReDim.

Arrays created with Static are persistent arrays whose values are kept in memory after the procedure is finished running.  Procedure-level dynamic arrays are released automatically at procedure exit.


Wrong number of dimensions

You referred to an array with a different number of dimensions than it actually has -- for example, referring to an array as X(2,4), an array with two dimensions, when it has been defined as Dim X(5), a one-dimensional array.


End If without block If

An End If statement is used without a corresponding If statement.  Check other control structures within the If...End If structure and verify that they are correctly matched.  For example, a While without a matching Wend inside the If...End If structure will generate this error.

Also check that the block If is correctly formatted.


Block If without End If

An If statement is used without a corresponding End If statement.  Check if there is an incorrectly matched If...End If structure inside the outer If...End If structure.

Also check that the block If is correctly formatted.


Else without If

An Else statement is used without a corresponding If statement.  Check other control structures within the If...Else structure and verify that they are correctly matched.  For example, a While without a matching Wend inside the If...Else structure will generate this error.

Also check that the block If is correctly formatted.


Exit Do not within Do...Loop

An Exit Do statement is used outside of a Do...Loop statement.  Make sure a valid Do statement precedes the Exit Do.


Exit For not within For...Next

An Exit For statement is used outside of a For...Next statement.  Make sure a valid For statement precedes the Exit For.


Loop without Do

A Loop statement is used without a corresponding Do statement.  Check other control structures within the Do...Loop structure and verify that they are correctly matched.  For example, an If without a matching End If inside the Do...Loop structure will generate this error.


Select Case without End Select

A Select statement is used without a corresponding End Select statement.  Check if there is an incorrectly matched Select...End Select structure inside the outer Select...End Select structure.  If you have nested Select Case statements, each must have a matching End Select.


Case without Select Case

A Case statement is used without a corresponding Select Case statement.  Check other control structures within the Select Case...Case structure and verify that they are correctly matched.  For example, an If without a matching End If inside the Select Case...Case structure will generate this error.


End Select without Select Case

An End Select statement is used without a corresponding Select Case statement.  Check other control structures within the Select Case...End Select structure and verify that they are correctly matched.  For example, an If without a matching End If inside the Select Case...End Select structure will generate this error.


User-defined type variable not allowed in expression

A variable of a user-defined type must be passed by reference in a Sub or Function call [image] it cannot be passed by value (i.e., as an expression).  For example, Sub1 Record is allowed, but Sub1 (Record) produces this error.  Note that you can pass an element of a user-defined type by value.  For example, Sub1 (Record.Element1) is allowed if Element1 is an fundamental data type -- that is, Integer, Long, Single, Double, Currency, String or Variant.


Parameter type mismatch

Possible causes:

An argument in a Sub or Function call does not have the correct data type.  For example, trying to pass a numeric value where a string is expected or vice versa produces this error.

An argument in a Sub or Function call is a property and is passed by reference [image] properties must be passed by value.  To pass an argument by value, either use ByVal in the Sub or Function argument list definition or enclose the argument in parentheses in the Sub or Function call.  For example, to pass the command button Caption property to a procedure,  Sub1 (Command1.Caption) is allowed, but  Sub1 Command1.Caption  produces this error.


Statements/labels invalid between Select Case and Case

Statements and line labels or line numbers are not permitted between Select Case and the first Case statement.  Comments and statement separators are permitted.


Invalid outside of Type block

The element As type clause is permitted only within a Type...End Type block.


Expression not allowed here

The indexes in an array definition, such as in a Dim, Global, or Static statement, cannot contain an expression.  For example,  Dim x(3*5)  will produce this error.  You can use a Const statement to evaluate the expression and then use the constant to dimension the array.


Duplicate Deftype statement

Part or all of the letter range for this Deftype statement is already included in another Deftype statement at this level of scope.


Label not defined

A line label or line number is referred to (in a Goto statement, for example), but does not occur in the code.


For without Next

A For statement is used without a corresponding Next statement.  Check if there is an incorrectly matched For...Next structure inside the outer For...Next structure.


While without Wend

A While statement is used without a corresponding Wend statement.  Check if there is an incorrectly matched While...Wend structure inside the outer While...Wend structure.


Wend without While

A Wend statement is used without a corresponding While statement.  Check other control structures within the While...Wend structure and verify that they are correctly matched.  For example, an If without a matching End If inside the While...Wend structure will generate this error.


Array not defined

Visual Basic requires all arrays to be declared [image]. You declare an array with a Dim, Global, Static, or ReDim statement.


Variable required

Possible causes:

You have attempted to use a numeric expression as an argument to the Len function.  The Len function does not accept a numeric expression, but it does accept either a string or numeric variable or a string expression.

You have used a function call  or an expression as an argument to Input, Let, Get, or Put.  For example, you've used an argument that appears to be a valid reference to an array variable, but instead is a call to a function of the same name.  These statements do not accept function calls as arguments.


This variable can't be passed by value
This variable type can't be passed by value

Object variables must be passed by reference.  For example, if the argument of a procedure named Sub1 is defined to be of the control data type, that is, Sub1 (A as Control), then  Sub1 Command1  is allowed, but Sub1 (Command1) is not.  Putting parentheses around an argument causes it to be passed by value.


Function reference must be followed by ( )

A Visual Basic Function procedure is called using the function name, followed by the argument list in parentheses.  If the function has no arguments, you still must include the parentheses unless a Declare statement was used to declare the function.


Next without For

A Next statement is used without a corresponding For statement.  Check other control structures within the For...Next structure and verify that they are correctly matched.  For example, an If without a matching End If inside the For...Next structure will generate this error.


Invalid use of object

Get, Input #, Line Input #, LSet, Mid$, Put, and RSet cannot be used with objects or properties.  For example,  Input #1, Form1.BackColor  will produce this message.


Invalid argument for DLL Sub or Function

You can pass array elements, but not a whole array, to a DLL.


Function not defined

A statement in the code looks like a function call, but there is no corresponding function definition with that name.

Possible causes:

The function name is misspelled or is not defined.

The scope of the function does not extend to the procedure that is referring to it.  Note that code within a form is recognized only by the procedures in that form.


Reference to undefined function or array

A statement in the code looks like a function call or array, but there is no corresponding function definition with that name.

Possible causes:

The function or array name is misspelled or is not defined.

The scope of the function or array does not extend to the procedure that is referring to it.  Note that code within a form is recognized only by the procedures in that form.


Duplicate definition with existing object

There is already an object with this name.


ReDim not allowed on object

You cannot resize a object array using Redim.  Use the Load statement to add more controls to a control array.  Use Unload to remove controls from a control array.


User-defined type with Variant or variable-length String element not allowed.

LSet or RSet require that user-defined datatypes have fixed-length data elements.


Must have startup form or Sub Main ()

There is no form in the current project, and the current project does not have a Sub procedure named "Main" in any module.  You must have one or the other to run a Visual Basic application.


Can't save file to TEMP

The directory established by your TEMP environment variable cannot be written to.  Check that your TEMP environment variable is set to a valid directory and that the disk is not full.


Error reading Tutorial file 'item'

The Tutorial file is damaged.  To reinstall the Tutorial, use the Visual Basic Setup disks.


Tutorial directory 'item' not found

The Tutorial directory, VB.CBT, was not found.  To install the Tutorial, use the Visual Basic Setup disks.


Can't find Tutorial file 'item'
Can't find file 'item'

A file needed by the Tutorial or Intro Computer Based Training (CBT) cannot be found. The tutorial file should be in the VB.CBT directory.  The Intro file should be in the Visual Basic (VB) directory  To reinstall the Tutorial or Intro files, use the Visual Basic Setup disks.


Not enough memory to load Tutorial
Not enough memory to load help file.

The Tutorial or Intro help files cannot be loaded because of low memory.  Close some documents or applications that are not needed and try again.


One or more replacements too long and not made

A Replace operation has attempted to create a line of code longer than the 1023-character maximum allowed.  Those replacements where the resulting line is less than 1023 characters were completed.  Use the Find command to find instances where the replacement was not done and break the long statements into several lines.


Syntax errors produced while replacing

The Replace command has introduced some errors in the code.


Can't find Windows Help .EXE file

The Windows Help application is not available.  If WINHELP.EXE is on your machine, make sure it is on your path.  If it is not on your machine, run Windows Setup to install it.


Invalid procedure name

A procedure name cannot be a reserved word, must start with a letter, and can be a maximum of 40 characters [image] including letters, numbers, and underscores (_).  Function procedure names can include a type declaration character, but Sub procedure names cannot.


Nothing to search for or replace

Find doesn't have anything to look for.  Enter a string into the Find What text box from the Find or Replace dialog box on the Code menu.


Not enough room to paste contents into current line

A line of Visual Basic code cannot contain more than 1023 characters.  Break the line into individual statements or assign some expressions to intermediate variables.


Can't set next statement

You are trying to set the next statement to a statement outside the current procedure.  The Set Next Statement command on the Run menu works only within the current procedure.


Search text not found

The specified text was not found during the search.  You might expand the search to "Current module" or "All modules" by checking the appropriate box in the Search dialog box.


Array already has a control at index 'item'

Possible causes:

You tried to change the index to a number that is already used by this control array.  To determine which indexes have already been assigned, select the Index property on the Properties bar for each control array element.  The assigned index appears in the Settings text box.

You tried to change the CtlName of a control in an array to the name of a control array already using this index.


Not a legal object name: 'item'

Form and control names must start with a letter and can be a maximum of 40 characters [image] including letters, numbers, and underscores (_).

Note that FormName and CtlName properties are different from the label properties [image] Caption, Text, and Value [image] which label or display the contents of a control at run time.  These properties can be reserved words, can begin with a number, and can contain non-alphanumeric characters.


Must specify which item(s) to print

You have not specified what to print.  Check at least one of the Form or Code check boxes in the Print dialog box after choosing Print from the File menu.


'item' is a form property name

You can't use the name of a form property to name a control.  To find out what words are reserved for form property names, see the Form topic in Help for complete information.


'item' is a form name

A form already has this name.  To find the duplicate, look in the Project window at the list of forms used in the project.  Note that a control cannot have the same name as any form in the same project.


'item' is a system object name

Screen, Clipboard, and Printer name system objects, so they cannot be used as a form or control name.


Event handler must be a Sub procedure

A valid event procedure, such as Form_Click, must be a Sub procedure [image] it cannot be a Function procedure.


Incorrect number of event procedure arguments

Possible causes:

An event procedure for a control array needs to be defined with the Index argument [image] for example, Command1_Click (Index as Integer), while an event procedure for a non-control array cannot take the Index argument.  Check the control's Index property.  If it is non-null then the control is considered part of a control array.

An event procedure was written for a control before the control was made part of a control array or before the control was removed from a control array.  In either case, the number of arguments is incorrect, either because the index needs to be added or because it must be removed.  Edit the event procedure in the Code window to add or remove the index argument.

An argument has been added or removed from the event procedure definition.  You can determine the correct syntax of the event procedure by looking at Help on the event.


Event procedure argument has incorrect data type

Some change has been made to the data type of an event procedure's arguments  The data type does not match the data type specified in the original event procedure definition.  To determine what the argument data types should be, use Search in Help to find the event procedure name and change the arguments back to what they originally were.


Can't assign shortcut key to menu name

You are trying to assign a key combination to a parent or top-level menu item that is not a command.  Only commands can have shortcut keys assigned to them.


Can't use separator bar as menu name

You are trying to put a separator bar in a parent or top-level menu name [image] these names must be text.


Shortcut key already assigned

You tried to assign an shortcut key that has already been assigned to another menu item.  Reassign the shortcut key.


Separator may not be checked or disabled, or have an shortcut key
Separator bar may not be checked or disabled, or have an shortcut key

You are trying to modify a separator on a menu.  Separators help to visually organize menu items.  They can't be disabled or enabled, or modified with check marks or shortcut keys.


At least one submenu item must be visible

The Visible property can't be set to False (0) for the last visible submenu item.  You can't have a parent menu with no visible submenu items.


Can't load Custom Control DLL: 'item'

Visual Basic could not load the specified custom control dynamic-link library (DLL).

Possible causes:

You attempted to use the Add File command to load a DLL file that is not a valid Visual Basic custom control DLL.  Custom control files usually have a .VBX extension.

You opened a project that contained a reference to a custom control DLL.  This DLL file exists but is not a valid custom control DLL.  The DLL file may have been damaged in some way; try replacing it with an undamaged copy.


Can't unload Custom Control DLL; in use

You can't remove a custom control dynamic-link library (.VBX) file from the project when a custom control from that file has been placed on a form.  If you want to unload the custom control file, first remove all of that file's custom controls from all forms in the project.


Can't quit at this time

You can't quit Windows while Visual Basic is in run or break mode.  You also can't quit Windows while a dialog box or message box is displayed.


You'll have to restart your program after this edit--proceed anyway?

You have edited some code that invalidates the current state of your program and requires reinitializing the program.  Click Cancel to restore the code to its original state, or click OK to re-initialize your program.


Invalid command-line argument 'item'

There is an invalid argument in the command line used to invoke Visual Basic.  Valid command line arguments are:

/run  ProjectName

FileName

/cmd  command-line argument


Reset halted programs so Code window can be closed?

To close the Code window and reinitialize your program, click OK.  To continue running your program, click Cancel.


Save changes to 'item'?

This file has changed since it was last saved.  Click Yes to save it, click No to close the file without saving it, or click Cancel if you do not want to close the file.


Not enough stack space to enter break mode--continue?

There is not enough stack space to save the current state and enter break mode.  To continue running the program, choose OK.  To reinitialize your program and return to design mode, choose Cancel.


Not enough stack space to enter break mode for error--must reset

There is not enough stack space to save the current state and enter break mode.  You must restart or end the program.


Line too long to edit--edit truncated line?

The current line is longer than the Visual Basic code editor can handle.  After you enter a line of code in the Code window, extra spaces are added between items in the line, which may make the line longer than the 1023-character maximum.  The line will still be readable by Visual Basic, but cannot be edited without losing some characters from the end of the line.

If you need to save this line, use the Save Text command on the File menu to save it to a file, and then use a different editor to break the line into separate lines or to assign some expressions to intermediate variables.  Reload the file into Visual Basic with the Load Text command on the File menu.


'item' has been changed; must reset

The changes you made require you to restart the program.


Search complete

There are no more instances of the text you want to search for.  If all instances were not found, verify the options you chose in the Find or Replace dialog box.


You already have a control named 'item'.  Do you want to create a control array?

You've tried to set CtlName or paste a new control onto the form, and you already have a control with the indicated name.

If you would like to create a control array, choose Yes.  The newly created control array element will have an Index one higher than the control previously created with this name.  If you do not want to create a control array, choose No.  If you're pasting a control, Visual Basic will generate a name for the new control.


Error loading 'item'.  An error was encountered loading a property.  Continue?

You may have tried to load a form with controls whose names conflict with forms already in the project.  For example, loading Form2 that contains a Form1 control will trigger this error.


Error loading 'item'.  A control could not be loaded due to load error.  Continue?

This error message appears after another error has occurred.  Once you've taken the appropriate action for that error, you will see this error message.  To load the control anyway, choose Yes; to cancel the loading, choose No.


Form had old file format

The form or module has an old file format.  To update the file format, choose Save File or Save Project from the File menu.


Replace existing 'item'?

There is already a file by that name.  Click Yes to replace that file with the current file, or click Cancel to stop the save operation.


'item' does not exist

The file you specified does not exist in the specified directory.  Check that you have spelled the file name correctly and specified the correct directory.


'item' already exists in project

The file you specified is already part of the project.  You cannot add the same file to a project more than once.  You cannot save a file with the same name as another file in the project.


Parent or top level menu item may not be checked
Parent or top-level menu item may not be checked

You may not use the checked option on the menu item that will appear on the menu bar or on a menu that has submenus.


Error loading 'item'.  The code associated with this form could not be loaded.  Continue loading form?

Visual Basic could not load the code in this form file. Do you want to continue to load the form anyway?


Search string too long.
Search string too long

The length of the string that you are searching for is too long. Reduce the length of the string and try again.


Unable to get system fixed font

A request was made for the system fixed font.  The font returned was not fixed-pitch.  There may be a problem with the font or screen driver setup on your system.  You may need to reinstall Microsoft Windows.


Incompatible version created '|'
Incompatible version created '<filename>'

The binary program file being loaded was incompatible with the current version of Visual Basic.  This can occur when the binary file is damaged or created by a version not supported by the current version.


Return without GoSub

Error 3

A Return statement doesn't have a corresponding GoSub statement.

Unlike For...Next, While...Wend, and Sub...End Sub, which are matched at compile time, GoSub and Return are matched at run time.


Illegal function call

Error 5

Possible causes:

A statement or function has an improper or out-of-range argument.  For example:

A negative or unreasonably large subscript

A negative number raised to a non-integer power

A negative record number in a Get or Put statement

An I/O function or statement (Loc or LOF, for example) performed on a device that does not support it

Strings are concatenated to create a string greater than 65,535 characters in length

Invalid method call, such as an inappropriate method argument


Overflow

Error 6

Possible causes:

The result of an assignment, calculation, or data type conversion is too large to be represented within the range allowed for that type of variable.

An assignment to a property exceeds the maximum value the property can accept.  The assignment may not necessarily be one that you have made in your code.  Some methods make automatic assignments to properties.  For example, in the course of execution, the Print method changes CurrentX and CurrentY properties.  Any attempt to print at an invalid CurrentX or CurrentY location results in an Overflow error.


Out of memory

Error 7

More memory was required than is available, or a 64K segment boundary was hit.  To prevent this error, you should try the following:

Close any unneeded applications, documents, or source files that are in memory.

If you have extremely large modules or procedures, consider breaking them into smaller ones.  This doesn't save memory, but it can prevent hitting 64K segment boundaries.

If you are running Windows in standard mode on a 386 or 486 computer, try enhanced mode.

If you are running Windows in enhanced mode, free up some disk space, or least ensure that some space is available.

Eliminate terminate-and-stay-resident programs.

Eliminate unneeded device drivers.

Reduce the number of global variables.


Subscript out of range

Error 9

Possible causes:

Reference to 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.


Duplicate definition

Error 10

The specified name is already used at this level of scope.  You can use the Find command on the Edit menu to help locate the duplicate name.  When specifying the name to search for, remove the type-declaration character, if there is one, since a conflict occurs if the names are the same and the type-declaration characters are different.

Possible causes:

A new variable or procedure has the same name as an existing variable or procedure.

A Const statement uses the same name as an existing variable or procedure.

You declared a fixed array more than once.

You tried to use Dim or ReDim to declare the dimensions of an already-dimensioned dynamic array without first using Erase to deallocate the array.


Division by zero

Error 11

This error is caused by dividing by zero in an expression.


Type mismatch

Error 13

Possible causes:

The variable or property is not of the correct type.  For example, a variable that requires an integer value cannot accept a string value.

An If TypeOf statement was used with something other than a control.

An object that is not a form has been passed to a procedure that is expecting a form as an argument.

An object that is not a control has been passed to a procedure that is expecting a control as an argument.


Out of string space

Error 14

Possible causes:

You tried to create a single string array larger than 64K.

You may have run out of memory, which has prevented a 64K string space from being allocated.


String formula too complex

Error 16

A string expression is too complicated.  Strings not assigned to variables (such as those returned by functions) are assigned to temporary locations during string expression evaluation.  Having a large number of such strings can cause this error.  Try assigning these strings to variables and use the variables in the expression instead.


Can't continue

Error 17

You have made a change to the code that prevents execution from continuing.  Choose Continue or End from the Run menu.


No Resume

Error 19

The program has encountered the end of the program while executing an error-handling routine.  Add a Resume statement to the error-handling routine.  If you want to exit the error-handling routine without resuming, use an Exit statement.


Resume without error

Error 20

A Resume statement has been encountered, but there is no active error-handling routine because there is no On Error statement.


Out of stack space

Error 28

Possible Causes:

Too many active Function or Sub calls.  Check that both event and general recursive procedures are not nested too deeply and that they terminate properly.

A cascading events will cause this error.

Local variables require more local variable space than is available.  Try declaring some variables at the module level instead.  You can also use the Static keyword with Sub or Function to declare the entire procedure, in which case all local variables will be static. Or you can use the Static statement to declare static variables within individual procedures

Fixed-length strings use more stack space than variable-length strings.  Try redefining some of your fixed-length strings as variable-length strings.

Too many nested DoEvents statements.

Use the "Calls" menu to view which procedures are active (on the stack).


Sub or Function not defined

Error 35

A Sub or Function procedure is called but is not defined.

Possible causes:

The specified procedure is not visible to the calling procedure.  Procedures in a form cannot be called from procedures outside the form.   Use Find on the Edit menu to locate the procedure.

You have declared a dynamic-link library routine, but the routine is not in the specified library.

You have misspelled the name of your procedure.


Error in loading DLL

Error 48

The specified DLL cannot be loaded.  This is usually because the file specified with the Lib clause in the Declare statement is not a valid DLL.

Possible causes:

The file is not DLL-executable.

The file is not a Windows DLL.

The file is an old Windows DLL that is incompatible with Windows protect mode.

The DLL requests another DLL that is not present.


Bad DLL calling convention

Error 49

Your program is calling a routine in a dynamic-link library that either is being passed the wrong type or number of arguments or does not use the Pascal calling convention.  Make sure that the arguments passed to the DLL routine exactly match the arguments expected by the routine.  If the DLL routine expects arguments by value, then make sure ByVal is specified for those arguments in the declaration for the routine.


Internal error

Error 51

An internal malfunction has occurred in Visual Basic.  Unless this call was generated by the Error statement, use the Product Assistance Request form included with your documentation to report to Microsoft the conditions under which the message appeared.


Bad file name or number

Error 52

A statement or command refers to a file with a file number or file name that is not specified in the Open statement or is out of the range of file numbers specified earlier in the application.

The filename used may be invalid. When using MS DOS, you will need to 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 eight characters, and the extension can contain up to three characters.

The name must start with either a letter or number. It can contain any uppercase or lowercase (filenames are not case-sensitive) characters except the following:

period (.)	quotation mark (")
slash (/)	backslash (\)
brackets ([ ])	colon (:)
semicolon (;)	vertical bar (|)
equal sign (=)	comma (,)

The name should not contain any spaces. The following names are reserved and cannot be used for files or directories: CON, AUX, COM1, COM2, COM3, COM4, LPT1, LPT2, LPT3, PRN, and NUL.  Examples of valid filenames are LETTER.DOC, MEMO.TXT, BUDGET.92, 12345678.901 and 2NDTRY.RPT.


File not found

Error 53

Possible causes:

A Kill, Name, or Open statement refers to a file that does not exist.

An attempt has been made to call a procedure in a DLL and the library file name specified in the Lib clause of the Declare statement cannot be found.


Bad file mode

Error 54

Possible causes:

A Put or Get statement specifies a sequential file. Put or Get can only refer to files opened as Random.

A Print # statement specifies a file mode other than Output or Append.

An Input # statement specifies a file mode other than Input.


File already open

Error 55

Possible causes:

A sequential-output-mode Open statement was executed for a file that is already open.

A Kill, SetAttr, or Name statement refers to an open file.


Device I/O error

Error 57

An input or output error occurred while your program was using a device such as the printer or disk drive.


File already exists

Error 58

The new file name specified in a Name statement is identical to a file name that already exists.


Bad record length

Error 59

The length of a record variable for a Get or Put statement does not match the length specified in the corresponding Open statement.  Because a two-byte descriptor is always added to a variable-length string Put to a random access file, the variable-length string must be at least two characters shorter than the record length specified in the Len clause of the Open statement. Variant data types also require a two-byte descriptor.  Variants containing variable-length strings require a four-byte descriptor.


Disk full

Error 61

Possible causes:

There isn't enough room on the disk for the completion of a Print #, Write #, or Close operation.

There isn't enough room on the disk for Visual Basic to create files it requires for successful operation.

Move some files to another disk, or delete some files.


Input past end of file

Error 62

An Input # or Line Input# statement is reading from an empty file, or from a file in which all data has already been read.  To avoid this error, use the EOF function to detect the end-of-file just before the Input # statement.


Bad record number

Error 63

The record number in a Put or Get statement is less than or equal to zero.


Bad file name

Error 64

A file name does not follow DOS naming conventions.


Too many files

Error 67

Possible causes:

There is a limit to the number of disk files that can be open at one time.  This limit is a function of the "Files=" setting in your CONFIG.SYS file.  Increase that number and reboot.

The operating system has a limit to the number of files in the root directory (usually 512).  If your program is opening, closing, and/or saving files in the root directory, change your program so it uses a subdirectory.


Device unavailable

Error 68

The device you are trying to access is not online or does not exist.


Permission denied

Error 70

An attempt was made to write to a write-protected disk or to access a locked file.  For example, this error will occur if an Open For Output statement is performed on a write-protected file.


Disk not ready

Error 71

There is no disk in the drive specified, or the drive door is open.  Insert a disk in the drive, close the door, and retry the operation.


Can't rename with different drive

Error 74

You cannot use the Name statement to rename a file with a new drive designation.  Use FileCopy to write the file to another drive, and delete the old file with a Kill statement.


Path/File access error

Error 75

During an Open, MkDir, ChDir, or RmDir operation, the operating system could not make a connection between the path and the file name.

Make sure the file specification is formatted correctly.  A file name can contain a fully qualified 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 is not fully qualified is relative to the current drive and directory.

This error can also occur while attempting to save a file that would replace an existing read-only file.


Path not found

Error 76

During an Open, MkDir, ChDir, or RmDir operation, the operating system was unable to find the specified path.  Make sure the path is typed correctly.


No timer available

Error 260

Possible causes:

There are too many timer controls active.  There is a limit of 16 timer controls in the environment.

There is not enough memory to load a timer control.  Try to free up some memory by closing other applications.


DDE channel not fully closed; awaiting response from foreign application

Error 280

Your Visual Basic application has terminated one DDE conversation with another application and has attempted to start a new conversation, but the other application has not finished handling the termination of the first conversation.

Possible causes:

The other application is waiting for a response from the user.  Switch to that application and take an action appropriate to the message it is displaying.

Your code is not yielding to allow other applications to handle events.  Call the DoEvents function and try establishing the link again.


No more DDE channels

Error 281

Too many DDE conversations are active at the same time.  Terminate some existing DDE conversations by setting LinkMode to 0 (None) before attempting to establish new conversations.


No foreign application responded to a DDE initiate

Error 282

Visual Basic could not find an application and topic corresponding to the application name and topic in the LinkTopic property.

Possible causes:

The application specified in LinkTopic is not running.

The application is running, but doesn't recognize the topic of the link.


Multiple applications responded to a DDE initiate

Error 283

At least two running applications have responded to the application name and topic you specified in the LinkTopic property.  This can happen if several instances of the same application are running and you attempt to initiate a DDE conversation on a topic more than one of them recognize.  To establish a DDE conversation, the combination of application and topic must be unique.


DDE channel locked

Error 284

You have attempted to initiate a new DDE conversation or perform a DDE method on a DDE link that another application has not freed.  Try calling the DoEvents function before setting LinkTopic to Automatic (1) or Manual (2) or before performing a LinkExecute, LinkPoke, LinkRequest, or LinkSend method.


Foreign application won't perform DDE method or operation

Error 285

An application refused to perform the DDE method or operation you attempted.

Possible causes:

You supplied data or commands that the other application did not recognize.  Check the application's documentation to see what data or commands it recognizes.

The LinkItem property is not set to an item that the other application recognizes as valid for the topic of the conversation.  Check the application's documentation to see what items it recognizes.


Timeout occured while waiting for DDE response
Timeout occurred while waiting for DDE response

Error 286

The other application in a DDE conversation did not respond in the time specified by the LinkTimeout property.

Possible causes:

The other application is not responding because it is waiting for a response from the user.  Switch to that application and close the dialog box or take an action appropriate to the message it is displaying.

The LinkTimeout property is set to a value that is too low.  Try increasing the value.

The other application is too busy to respond to DDE messages.  Try calling the DoEvents function before performing this DDE operation.


User pressed Alt key during DDE operation
User pressed ESC key during DDE operation

Error 287

You pressed the ESC key while waiting for a DDE operation to be completed.  If DDE operations are taking too long, try setting the LinkTimeout property to a lower value.


Destination is busy

Error 288

The other application in the DDE conversation is busy and cannot perform a DDE operation.  Try calling DoEvents and attempt the DDE operation again.


Data not provided in DDE operation

Error 289

Visual Basic has encountered an unexpected error while attempting to perform a DDE operation.  The other application informed Visual Basic it was supplying data in a DDE conversation but did not provide it when requested.  The other application may not be performing DDE correctly.


Data in wrong format

Error 290

An application in a DDE conversation supplied data in an unexpected format.  It may not be performing DDE correctly.

Possible causes:

The application is supplying data in a format that Visual Basic does not recognize.  Try initiating the conversation with a different topic.

The application is supplying text data to a picture box or picture data to a text box.  Try initiating the conversation with a different control.


Foreign application quit

Error 291

The other application in a DDE conversation quit unexpectedly.  A DDE operation can't take place unless the other application is running.


DDE conversation closed or changed

Error 292

The other application has closed or changed the DDE conversation unexpectedly.  Terminate this conversation and attempt to establish a new conversation with the application.


DDE method invoked with no channel open

Error 293

A DDE method (LinkExecute, LinkPoke, LinkRequest, or LinkSend) was performed on a control that is not involved in a valid DDE conversation.

Possible causes:

Changing the LinkTopic property terminates an existing DDE conversation but does not automatically establish a new conversation.  After changing the LinkTopic property for a control, you must set the LinkMode property to 1 (Automatic) or 2 (Manual) before executing a DDE method on this control.

You executed a DDE method on a control with LinkMode set to 0 (None).  Set the LinkMode to 1 (Automatic) or 2 (Manual) and try again.


Invalid DDE link format

Error 294

The other application in a DDE conversation passed data in CF_LINK format, but it is not valid link data.


Message queue filled; DDE message lost

Error 295

Visual Basic cannot keep up with the number of DDE operations attempted.

Possible causes:

Too many DDE conversations.  Try terminating some DDE conversations.

Too much code in event procedures is executing because of incoming DDE data.  Reduce the amount of code being called as a result of DDE changes, or try calling the DoEvents function.


PasteLink already performed on this control

Error 296

You have already performed a Paste Link on this control.  To paste a new link, first set the LinkMode property of this control to 0 (None), and then use the Paste Link command.


Can't set LinkMode; invalid LinkTopic

Error 297

You've tried to set the LinkMode property but can't because no valid LinkTopic property has been specified.


DDE requires DDEML.DLL

Error 298

A DDE operation was initiated, but the DDEML.DLL file was not located. This file must be present in the path in order for DDE operations to work.


Can't use character device names in filenames: 'item'

Error 320

From within Visual Basic, you cannot give a file the same name as a character device driver, such as AUX, CON, COM1, COM2, LPT1, LPT2, LPT3, LPT4, or NUL.


Invalid file format

Error 321

The form file is damaged.  Try replacing it with an undamaged copy. This could be caused by having mismatched custom controls.  This error could be triggered if the number of properties in the current version of the control do not match the number expected.


Control array element 'item' does not exist

Error 340

You used an index value that does not correspond to an existing element in this control array.  Adjust the value or Load a control into the array with an index equal to the value.


Invalid object array index

Error 341

The index for an object array element cannot be greater than 32,767 or less than 0.


Not enough room to allocate control array 'item'

Error 342

There isn't enough memory to create all the elements of a control array.  If a control array has discontiguous indexes, such as 0, 2, and 4, Visual Basic will use more memory than if the indexes were contiguous (0, 1, 2).  Check either how you've assigned indexes at design time or how your program assigns indexes as it creates new control array elements, and make them contiguous.


Object not an array

Error 343

A control that is not part of any array is referred to as if it has an index, for example, Command1(3).Caption and Command1.Text.  You can refer to an object as an array element only if it is defined to be part of an control array [image] see Creating a Control Array.


Must specify index for object array

Error 344

The control referred to is part of a control array.  Refer to it using CtlName(index).  If you created the control at design time, you can determine the index of the control by selecting it and viewing its Index property in the Properties window.


Reached limit: cannot create any more controls for this form
Reached limit: cannot create any more controls on this form

Error 345

No more than 255 controls are allowed on each form.  The total of all menu items and controls on your form would exceed 255 if any more were added.


Object already loaded

Error 360

The control in the control array has already been loaded.  If it was loaded during run time, it can be removed with the Unload statement.


Can't load or unload this object

Error 361

Possible causes:

You've attempted to Load or Unload a system object [image] Screen, Printer, or Clipboard.

You've attempted to Load or Unload a control that is not an element of an existing control array.  For example,  Load CtlArray  will produce this error, while  Load CtlArray(3)  will not.  If a control is already loaded, you can make it visible with the Visible property.


Can't unload controls created at design time

Error 362

Only control array elements loaded at run time can be unloaded.  If a control is created at design time, it cannot later be unloaded, even if it is part of a control array.  However, you can hide any control by setting the Visible property to False.


Custom control 'item' not found

Error 363

The form being loaded contains a custom control that is not part of the current project.  Use the Add File command on the File menu to add the custom control to the project.


Object was unloaded

Error 364

A form was unloaded from its own Form_Load procedure.  The form that was unloaded may have been implicitly loaded.  For example, the following will implicitly load Form2 if it is not already loaded:

Form2.BackColor = Form1.BackColor


Unable to unload within this context

Error 365

In some situations you are not allowed to unload a form or a control on a form.  For example, this occurs when trying to unload a form or control on the form:

During any Paint event for the form or for any control on the form.

Whenever a combo box is pulled down on the form being unloaded or containing the control being unloaded.


No MDI form available to load

Error 366

You set the MDIChild property on a form to True, but at run time, there was no MDI form in your project to load.


Invalid property value

Error 380

An inappropriate value is assigned to a property.  To find out what values are valid for a property, see the remarks in the property's Help topic.


Invalid property array index

Error 381

You tried to use an inappropriate property array index value.  List Property and Fonts Property index values must be greater than 0 and less than 32,767.  For example, List1.List(3) is valid.


'item' property cannot be set at run time
'item' property can't be set at run time

Error 382

The following properties can't be set at run time:

ActiveControl	ActiveForm

BorderStyle (for form and text box only)	ControlBox

Fonts	FontCount

hDC	hWnd

Image	Index

List	ListCount

MaxButton	MinButton

MultiLine	Name

Parent	ScrollBars

Sorted	Style

Text (for list box and combo box only)	Width (for Screen only)


'item' property is read-only

Error 383

The following properties are read-only at both design time and run time.

Property	On Object

hDC	Form, picture box, Printer

Height	Combo box (with Style = 1), drive, Printer

hWnd	Form

Image	Form, picture box

List	Dir, drive, file

ListCount	Combo box, dir, drive, file, list box

Page	Printer

Parent	Any control

Text	Combo box (with Style = 2), list box

Width	Printer


'item' property can't be modified when form is minimized or maximized

Error 384

The Left, Top, and Height, Width properties cannot be changed on a minimized or maximized form.  You can set or return the state of a form with the WindowState Property.  You can prevent a user from maximizing or minimizing a form by setting the MaxButton or MinButton form properties to False (0).


Must specify index when using property array

Error 385

You must specify an index when using the List Property or the Fonts Property.  Index values must be greater than 0 and less than 32,767.  For example, List1.List is invalid because no index is specified.  However, List1.List(3) is valid.


'item' property not available at run time

Error 386

The Name property is not available at run time.


'item' property can't be set on this control

Error 387

Possible causes:

The Checked box for a menu control can't be selected when that control is a parent or top-level menu.

The separator bar on a menu control can't be set when the control is a parent or top-level menu item.

The Visible property can't be set to False (0) for the last visible submenu on a parent menu.  You can't have a parent menu with no visible submenu items.


Can't set Visible property from a parent menu

Error 388

The Visible property of a submenu item cannot be set from its parent's menu code.


Name not available.
Name not available

Error 391

A custom control (.VBX) file tried to use the VBGetControlName API against a VISUAL BASIC application in .EXE form. VISUAL BASIC does not embed object names in the executable (.EXE) file. Consult the author of the .VBX file.


MDI Child forms cannot be hidden

Error 392

You cannot set the hidden property to True or use the Hide method with MDI child forms.


'item' property cannot be read at run time

Error 393

You have tried to read a property that is only available in design mode.  Some properties may be visible and alterable at design time but cannot be read during run time.


'item' property is write-only

Error 394

Indicates that a property cannot be read, i.e., "ctl.property = 3" is legal, but "Print ctl.property" generates this error.


Can't use separator bar as menu name

Error 395

A menu caption that has submenus cannot be changed to a separator bar at run time.


Form already displayed; can't show modally

Error 400

You cannot use the Show method to display a modal form if the form is already visible.  Either Unload or Hide the form before attempting to show it as a modal form.  Don't try to display it as a modal form.


Can't show non-modal form when a modal form is displayed

Error 401

You cannot show a non-modal form when a modal form is displayed.  Unload or Hide the modal form before attempting to use the Show method on another form.


Must close or hide topmost modal form first

Error 402

The modal form you are trying to close or hide is not on top [image] you need to Unload or Hide all modal forms that are on top of this one before you can continue.  A modal form is a form displayed by the Show method with the style% argument equal to 1.


MDI forms cannot be shown modally

Error 403

You may not set the modal option on MDI forms. (MDIForm.Show 1 is incorrect.)


MDI child forms cannot be shown modally.
MDI child forms cannot be shown modally

Error 404

You may not set the modal option on MDI child forms. (MDIChildForm.Show 1 is incorrect.)


Invalid object reference

Error 420

The object that is referred to is not loaded.


Method not applicable for this object

Error 421

Object.method is referred to, but the method is not appropriate for the object.  For example,  Command1.AddItem produces this error because the AddItem method is used only with a list box or combo box.


Property 'item' not found

Error 422

Control.property or Control(index).property is referred to, but property is not defined for this control or you may have misspelled the name of the property.  To see what properties are defined for this control, search for help on properties, events and objects for complete information on a specific control.


Property or control 'item' not found

Error 423

Form.control or Form.property is referred to, but control or property is not defined for this form, or you may have misspelled the name of the control or property.  To see what properties are defined for a form, search Help for Form for complete information.  To see what controls are on this form, look at the list in the Code window's Object box.


Object required

Error 424

Property.property is referred to [image] you need to specify object.property, where object is either a form or control.


Invalid object use

Error 425

You've attempted an invalid assignment using a form or control.  If you want to assign a value to a property or a property value to a variable, remember to include the property name in the object specification.  For example, Form1.Command1.Caption = "OK" instead of Form1.Command1 = "OK".


Only one MDI form allowed

Error 426

You cannot load a file that contains an MDI form if there is already an MDI form in your project. You must remove the file containing the loaded MDI form before loading another.


Invalid Clipboard format

Error 460

The specified Clipboard format is incompatible with the method being executed.  GetText and SetText can be used only with CF_TEXT or CF_LINK formats.  GetData and SetData can be used only with CF_BITMAP, CF_METAFILEPICT (Windows metafile picture), or CF_DIB (device independent bitmap) formats.

Note

The Clipboard formats, such as CF_TEXT and CF_BITMAP, are global constants that must be set to numerical values found in CONSTANT.TXT.  If you do not initialize these in your code, Visual Basic treats them as variables and initializes them to 0.

See Also

GetFormat


Specified format does not match format of data

Error 461

In a GetData or SetData method, the Clipboard format you specified does not match the actual data.  For example, you might have specified CF_BITMAP for the format, but the data is in the Windows metafile format (CF_METAFILEPICT).  Make sure you specify the correct format for the data.

Note

The Clipboard formats, such as CF_TEXT and CF_BITMAP, are global constants that must be set to numerical values found in CONSTANT.TXT.  If you do not initialize these in your code, Visual Basic treats them as variables and initializes them to 0.

See also

GetFormat


Can't create AutoRedraw image

Error 480

There isn't enough available memory to create a persistent bitmap for automatic redraw of the form or picture.  Make the picture box control or form smaller, or reset the AutoRedraw property and perform your own redraw in the Paint event procedure.


Invalid picture

Error 481

You attempted to assign something to the Picture property of a form or picture box that Visual Basic doesn't recognize as an icon, bitmap, or Windows metafile.


Printer error

Error 482

There is some problem that prevents printing.  Some possible causes are:

You don't have a printer selected from the Windows Control Panel.

Your printer is not online.

Your printer is jammed or out of paper.

You tried to print a form to a printer than can accept only text.


Can't empty Clipboard

Error 520

Another application is using the Clipboard and will not release it to your application.


Can't open Clipboard

Error 521

Another application is using the Clipboard and will not release it to your application.


User defined error
User-defined error

The application has executed the Error n% statement which caused a trappable user-defined error. If the Error statement specifies an error code that is not used by Visual Basic, the message "User-defined error" is displayed.


Out of stack space

Possible Causes:

Too many active Function or Sub calls.  Check that recursive procedures, both event and general, terminate and that they are not nested too deeply.

A cascading event will cause this error.

Local variables (which are stored on the stack) require more local variable space than is available.  Try declaring some variables at the form or module level instead.

User-defined types and fixed-length strings share space with the stack.  Try redefining some of these in other ways that do not use static memory.

Arrays declared in procedures share space with the stack. Declare these arrays in a global module if possible.

Too many nested DoEvents.


Identifier is not an object or user-defined type

Possible causes:

Object.property is referenced, but Object does not exist.  Allowable objects are control names, form names, and project names.  Check that the necessary form is in the project, or check that the name is spelled correctly.

Object.method is referenced, but Object does not exist.  Check that the necessary form or control is loaded.

Form.control is referenced, but Form does not exist.

A variable name cannot contain a period [image] it can contain only letters, numbers, underscores (_), and one type declaration character.


Expression too complex

An expression exceeds certain internal limitations of Visual Basic. Perhaps a numeric expression has too many complicated subexpressions.  Try breaking down the expression by assigning some subexpressions to variables.


Duplicate label

Two program lines have the same number or label.  Each line number or line label in form code or a module must be unique.

Check all the Sub and Function procedure definitions in the form code or module for the duplicate label.

You can use the Find command on the Edit menu to locate the duplicate label.


Conflict between Global variable and global procedure name

The highlighted word is already defined.  To find the other occurrence of the highlighted word, choose Find from the Edit menu and then select All Modules from the Search box.  Before you do the Find, remove the type-declaration character, if there is one, since this error message is produced if the names are the same and the type-declaration characters are different.


Array already dimensioned

Possible causes:

You attempted to change the dimensions of a static array with a ReDim statement [image] only dynamic arrays can be redimensioned.  To define a dynamic array, use a Dim, Global, or Static statement with empty parentheses.

An Option Base statement occurs after dimensions have been set.


Do without Loop

A Do statement is used without a terminating Loop statement.  Check that other control structures within the Do...Loop structure are correctly matched.  For example, a block If without a matching End If inside the Do...Loop structure may produce this error.


DEFType statements must preceed declarations
Deftype statements must precede declarations

Within the Declarations section of a form or module, a Deftype statement must occur on a line before variables are defined.


Sub and Function or variable of the same name

A Sub cannot have the same name as a Function, variable, or constant at the same level of scope.


Argument-count mismatch

A Sub or Function procedure call has an incorrect number of arguments.

Compare the Declare statement for the procedure with the statement calling the Sub or Function or the associated Call statement to make sure the argument list has the same number of items in both cases.

Use the Find command on the Edit menu to locate the Declare statement, or Press SHIFT+F2 to locate the selected procedure definition.


Object must be specified

You specified a method where the target object was not provided. For example if you execute: Print "Hi!" in a global procedure (a non-forms module), the target object (the form) is not available. Form1.Print "Hi!" would be correct (assuming Form1 was visible).


Procedure has the same name as a control

A Sub or Function cannot have the same name as a control.  Use the Find command on the Edit menu to locate the Declare statement or press SHIFT+F2 to locate the selected procedure definition.


File not found: |
File not found: <file name>

The file you referenced could not be found. Make sure you used the correct path name, the file is not marked as hidden, and you have permission to access the file.


File already open: |
File already open: <file name>

You attempted to open a file that is already open. Make sure this (and no other) application has this file open.


Device IO error: |
Device I/O error: <device>

A hardware error has occurred. This may be due to damaged disk media or the I/O device itself.


File already exists: |
File already exists: <file name>

You are trying to create a file that already exists.


Disk full: |
Disk full: <drive>

The disk media you are writing to is full.  Delete some unneeded files or choose another drive to which to write/save.


Bad file name: |
Bad file name: <file name>

The file name used was invalid. When using MS-DOS, you will need to 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 eight characters, and the extension can contain up to three characters.

The name must start with either a letter or number. It can contain any uppercase or lowercase characters  (file names are not case-sensitive) except the following:

period (.)	quotation mark (")
slash (/)	backslash (\)
brackets ([ ])	colon (:)
semicolon (;)	vertical bar (|)
equal sign (=)	comma (,)

The name should not contain any spaces. The following names are reserved and cannot be used for files or directories: CON, AUX, COM1, COM2, COM3, COM4, LPT1, LPT2, LPT3, PRN, and NUL.  Examples of valid file names are LETTER.DOC, MEMO.TXT, BUDGET.92, 12345678.901 and 2NDTRY.RPT.


Too many files: |
Too many files: <file name>

You have too many files open. Microsoft Windows and MS-DOS can only open a limited number of files.  To correct this situation, try to close some other files in this or other running applications. If this does not work, you may need to increase the FILES=nn statement in the CONFIG.SYS file (and reboot your system).


Permission denied: |
Permission denied: <file name>

You do not have permission to access this file. This may be due to file attributes or other permission violations. For example, you may have tried to write to or erase a file marked as read-only.


Disk-media error: |
Disk-media error: <device>

A hardware error has occurred. This may be due to damaged disk media or the I/O device itself.


Path access error: |
Path access error: <path name>

The path (which designates the directory location for files) could not be accessed.


Path not found: |
Path not found: <path name>

The path (which designates the directory location for files) could not be found.


Text would be too long.  Edit prevented

The current line is too long to edit.  The maximum length of the line is dependent upon the current state of Visual Basic and of the operating system, but is generally 1023 characters.

When working with long strings, it is usually better to use string variables and concatenation to increase the text incrementally.


Duplicate procedure name

A procedure with this name already exists [image] you can use the Find command on the Edit menu (or SHIFT+F2) to help locate the duplicate procedure.  Before you do this, remove the type-declaration character, if there is one, since a conflict occurs if the names are the same and the type-declaration characters are different.


Control must be same type as rest of array

You attempted to give a control the same name as an existing control array of a different type.  All controls in a control array must be the same type.


Can't clear INDEX property without changing CTLNAME
Can't clear Index property without changing name

This control is part of a control array.  If you want to delete its index, and thus delete it from the control array, you must first rename it with a unique name.


| is a control name
<name> is a control name

A control already has this name.  A form cannot have the same name as a control in the same project.


Menu subitem skipped a level

Menu levels must be contiguous.  Menus can be cascaded to five levels.  An item at level 2 can open a pop-up menu at level 3, and an item at level 3 can open a pop-up menu at level 4.

In the Menu Design window, make sure menu items are indented only one level beyond the previous level.


Menu control must have a name

A menu item has been created without assigning a name to it.  Unlike other controls in Visual Basic, menu controls require you to assign names as the control is created, since Visual Basic does not supply a default name for menu items.


Menu control array element must have an index

An item has been added to a menu control array without assigning an index to the item.  Unlike other control arrays in Visual Basic, menu control arrays require you to assign indices as the item is created, since Visual Basic does not supply a default index for menu control array items.


Menu control array indices must be in order
Menu control array indices must be in ascending order

An index assigned to an item in a menu control array is out of order with the other items.  The indices of a menu control array do not have to be contiguous (e.g.,  they could be 1, 3, and 5), but they must be in ascending order according to their location on the menu.  Get the next available index number before assigning a number to the index.


Menu control array elements must be contiguous and within the same submenu

You have tried to add an item to a control array, where the other items in the array are adjacent to the current item.  The indices of the items in a menu control array do not have to be contiguous (i.e.,  2, 3, 4), but they must be in ascending order according to their location on the menu.  The items in a menu control array, however, must be located next to each other within the same menu or pop-up menu.


1000Remote data not accessible. Start application '|'?
Remote data not accessible.  Start application <name>?

No running application recognized the LinkTopic you specified.

Possible causes:

The application you specified in the LinkTopic property is not running.  Choose OK and Visual Basic will attempt to run the application.

The application you specified in the LinkTopic property is running, but it does not recognize the topic you specified.  Choose OK and Visual Basic will attempt to run another instance of the application and have it open the topic you specified.

The application you specified in the LinkTopic property is running, but is ignoring DDE messages.  Consult the documentation for that application to see how to make it perform DDE.  (In Microsoft Excel, for example, you must turn off the "Ignore Remote Requests" option in the Options Workspace dialog box.)

The application or topic you specified in the LinkTopic property is not valid.  Choose Cancel and set the LinkTopic property to a valid application and topic.